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/>.
29 from fba import blacklist
30 from fba import blocks
32 from fba import config
34 from fba import instances
36 from fba.federation import *
38 def check_instance(args: argparse.Namespace) -> int:
39 # DEBUG: print(f"DEBUG: args.domain='{args.domain}' - CALLED!")
41 if not validators.domain(args.domain):
42 print(f"WARNING: args.domain='{args.domain}' is not valid")
44 elif blacklist.is_blacklisted(args.domain):
45 print(f"WARNING: args.domain='{args.domain}' is blacklisted")
47 elif instances.is_registered(args.domain):
48 print(f"WARNING: args.domain='{args.domain}' is already registered")
51 print(f"INFO: args.domain='{args.domain}' is not known")
53 # DEBUG: print(f"DEBUG: status={status} - EXIT!")
56 def fetch_bkali(args: argparse.Namespace):
57 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
60 fetched = fba.post_json_api("gql.api.bka.li", "/v1/graphql", json.dumps({
61 "query": "query domainlist {nodeinfo(order_by: {domain: asc}) {domain}}"
64 # DEBUG: print(f"DEBUG: fetched({len(fetched)})[]='{type(fetched)}'")
66 raise Exception("WARNING: Returned no records")
67 elif not "data" in fetched:
68 raise Exception(f"WARNING: fetched()={len(fetched)} does not contain key 'data'")
69 elif not "nodeinfo" in fetched["data"]:
70 raise Exception(f"WARNING: fetched()={len(fetched['data'])} does not contain key 'nodeinfo'")
72 for entry in fetched["data"]["nodeinfo"]:
73 # DEBUG: print(f"DEBUG: entry['{type(entry)}']='{entry}'")
74 if not "domain" in entry:
75 print(f"WARNING: entry does not contain 'domain' - SKIPPED!")
77 elif not validators.domain(entry["domain"]):
78 print(f"WARNING: domain='{entry['domain']}' is not a valid domain - SKIPPED!")
80 elif blacklist.is_blacklisted(entry["domain"]):
81 # DEBUG: print(f"DEBUG: domain='{entry['domain']}' is blacklisted - SKIPPED!")
83 elif instances.is_registered(entry["domain"]):
84 # DEBUG: print(f"DEBUG: domain='{entry['domain']}' is already registered - SKIPPED!")
87 # DEBUG: print(f"DEBUG: Adding domain='{entry['domain']}' ...")
88 domains.append(entry["domain"])
90 except BaseException as e:
91 print(f"ERROR: Cannot fetch graphql,exception[{type(e)}]:'{str(e)}'")
94 # DEBUG: print(f"DEBUG: domains()={len(domains)}")
98 print(f"INFO: Adding {len(domains)} new instances ...")
99 for domain in domains:
100 print(f"INFO: Fetching instances from domain='{domain}' ...")
101 fba.fetch_instances(domain, None, None, inspect.currentframe().f_code.co_name)
103 # DEBUG: print("DEBUG: EXIT!")
105 def fetch_blocks(args: argparse.Namespace):
106 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
107 if args.domain != None and args.domain != "":
108 # DEBUG: print(f"DEBUG: args.domain='{args.domain}' - checking ...")
109 if not validators.domain(args.domain):
110 print(f"WARNING: domain='{args.domain}' is not valid.")
112 elif blacklist.is_blacklisted(args.domain):
113 print(f"WARNING: domain='{args.domain}' is blacklisted, won't check it!")
115 elif not instances.is_registered(args.domain):
116 print(f"WARNING: domain='{args.domain}' is not registered, please run ./fba.py fetch_instances {args.domain} first.")
121 if args.domain != None and args.domain != "":
122 # Re-check single domain
124 "SELECT domain, software, origin, nodeinfo_url FROM instances WHERE software IN ('pleroma', 'mastodon', 'friendica', 'misskey', 'bookwyrm', 'takahe') AND domain = ?", [args.domain]
127 # Re-check after "timeout" (aka. minimum interval)
129 "SELECT domain, software, origin, nodeinfo_url FROM instances WHERE software IN ('pleroma', 'mastodon', 'friendica', 'misskey', 'bookwyrm', 'takahe') AND (last_blocked IS NULL OR last_blocked < ?) ORDER BY rowid DESC", [time.time() - config.get("recheck_block")]
132 rows = fba.cursor.fetchall()
133 print(f"INFO: Checking {len(rows)} entries ...")
134 for blocker, software, origin, nodeinfo_url in rows:
135 # DEBUG: print("DEBUG: BEFORE blocker,software,origin,nodeinfo_url:", blocker, software, origin, nodeinfo_url)
137 blocker = fba.tidyup_domain(blocker)
138 # DEBUG: print("DEBUG: AFTER blocker,software:", blocker, software)
141 print("WARNING: blocker is now empty!")
143 elif blacklist.is_blacklisted(blocker):
144 print(f"WARNING: blocker='{blocker}' is blacklisted now!")
147 # DEBUG: print(f"DEBUG: blocker='{blocker}'")
148 instances.update_last_blocked(blocker)
150 if software == "pleroma":
151 print(f"INFO: blocker='{blocker}',software='{software}'")
152 pleroma.fetch_blocks(blocker, origin, nodeinfo_url)
153 elif software == "mastodon":
154 print(f"INFO: blocker='{blocker}',software='{software}'")
155 mastodon.fetch_blocks(blocker, origin, nodeinfo_url)
156 elif software == "friendica" or software == "misskey":
157 print(f"INFO: blocker='{blocker}',software='{software}'")
159 if software == "friendica":
160 json = fba.fetch_friendica_blocks(blocker)
161 elif software == "misskey":
162 json = misskey.fetch_blocks(blocker)
164 print(f"INFO: Checking {len(json.items())} entries from blocker='{blocker}',software='{software}' ...")
165 for block_level, blocklist in json.items():
166 # DEBUG: print("DEBUG: blocker,block_level,blocklist():", blocker, block_level, len(blocklist))
167 block_level = fba.tidyup_domain(block_level)
168 # DEBUG: print("DEBUG: AFTER-block_level:", block_level)
169 if block_level == "":
170 print("WARNING: block_level is empty, blocker:", blocker)
173 # DEBUG: print(f"DEBUG: Checking {len(blocklist)} entries from blocker='{blocker}',software='{software}',block_level='{block_level}' ...")
174 for block in blocklist:
175 blocked, reason = block.values()
176 # DEBUG: print(f"DEBUG: blocked='{blocked}',reason='{reason}' - BEFORE!")
177 blocked = fba.tidyup_domain(blocked)
178 reason = fba.tidyup_reason(reason) if reason != None else None
179 # DEBUG: print(f"DEBUG: blocked='{blocked}',reason='{reason}' - AFTER!")
182 print("WARNING: blocked is empty:", blocker)
184 elif blacklist.is_blacklisted(blocked):
185 # DEBUG: print(f"DEBUG: blocked='{blocked}' is blacklisted - skipping!")
187 elif blocked.count("*") > 0:
188 # Some friendica servers also obscure domains without hash
190 "SELECT domain, origin, nodeinfo_url FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("*", "_")]
193 searchres = fba.cursor.fetchone()
195 if searchres == None:
196 print(f"WARNING: Cannot deobsfucate blocked='{blocked}' - SKIPPED!")
199 blocked = searchres[0]
200 origin = searchres[1]
201 nodeinfo_url = searchres[2]
202 elif blocked.count("?") > 0:
203 # Some obscure them with question marks, not sure if that's dependent on version or not
205 "SELECT domain, origin, nodeinfo_url FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("?", "_")]
208 searchres = fba.cursor.fetchone()
210 if searchres == None:
211 print(f"WARNING: Cannot deobsfucate blocked='{blocked}' - SKIPPED!")
214 blocked = searchres[0]
215 origin = searchres[1]
216 nodeinfo_url = searchres[2]
217 elif not validators.domain(blocked):
218 print(f"WARNING: blocked='{blocked}',software='{software}' is not a valid domain name - skipped!")
221 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
222 if not validators.domain(blocked):
223 print(f"WARNING: blocked='{blocked}',software='{software}' is not a valid domain name - skipped!")
225 elif not instances.is_registered(blocked):
226 # DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, blocker)
227 instances.add(blocked, blocker, inspect.currentframe().f_code.co_name, nodeinfo_url)
229 if not blocks.is_instance_blocked(blocker, blocked, block_level):
230 blocks.add_instance(blocker, blocked, reason, block_level)
232 if block_level == "reject":
238 # DEBUG: print(f"DEBUG: Updating block last seen and reason for blocker='{blocker}',blocked='{blocked}' ...")
239 blocks.update_last_seen(blocker, blocked, block_level)
240 blocks.update_reason(reason, blocker, blocked, block_level)
242 # DEBUG: print("DEBUG: Committing changes ...")
243 fba.connection.commit()
244 except Exception as e:
245 print(f"ERROR: blocker='{blocker}',software='{software}',exception[{type(e)}]:'{str(e)}'")
247 print("WARNING: Unknown software:", blocker, software)
249 if config.get("bot_enabled") and len(blockdict) > 0:
250 send_bot_post(blocker, blockdict)
254 # DEBUG: print("DEBUG: EXIT!")
256 def fetch_cs(args: argparse.Namespace):
257 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
264 doc = bs4.BeautifulSoup(
265 fba.get_response("meta.chaos.social", "/federation", fba.headers, (config.get("connection_timeout"), config.get("read_timeout"))).text,
268 # DEBUG: print(f"DEBUG: doc()={len(doc)}[]={type(doc)}")
269 silenced = doc.find("h2", {"id": "silenced-instances"}).findNext("table")
271 # DEBUG: print(f"DEBUG: silenced[]={type(silenced)}")
272 domains["silenced"] = domains["silenced"] + fba.find_domains(silenced)
273 blocked = doc.find("h2", {"id": "blocked-instances"}).findNext("table")
275 # DEBUG: print(f"DEBUG: blocked[]={type(blocked)}")
276 domains["blocked"] = domains["blocked"] + fba.find_domains(blocked)
278 except BaseException as e:
279 print(f"ERROR: Cannot fetch from meta.chaos.social,exception[{type(e)}]:'{str(e)}'")
282 # DEBUG: print(f"DEBUG: domains()={len(domains)}")
286 print(f"INFO: Adding {len(domains)} new instances ...")
287 for block_level in domains:
288 # DEBUG: print(f"DEBUG: block_level='{block_level}'")
290 for row in domains[block_level]:
291 # DEBUG: print(f"DEBUG: row='{row}'")
292 if not instances.is_registered(row["domain"]):
293 print(f"INFO: Fetching instances from domain='{row['domain']}' ...")
294 fba.fetch_instances(row["domain"], None, None, inspect.currentframe().f_code.co_name)
296 if not blocks.is_instance_blocked('chaos.social', row["domain"], block_level):
297 # DEBUG: print(f"DEBUG: domain='{row['domain']}',block_level='{block_level}' blocked by chaos.social, adding ...")
298 blocks.add_instance('chaos.social', row["domain"], row["reason"], block_level)
300 # DEBUG: print("DEBUG: Committing changes ...")
301 fba.connection.commit()
303 # DEBUG: print("DEBUG: EXIT!")
305 def fetch_fba_rss(args: argparse.Namespace):
306 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
310 print(f"INFO: Fetch FBA-specific RSS args.feed='{args.feed}' ...")
311 response = fba.get_url(args.feed, fba.headers, (config.get("connection_timeout"), config.get("read_timeout")))
313 # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code='{response.status_code}',response.text()={len(response.text)}")
314 if response.ok and response.status_code < 300 and len(response.text) > 0:
315 # DEBUG: print(f"DEBUG: Parsing RSS feed ...")
316 rss = atoma.parse_rss_bytes(response.content)
318 # DEBUG: print(f"DEBUG: rss[]={type(rss)}")
319 for item in rss.items:
320 # DEBUG: print(f"DEBUG: item={item}")
321 domain = item.link.split("=")[1]
323 if blacklist.is_blacklisted(domain):
324 # DEBUG: print(f"DEBUG: domain='{domain}' is blacklisted - SKIPPED!")
326 elif domain in domains:
327 # DEBUG: print(f"DEBUG: domain='{domain}' is already added - SKIPPED!")
329 elif instances.is_registered(domain):
330 # DEBUG: print(f"DEBUG: domain='{domain}' is already registered - SKIPPED!")
333 # DEBUG: print(f"DEBUG: Adding domain='{domain}'")
334 domains.append(domain)
336 except BaseException as e:
337 print(f"ERROR: Cannot fetch feed='{feed}',exception[{type(e)}]:'{str(e)}'")
340 # DEBUG: print(f"DEBUG: domains()={len(domains)}")
344 print(f"INFO: Adding {len(domains)} new instances ...")
345 for domain in domains:
346 print(f"INFO: Fetching instances from domain='{domain}' ...")
347 fba.fetch_instances(domain, None, None, inspect.currentframe().f_code.co_name)
349 # DEBUG: print("DEBUG: EXIT!")
351 def fetch_fbabot_atom(args: argparse.Namespace):
352 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
353 feed = "https://ryona.agency/users/fba/feed.atom"
357 print(f"INFO: Fetching ATOM feed='{feed}' from FBA bot account ...")
358 response = fba.get_url(feed, fba.headers, (config.get("connection_timeout"), config.get("read_timeout")))
360 # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code='{response.status_code}',response.text()={len(response.text)}")
361 if response.ok and response.status_code < 300 and len(response.text) > 0:
362 # DEBUG: print(f"DEBUG: Parsing ATOM feed ...")
363 atom = atoma.parse_atom_bytes(response.content)
365 # DEBUG: print(f"DEBUG: atom[]={type(atom)}")
366 for entry in atom.entries:
367 # DEBUG: print(f"DEBUG: entry[]={type(entry)}")
368 doc = bs4.BeautifulSoup(entry.content.value, "html.parser")
369 # DEBUG: print(f"DEBUG: doc[]={type(doc)}")
370 for element in doc.findAll("a"):
371 for href in element["href"].split(","):
372 # DEBUG: print(f"DEBUG: href[{type(href)}]={href}")
373 domain = fba.tidyup_domain(href)
375 # DEBUG: print(f"DEBUG: domain='{domain}'")
376 if blacklist.is_blacklisted(domain):
377 # DEBUG: print(f"DEBUG: domain='{domain}' is blacklisted - SKIPPED!")
379 elif domain in domains:
380 # DEBUG: print(f"DEBUG: domain='{domain}' is already added - SKIPPED!")
382 elif instances.is_registered(domain):
383 # DEBUG: print(f"DEBUG: domain='{domain}' is already registered - SKIPPED!")
386 # DEBUG: print(f"DEBUG: Adding domain='{domain}',domains()={len(domains)}")
387 domains.append(domain)
389 except BaseException as e:
390 print(f"ERROR: Cannot fetch feed='{feed}',exception[{type(e)}]:'{str(e)}'")
393 # DEBUG: print(f"DEBUG: domains({len(domains)})={domains}")
397 print(f"INFO: Adding {len(domains)} new instances ...")
398 for domain in domains:
399 print(f"INFO: Fetching instances from domain='{domain}' ...")
400 fba.fetch_instances(domain, None, None, inspect.currentframe().f_code.co_name)
402 # DEBUG: print("DEBUG: EXIT!")
404 def fetch_instances(args: argparse.Namespace):
405 # DEBUG: print(f"DEBUG: args[]={type(args)} - CALLED!")
409 fba.fetch_instances(args.domain, None, None, inspect.currentframe().f_code.co_name)
412 # DEBUG: print(f"DEBUG: Not fetching more instances - EXIT!")
415 # Loop through some instances
417 "SELECT domain, origin, software, nodeinfo_url FROM instances WHERE software IN ('pleroma', 'mastodon', 'friendica', 'misskey', 'bookwyrm', 'takahe', 'lemmy') AND (last_instance_fetch IS NULL OR last_instance_fetch < ?) ORDER BY rowid DESC", [time.time() - config.get("recheck_instance")]
420 rows = fba.cursor.fetchall()
421 print(f"INFO: Checking {len(rows)} entries ...")
423 # DEBUG: print("DEBUG: domain:", row[0])
424 if blacklist.is_blacklisted(row[0]):
425 print("WARNING: domain is blacklisted:", row[0])
428 print(f"INFO: Fetching instances for instance '{row[0]}' ('{row[2]}') of origin='{row[1]}',nodeinfo_url='{row[3]}'")
429 fba.fetch_instances(row[0], row[1], row[2], inspect.currentframe().f_code.co_name, row[3])
431 # DEBUG: print("DEBUG: EXIT!")