1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
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.
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.
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/>.
24 from fba import blacklist
27 from fba import federation
29 # Found info from node, such as nodeinfo URL, detection mode that needs to be
30 # written to database. Both arrays must be filled at the same time or else
31 # update_data() will fail
33 # Detection mode: 'AUTO_DISCOVERY', 'STATIC_CHECKS' or 'GENERATOR'
34 # NULL means all detection methods have failed (maybe still reachable instance)
35 "detection_mode" : {},
40 # Last fetched instances
41 "last_instance_fetch": {},
46 # Last nodeinfo (fetched)
49 "last_status_code" : {},
51 "last_error_details" : {},
52 # Whether CSRF tokens are present
56 def set_data(key: str, domain: str, value: any):
57 # DEBUG: print(f"DEBUG: key='{key}',domain='{domain}',value[]='{type(value)}' - CALLED!")
58 if not isinstance(key, str):
59 raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
61 raise ValueError("Parameter 'key' is empty")
62 elif not isinstance(domain, str):
63 raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
65 raise ValueError("Parameter 'domain' is empty")
66 elif not key in _pending:
67 raise ValueError(f"key='{key}' not found in _pending")
68 elif not fba.is_primitive(value):
69 raise ValueError(f"value[]='{type(value)}' is not a primitive type")
72 _pending[key][domain] = value
74 # DEBUG: print("DEBUG: EXIT!")
76 def has_pending_instance_data(domain: str) -> bool:
77 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
78 if not isinstance(domain, str):
79 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
81 raise ValueError("Parameter 'domain' is empty")
85 # DEBUG: print(f"DEBUG: key='{key}',domain='{domain}',_pending[key]()='{len(_pending[key])}'")
86 if domain in _pending[key]:
90 # DEBUG: print(f"DEBUG: has_pending='{has_pending}' - EXIT!")
93 def update_data(domain: str):
94 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
95 if not isinstance(domain, str):
96 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
98 raise ValueError("Parameter 'domain' is empty")
99 elif not has_pending_instance_data(domain):
100 raise Exception(f"Domain '{domain}' has no pending instance data, but function invoked")
102 # DEBUG: print(f"DEBUG: Updating instance data for domain='{domain}' ...")
106 # DEBUG: print("DEBUG: key:", key)
107 if domain in _pending[key]:
108 # DEBUG: print(f"DEBUG: Adding '{_pending[key][domain]}' for key='{key}' ...")
109 fields.append(_pending[key][domain])
110 sql_string += f" {key} = ?,"
112 fields.append(time.time())
113 fields.append(domain)
116 raise ValueError(f"No fields have been set, but method invoked, domain='{domain}'")
118 # DEBUG: print(f"DEBUG: sql_string='{sql_string}',fields()={len(fields)}")
119 sql_string = "UPDATE instances SET" + sql_string + " last_updated = ? WHERE domain = ? LIMIT 1"
120 # DEBUG: print("DEBUG: sql_string:", sql_string)
123 # DEBUG: print("DEBUG: Executing SQL:", sql_string)
124 fba.cursor.execute(sql_string, fields)
126 # DEBUG: print(f"DEBUG: Success! (rowcount={fba.cursor.rowcount })")
127 if fba.cursor.rowcount == 0:
128 # DEBUG: print(f"DEBUG: Did not update any rows: domain='{domain}',fields()={len(fields)} - EXIT!")
131 # DEBUG: print("DEBUG: Committing changes ...")
132 fba.connection.commit()
134 # DEBUG: print("DEBUG: Deleting _pending for domain:", domain)
137 # DEBUG: print("DEBUG: Deleting key:", key)
138 del _pending[key][domain]
142 except BaseException as exception:
143 print(f"ERROR: failed SQL query: domain='{domain}',sql_string='{sql_string}',exception[{type(exception)}]:'{str(exception)}'")
146 # DEBUG: print("DEBUG: EXIT!")
148 def update_last_instance_fetch(domain: str):
149 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
150 if not isinstance(domain, str):
151 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
153 raise ValueError("Parameter 'domain' is empty")
155 # DEBUG: print("DEBUG: Updating last_instance_fetch for domain:", domain)
156 set_data("last_instance_fetch", domain, time.time())
158 # Running pending updated
159 # DEBUG: print(f"DEBUG: Invoking update_data({domain}) ...")
162 # DEBUG: print("DEBUG: EXIT!")
164 def update_last_blocked(domain: str):
165 if not isinstance(domain, str):
166 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
168 raise ValueError("Parameter 'domain' is empty")
170 # DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
171 set_data("last_blocked", domain, time.time())
173 # Running pending updated
174 # DEBUG: print(f"DEBUG: Invoking update_data({domain}) ...")
177 # DEBUG: print("DEBUG: EXIT!")
179 def add(domain: str, origin: str, command: str, path: str = None):
180 # DEBUG: print(f"DEBUG: domain='{domain}',origin='{origin}',command='{command}',path='{path}' - CALLED!")
181 if not isinstance(domain, str):
182 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
184 raise ValueError("Parameter 'domain' is empty")
185 elif not isinstance(origin, str) and origin is not None:
186 raise ValueError(f"origin[]={type(origin)} is not 'str'")
188 raise ValueError("Parameter 'origin' is empty")
189 elif not isinstance(command, str):
190 raise ValueError(f"command[]={type(command)} is not 'str'")
192 raise ValueError("Parameter 'command' is empty")
193 elif not validators.domain(domain.split("/")[0]):
194 raise ValueError(f"Bad domain name='{domain}'")
195 elif origin is not None and not validators.domain(origin.split("/")[0]):
196 raise ValueError(f"Bad origin name='{origin}'")
197 elif blacklist.is_blacklisted(domain):
198 raise Exception(f"domain='{domain}' is blacklisted, but method invoked")
199 elif domain.find("/profile/") > 0 or domain.find("/users/") > 0:
200 raise Exception(f"domain='{domain}' is a single user")
202 # DEBUG: print("DEBUG: domain,origin,command,path:", domain, origin, command, path)
203 software = federation.determine_software(domain, path)
205 # DEBUG: print("DEBUG: Determined software:", software)
206 if software == "lemmy" and domain.find("/c/") > 0:
207 domain = domain.split("/c/")[0]
208 if is_registered(domain):
209 print(f"WARNING: domain='{domain}' already registered after cutting off user part. - EXIT!")
212 print(f"INFO: Adding instance domain='{domain}' (origin='{origin}',software='{software}')")
215 "INSERT INTO instances (domain, origin, command, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
220 fba.get_hash(domain),
226 cache.set_sub_key("is_registered", domain, True)
228 if has_pending_instance_data(domain):
229 # DEBUG: print(f"DEBUG: domain='{domain}' has pending nodeinfo being updated ...")
230 set_data("last_status_code" , domain, None)
231 set_data("last_error_details", domain, None)
234 except BaseException as exception:
235 update_last_error(domain, exception)
236 raise Exception(f"ERROR: failed SQL query: domain='{domain}',exception[{type(exception)}]:'{str(exception)}'") from exception
238 # DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
239 update_last_nodeinfo(domain)
241 # DEBUG: print("DEBUG: EXIT!")
243 def update_last_nodeinfo(domain: str):
244 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
245 if not isinstance(domain, str):
246 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
248 raise ValueError("Parameter 'domain' is empty")
250 # DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
251 set_data("last_nodeinfo", domain, time.time())
252 set_data("last_updated" , domain, time.time())
254 # Running pending updated
255 # DEBUG: print(f"DEBUG: Invoking update_data({domain}) ...")
258 # DEBUG: print("DEBUG: EXIT!")
260 def update_last_error(domain: str, error: dict):
261 print("DEBUG: domain,error[]:", domain, type(error))
262 if not isinstance(domain, str):
263 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
265 raise ValueError("Parameter 'domain' is empty")
267 print("DEBUG: BEFORE error[]:", type(error))
268 if isinstance(error, BaseException) or isinstance(error, json.decoder.JSONDecodeError):
269 error = f"error[{type(error)}]='{str(error)}'"
270 print("DEBUG: AFTER error[]:", type(error))
272 if isinstance(error, str):
273 print(f"DEBUG: Setting last_error_details='{error}'")
274 set_data("last_status_code" , domain, 999)
275 set_data("last_error_details", domain, error)
276 elif isinstance(error, requests.models.Response):
277 print(f"DEBUG: Setting last_error_details='{error.reason}'")
278 set_data("last_status_code" , domain, error.status_code)
279 set_data("last_error_details", domain, error.reason)
281 print(f"DEBUG: Setting last_error_details='{error['error_message']}'")
282 set_data("last_status_code" , domain, error["status_code"])
283 set_data("last_error_details", domain, error["error_message"])
285 # Running pending updated
286 print(f"DEBUG: Invoking update_data({domain}) ...")
289 fba.log_error(domain, error)
291 print("DEBUG: EXIT!")
293 def is_registered(domain: str) -> bool:
294 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
295 if not isinstance(domain, str):
296 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
298 raise ValueError("Parameter 'domain' is empty")
300 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
301 if not cache.key_exists("is_registered"):
302 # DEBUG: print("DEBUG: Cache for 'is_registered' not initialized, fetching all rows ...")
304 fba.cursor.execute("SELECT domain FROM instances")
307 cache.set_all("is_registered", fba.cursor.fetchall(), True)
308 except BaseException as exception:
309 update_last_error(domain, exception)
310 raise Exception(f"ERROR: failed SQL query: domain='{domain}',exception[{type(exception)}]:'{str(exception)}'") from exception
313 registered = cache.sub_key_exists("is_registered", domain)
315 # DEBUG: print(f"DEBUG: registered='{registered}' - EXIT!")