]> git.mxchange.org Git - fba.git/blob - fba/models/blocks.py
Continued:
[fba.git] / fba / models / blocks.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 import logging
18
19 import time
20
21 from fba import database
22
23 from fba.helpers import blacklist
24 from fba.helpers import domain as domain_helper
25 from fba.helpers import tidyup
26
27 logging.basicConfig(level=logging.INFO)
28 logger = logging.getLogger(__name__)
29
30 def update_reason(reason: str, blocker: str, blocked: str, block_level: str):
31     logger.debug("reason='%s',blocker='%s',blocked='%s',block_level='%s' - CALLED!", reason, blocker, blocked, block_level)
32     domain_helper.raise_on(blocker)
33     domain_helper.raise_on(blocked)
34
35     if not isinstance(reason, str) and reason is not None:
36         raise ValueError(f"Parameter reason[]='{type(reason)}' is not of type 'str'")
37     elif not isinstance(block_level, str):
38         raise ValueError(f"Parameter block_level[]='{type(block_level)}' is not of type 'str'")
39     elif block_level == "":
40         raise ValueError("Parameter 'block_level' is empty")
41     elif block_level in ["accept", "suspend", "silence", "nsfw", "quarantined_instances"]:
42         raise ValueError(f"block_level='{block_level}' is not wanted.")
43     elif blacklist.is_blacklisted(blocker):
44         raise Exception(f"blocker='{blocker}' is blacklisted but function invoked")
45     elif blacklist.is_blacklisted(blocked):
46         raise Exception(f"blocked='{blocked}' is blacklisted but function invoked")
47     elif not is_instance_blocked(blocker, blocked, block_level):
48         raise Exception(f"blocker='{blocker}',blocked='{blocked}',block_level='{block_level}' is not registered but function is invoked")
49
50     logger.debug("Updating block reason='%s',blocker='%s',blocked='%s',block_level='%s'", reason, blocker, blocked, block_level)
51     database.cursor.execute(
52         "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND (reason IS NULL OR reason = '') LIMIT 1",
53         [
54             reason,
55             time.time(),
56             blocker,
57             blocked,
58             block_level
59         ])
60
61     logger.debug("EXIT!")
62
63 def update_last_seen(blocker: str, blocked: str, block_level: str):
64     logger.debug("blocker='%s',blocked='%s',block_level='%s' - CALLED!", blocker, blocked, block_level)
65     domain_helper.raise_on(blocker)
66     domain_helper.raise_on(blocked)
67
68     if not isinstance(block_level, str):
69         raise ValueError(f"Parameter block_level[]='{type(block_level)}' is not of type 'str'")
70     elif block_level == "":
71         raise ValueError("Parameter 'block_level' is empty")
72     elif block_level in ["accept", "suspend", "silence", "nsfw", "quarantined_instances"]:
73         raise ValueError(f"blocked='{blocked}' has unwanted block_level='{block_level}'")
74     elif blacklist.is_blacklisted(blocker):
75         raise Exception(f"blocker='{blocker}' is blacklisted but function invoked")
76     elif blacklist.is_blacklisted(blocked):
77         raise Exception(f"blocked='{blocked}' is blacklisted but function invoked")
78     elif not is_instance_blocked(blocker, blocked, block_level):
79         raise Exception(f"blocker='{blocker}',blocked='{blocked}',block_level='{block_level}' is not registered but function is invoked")
80
81     database.cursor.execute(
82         "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? LIMIT 1",
83         [
84             time.time(),
85             blocker,
86             blocked,
87             block_level
88         ])
89
90     logger.debug("EXIT!")
91
92 def is_instance_blocked(blocker: str, blocked: str, block_level: str = None) -> bool:
93     logger.debug("blocker='%s',blocked='%s',block_level='%s' - CALLED!", blocker, blocked, block_level)
94     domain_helper.raise_on(blocker)
95     domain_helper.raise_on(blocked)
96
97     if not isinstance(block_level, str) and block_level is not None:
98         raise ValueError(f"Parameter block_level[]='{type(block_level)}' is not of type 'str'")
99     elif block_level == "":
100         raise ValueError("Parameter 'block_level' is empty")
101     elif block_level in ["accept", "suspend", "silence", "nsfw", "quarantined_instances"]:
102         raise ValueError(f"blocked='{blocked}' has unwanted block_level='{block_level}'")
103     elif blacklist.is_blacklisted(blocker):
104         raise Exception(f"blocker='{blocker}' is blacklisted but function invoked")
105     elif blacklist.is_blacklisted(blocked):
106         raise Exception(f"blocked='{blocked}' is blacklisted but function invoked")
107
108     if block_level is None:
109         database.cursor.execute(
110             "SELECT * FROM blocks WHERE blocker = ? AND blocked = ? LIMIT 1",
111             [
112                 blocker,
113                 blocked
114             ]
115          )
116     else:
117         database.cursor.execute(
118             "SELECT * FROM blocks WHERE blocker = ? AND blocked = ? AND block_level = ? LIMIT 1",
119             [
120                 blocker,
121                 blocked,
122                 block_level
123             ]
124         )
125
126     is_blocked = database.cursor.fetchone() is not None
127
128     logger.debug("is_blocked='%s' - EXIT!", is_blocked)
129     return is_blocked
130
131 def add(blocker: str, blocked: str, reason: str, block_level: str):
132     logger.debug("blocker='%s',blocked='%s',reason='%s',block_level='%s' - CALLED!", blocker, blocked, reason, block_level)
133     domain_helper.raise_on(blocker)
134     domain_helper.raise_on(blocked)
135
136     if not isinstance(block_level, str):
137         raise ValueError(f"Parameter block_level[]='{type(block_level)}' is not of type 'str'")
138     elif block_level == "":
139         raise ValueError("Parameter 'block_level' is empty")
140     elif block_level in ["accept", "suspend", "silence", "nsfw", "quarantined_instances"]:
141         raise ValueError(f"blocked='{blocked}' has unwanted block_level='{block_level}'")
142     elif blacklist.is_blacklisted(blocker):
143         raise Exception(f"blocker='{blocker}' is blacklisted but function invoked")
144     elif blacklist.is_blacklisted(blocked):
145         raise Exception(f"blocked='{blocked}' is blacklisted but function invoked")
146     elif reason is not None and reason == "":
147         raise Exception(f"blocker='{blocker}',blocked='{blocked}',block_level='{block_level}' has empty (not 'None') block reason set")
148
149     logger.debug("reason='%s' - BEFORE!")
150     reason = tidyup.reason(reason) if reason is not None and reason != "" else None
151     logger.debug("reason='%s' - AFTER!")
152
153     logger.info("New block: blocker='%s',blocked='%s',reason='%s',block_level='%s'", blocker, blocked, reason, block_level)
154
155     database.cursor.execute(
156         "INSERT INTO blocks (blocker, blocked, reason, block_level, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?)",
157         [
158              blocker,
159              blocked,
160              reason,
161              block_level,
162              time.time(),
163              time.time()
164         ])
165
166     logger.debug("EXIT!")
167
168 def valid(value: str, column: str) -> bool:
169     logger.debug("value='%s' - CALLED!", value)
170
171     if not isinstance(value, str):
172         raise ValueError(f"Parameter value[]='{type(value)}' is not of type 'str'")
173     elif value == "":
174         raise ValueError("Parameter 'value' is empty")
175     elif not isinstance(column, str):
176         raise ValueError(f"Parameter column[]='{type(column)}' is not of type 'str'")
177     elif column == "":
178         raise ValueError("Parameter 'column' is empty")
179
180     # Query database
181     database.cursor.execute(
182         f"SELECT {column} FROM blocks WHERE {column} = ? LIMIT 1", [value]
183     )
184
185     is_valid = database.cursor.fetchone() is not None
186
187     logger.debug("is_valid='%s' - EXIT!", is_valid)
188     return is_valid
189
190 def translate_idnas(rows: list, column: str):
191     logger.debug("rows[]='%s' - CALLED!", type(rows))
192
193     if not isinstance(rows, list):
194         raise ValueError(f"rows[]='{type(rows)}' is not of type 'list'")
195     elif len(rows) == 0:
196         raise ValueError("Parameter 'rows' is an empty list")
197     elif not isinstance(column, str):
198         raise ValueError(f"column='{type(column)}' is not of type 'str'")
199     elif column not in ["blocker", "blocked"]:
200         raise ValueError(f"column='{column}' is not supported")
201
202     logger.info("Checking/converting %d domain names ...", len(rows))
203     for row in rows:
204         logger.debug("row[]='%s'", type(row))
205
206         translated = row[column].encode("idna").decode("utf-8")
207         logger.debug("translated='%s',row[%s]='%s'", translated, column, row[column])
208
209         if translated != row[column]:
210             logger.info("Translated row[%s]='%s' to '%s'", column, row[column], translated)
211             database.cursor.execute(f"UPDATE blocks SET {column} = ? WHERE {column} = ?", [translated, row[column]])
212
213             logger.debug("Invoking commit() ...")
214             database.connection.commit()
215
216     logger.debug("EXIT!")
217
218 def alias_block_level(block_level: str) -> str:
219     logger.debug("block_level='%s' - CALLED!", block_level)
220
221     if not isinstance(block_level, str):
222         raise ValueError(f"Parameter block_level[]='{type(block_level)}' is not of type 'str'")
223     elif block_level in ["accept", "accepted"]:
224         raise ValueError(f"Parameter block_level='{block_level}' is not accepted but function was invoked")
225     elif block_level == "silence":
226         logger.debug("Block level 'silence' has been changed to 'silenced'")
227         block_level = "silenced"
228     elif block_level == "suspend":
229         logger.debug("Block level 'suspend' has been changed to 'suspended'")
230         block_level = "suspended"
231     elif block_level == "nsfw":
232         logger.debug("Block level 'nsfw' has been changed to 'media_nsfw'")
233         block_level = "media_nsfw"
234     elif block_level == "quarantined_instances":
235         logger.debug("Block level 'quarantined_instances' has been changed to 'quarantined'")
236         block_level = "quarantined"
237
238     logger.debug("block_level='%s' - EXIT!", block_level)
239     return block_level