]> git.mxchange.org Git - fba.git/blob - fba.py
Continued:
[fba.git] / fba.py
1 import bs4
2 import hashlib
3 import re
4 import reqto
5 import json
6 import sqlite3
7 import sys
8 import time
9 import validators
10
11 with open("config.json") as f:
12     config = json.loads(f.read())
13
14 # Don't check these, known trolls/flooders/testing/developing
15 blacklist = [
16     # Floods network with fake nodes as "research" project
17     "activitypub-troll.cf",
18     # Similar troll
19     "gab.best",
20     # Similar troll
21     "4chan.icu",
22     # Flooder (?)
23     "social.shrimpcam.pw",
24     # Flooder (?)
25     "mastotroll.netz.org",
26     # Testing/developing installations
27     "ngrok.io",
28 ]
29
30 # Array with pending errors needed to be written to database
31 pending_errors = {
32 }
33
34 # "rel" identifiers (no real URLs)
35 nodeinfo_identifier = [
36     "http://nodeinfo.diaspora.software/ns/schema/2.1",
37     "http://nodeinfo.diaspora.software/ns/schema/2.0",
38     "http://nodeinfo.diaspora.software/ns/schema/1.1",
39     "http://nodeinfo.diaspora.software/ns/schema/1.0",
40 ]
41
42 # HTTP headers for requests
43 headers = {
44     "user-agent": config["useragent"],
45 }
46
47 # Found info from node, such as nodeinfo URL, detection mode that needs to be
48 # written to database. Both arrays must be filled at the same time or else
49 # update_nodeinfos() will fail
50 nodeinfos = {
51     # Detection mode: AUTO_DISCOVERY or STATIC_CHECKS
52     "detection_mode": {},
53     # Found nodeinfo URL
54     "nodeinfo_url": {},
55     # Where to fetch peers (other instances)
56     "get_peers_url": {},
57 }
58
59 language_mapping = {
60     # English -> English
61     "Silenced instances"            : "Silenced servers",
62     "Suspended instances"           : "Suspended servers",
63     "Limited instances"             : "Limited servers",
64     # Mappuing German -> English
65     "Gesperrte Server"              : "Suspended servers",
66     "Gefilterte Medien"             : "Filtered media",
67     "Stummgeschaltete Server"       : "Silenced servers",
68     # Japanese -> English
69     "停止済みのサーバー"            : "Suspended servers",
70     "制限中のサーバー"              : "Limited servers",
71     "メディアを拒否しているサーバー": "Filtered media",
72     "サイレンス済みのサーバー"      : "Silenced servers",
73     # ??? -> English
74     "שרתים מושעים"                  : "Suspended servers",
75     "מדיה מסוננת"                   : "Filtered media",
76     "שרתים מוגבלים"                 : "Silenced servers",
77     # French -> English
78     "Serveurs suspendus"            : "Suspended servers",
79     "Médias filtrés"                : "Filtered media",
80     "Serveurs limités"              : "Limited servers",
81     "Serveurs modérés"              : "Limited servers",
82 }
83
84 # URL for fetching peers
85 get_peers_url = "/api/v1/instance/peers"
86
87 # Connect to database
88 connection = sqlite3.connect("blocks.db")
89 cursor = connection.cursor()
90
91 def is_blacklisted(domain: str) -> bool:
92     blacklisted = False
93     for peer in blacklist:
94         if peer in domain:
95             blacklisted = True
96
97     return blacklisted
98
99 def get_hash(domain: str) -> str:
100     return hashlib.sha256(domain.encode("utf-8")).hexdigest()
101
102 def update_last_blocked(domain: str):
103     # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
104     try:
105         cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
106             time.time(),
107             time.time(),
108             domain
109         ])
110
111         if cursor.rowcount == 0:
112             print("WARNING: Did not update any rows:", domain)
113
114     except BaseException as e:
115         print("ERROR: failed SQL query:", domain, e)
116         sys.exit(255)
117
118     # NOISY-DEBUG: print("DEBUG: EXIT!")
119
120 def update_nodeinfos(domain: str):
121     # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
122     sql_string = ''
123     fields = list()
124     for key in nodeinfos:
125         # NOISY-DEBUG: print("DEBUG: key:", key)
126         if domain in nodeinfos[key]:
127            # NOISY-DEBUG: print(f"DEBUG: Adding '{nodeinfos[key][domain]}' for key='{key}' ...")
128            fields.append(nodeinfos[key][domain])
129            sql_string += f" {key} = ?,"
130
131     fields.append(domain)
132     # NOISY-DEBUG: print(f"DEBUG: sql_string='{sql_string}',fields()={len(fields)}")
133
134     sql = "UPDATE instances SET" + sql_string + " last_status_code = NULL, last_error_details = NULL WHERE domain = ? LIMIT 1"
135     # NOISY-DEBUG: print("DEBUG: sql:", sql)
136
137     try:
138         # NOISY-DEBUG: print("DEBUG: Executing SQL:", sql)
139         cursor.execute(sql, fields)
140         # NOISY-DEBUG: print(f"DEBUG: Success! (rowcount={cursor.rowcount })")
141
142         if cursor.rowcount == 0:
143             print("WARNING: Did not update any rows:", domain)
144
145     except BaseException as e:
146         print(f"ERROR: failed SQL query: domain='{domain}',sql='{sql}',exception='{e}'")
147         sys.exit(255)
148
149     # NOISY-DEBUG: print("DEBUG: Deleting nodeinfos for domain:", domain)
150     for key in nodeinfos:
151         try:
152             # NOISY-DEBUG: print("DEBUG: Deleting key:", key)
153             del nodeinfos[key][domain]
154         except:
155             pass
156
157     # NOISY-DEBUG: print("DEBUG: EXIT!")
158
159 def update_last_error(domain: str, res: any):
160     # NOISY-DEBUG: print("DEBUG: domain,res[]:", domain, type(res))
161     try:
162         # NOISY-DEBUG: print("DEBUG: BEFORE res[]:", type(res))
163         if isinstance(res, BaseException) or isinstance(res, json.JSONDecodeError):
164             res = str(res)
165
166         # NOISY-DEBUG: print("DEBUG: AFTER res[]:", type(res))
167         if type(res) is str:
168             # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res}'");
169             cursor.execute("UPDATE instances SET last_status_code = 999, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
170                 res,
171                 time.time(),
172                 domain
173             ])
174         else:
175             # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res.reason}'");
176             cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
177                 res.status_code,
178                 res.reason,
179                 time.time(),
180                 domain
181             ])
182
183         if cursor.rowcount == 0:
184             # NOISY-DEBUG: print("DEBUG: Did not update any rows:", domain)
185             pending_errors[domain] = res
186
187     except BaseException as e:
188         print("ERROR: failed SQL query:", domain, e)
189         sys.exit(255)
190
191     # NOISY-DEBUG: print("DEBUG: EXIT!")
192
193 def update_last_nodeinfo(domain: str):
194     # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
195     try:
196         cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
197             time.time(),
198             time.time(),
199             domain
200         ])
201
202         if cursor.rowcount == 0:
203             print("WARNING: Did not update any rows:", domain)
204
205     except BaseException as e:
206         print("ERROR: failed SQL query:", domain, e)
207         sys.exit(255)
208
209     connection.commit()
210     # NOISY-DEBUG: print("DEBUG: EXIT!")
211
212 def get_peers(domain: str, software: str) -> list:
213     # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain, software)
214     peers = list()
215
216     if software == "lemmy":
217         # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is Lemmy, fetching JSON ...")
218         try:
219             res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
220
221             # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
222             if res.ok and isinstance(res.json(), dict):
223                 # NOISY-DEBUG: print("DEBUG: Success, res.json():", len(res.json()))
224                 json = res.json()
225
226                 if "federated_instances" in json and "linked" in json["federated_instances"]:
227                     # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
228                     peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
229
230         except BaseException as e:
231             print("WARNING: Exception during fetching JSON:", domain, e)
232
233         update_last_nodeinfo(domain)
234
235         # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
236         return peers
237     elif software == "peertube":
238         # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
239
240         start = 0
241         for mode in ["followers", "following"]:
242             print(f"DEBUG: domain='{domain}',mode='{mode}'")
243             while True:
244                 try:
245                     res = reqto.get(f"https://{domain}/api/v1/server/{mode}?start={start}&count=100", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
246
247                     # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
248                     if res.ok and isinstance(res.json(), dict):
249                         # NOISY-DEBUG: uccess, res.json():", len(res.json()))
250                         json = res.json()
251
252                         if "data" in json:
253                             # NOISY-DEBUG: print(f"DEBUG: Found {len(json['data'])} record(s).")
254                             for record in json["data"]:
255                                 # NOISY-DEBUG: print(f"DEBUG: record()={len(record)}")
256                                 if mode in record and "host" in record[mode]:
257                                     # NOISY-DEBUG: print(f"DEBUG: Found host={record[mode]['host']}, adding ...")
258                                     peers.append(record[mode]["host"])
259                                 else:
260                                     print(f"WARNING: record from '{domain}' has no '{mode}' or 'host' record: {record}")
261
262                             if len(json["data"]) < 100:
263                                 # NOISY-DEBUG: print("DEBUG: Reached end of JSON response:", domain)
264                                 break
265
266                         # Continue with next row
267                         start = start + 100
268
269                 except BaseException as e:
270                     print("WARNING: Exception during fetching JSON:", domain, e)
271
272             update_last_nodeinfo(domain)
273
274             # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
275             return peers
276
277     # NOISY-DEBUG: print(f"DEBUG: Fetching '{get_peers_url}' from '{domain}' ...")
278     try:
279         res = reqto.get(f"https://{domain}{get_peers_url}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
280
281         if not res.ok or res.status_code >= 400:
282             res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
283
284             if "federated_instances" in json and "linked" in json["federated_instances"]:
285                 # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
286                 peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
287             else:
288                 print("WARNING: Could not reach any JSON API:", domain)
289                 update_last_error(domain, res)
290         else:
291             # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
292             peers = res.json()
293             nodeinfos["get_peers_url"][domain] = get_peers_url
294
295     except BaseException as e:
296         print("WARNING: Some error during get():", domain, e)
297         update_last_error(domain, e)
298
299     update_last_nodeinfo(domain)
300
301     # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
302     return peers
303
304 def post_json_api(domain: str, path: str, data: str) -> list:
305     # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
306     json = {}
307     try:
308         res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
309
310         if not res.ok or res.status_code >= 400:
311             print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
312             update_last_error(domain, res)
313             raise
314
315         update_last_nodeinfo(domain)
316         json = res.json()
317     except BaseException as e:
318         print("WARNING: Some error during post():", domain, path, data, e)
319
320     # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
321     return json
322
323 def fetch_nodeinfo(domain: str) -> list:
324     # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
325
326     nodeinfo = fetch_wellknown_nodeinfo(domain)
327     # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
328
329     if len(nodeinfo) > 0:
330         # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
331         return nodeinfo
332
333     requests = [
334        f"https://{domain}/nodeinfo/2.1.json",
335        f"https://{domain}/nodeinfo/2.1",
336        f"https://{domain}/nodeinfo/2.0.json",
337        f"https://{domain}/nodeinfo/2.0",
338        f"https://{domain}/nodeinfo/1.0",
339        f"https://{domain}/api/v1/instance"
340     ]
341
342     json = {}
343     for request in requests:
344         try:
345             # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
346             res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
347
348             # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
349             if res.ok and isinstance(res.json(), dict):
350                 # NOISY-DEBUG: print("DEBUG: Success:", request)
351                 json = res.json()
352                 nodeinfos["detection_mode"][domain] = "STATIC_CHECK"
353                 nodeinfos["nodeinfo_url"][domain] = request
354                 break
355             elif not res.ok or res.status_code >= 400:
356                 print("WARNING: Failed fetching nodeinfo from domain:", domain)
357                 update_last_error(domain, res)
358                 continue
359
360         except BaseException as e:
361             # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
362             update_last_error(domain, e)
363             pass
364
365     # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
366     if not isinstance(json, dict) or len(json) == 0:
367         print("WARNING: Failed fetching nodeinfo from domain:", domain)
368
369     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
370     return json
371
372 def fetch_wellknown_nodeinfo(domain: str) -> list:
373     # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
374     json = {}
375
376     try:
377         res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
378         # NOISY-DEBUG: print("DEBUG: domain,res.ok,res.json[]:", domain, res.ok, type(res.json()))
379         if res.ok and isinstance(res.json(), dict):
380             nodeinfo = res.json()
381             # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
382             if "links" in nodeinfo:
383                 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
384                 for link in nodeinfo["links"]:
385                     # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
386                     if link["rel"] in nodeinfo_identifier:
387                         # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
388                         res = reqto.get(link["href"])
389                         # NOISY-DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
390                         if res.ok and isinstance(res.json(), dict):
391                             # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
392                             json = res.json()
393                             nodeinfos["detection_mode"][domain] = "AUTO_DISCOVERY"
394                             nodeinfos["nodeinfo_url"][domain] = link["href"]
395                             break
396                     else:
397                         print("WARNING: Unknown 'rel' value:", domain, link["rel"])
398             else:
399                 print("WARNING: nodeinfo does not contain 'links':", domain)
400
401     except BaseException as e:
402         print("WARNING: Failed fetching .well-known info:", domain)
403         update_last_error(domain, e)
404         pass
405
406     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
407     return json
408
409 def determine_software(domain: str) -> str:
410     # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
411     software = None
412
413     json = fetch_nodeinfo(domain)
414     # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
415
416     if not isinstance(json, dict) or len(json) == 0:
417         # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
418         return None
419
420     # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
421     if "status" in json and json["status"] == "error" and "message" in json:
422         print("WARNING: JSON response is an error:", json["message"])
423         update_last_error(domain, json["message"])
424         return None
425     elif "software" not in json or "name" not in json["software"]:
426         print("WARNING: JSON response does not include [software][name], guessing ...")
427         found = 0
428         for element in {"uri", "title", "short_description", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account", "registrations", "approval_required"}:
429             # NOISY-DEBUG: print("DEBUG: element:", element)
430             if element in json:
431                 found = found + 1
432
433         # NOISY-DEBUG: print("DEBUG: Found elements:", found)
434         if found == len(json):
435             # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
436             return "mastodon"
437
438         print(f"WARNING: Cannot guess software type: domain='{domain}',found={found},json()={len(json)}")
439         return None
440
441     software = tidyup(json["software"]["name"])
442
443     # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
444     if software in ["akkoma", "rebased"]:
445         # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
446         software = "pleroma"
447     elif software in ["hometown", "ecko"]:
448         # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
449         software = "mastodon"
450     elif software in ["calckey", "groundpolis", "foundkey", "cherrypick", "meisskey"]:
451         # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
452         software = "misskey"
453     elif software.find("/") > 0:
454         print("WARNING: Spliting of path:", software)
455         software = software.split("/")[-1];
456     elif software.find("|") > 0:
457         print("WARNING: Spliting of path:", software)
458         software = software.split("|")[0].strip();
459
460     if software == "":
461         print("WARNING: tidyup() left no software name behind:", domain)
462         software = None
463
464     # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
465     return software
466
467 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
468     # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
469     try:
470         cursor.execute(
471             "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
472             (
473                 reason,
474                 time.time(),
475                 blocker,
476                 blocked,
477                 block_level
478             ),
479         )
480
481         if cursor.rowcount == 0:
482             print("WARNING: Did not update any rows:", domain)
483
484     except BaseException as e:
485         print("ERROR: failed SQL query:", reason, blocker, blocked, block_level, e)
486         sys.exit(255)
487
488 def update_last_seen(blocker: str, blocked: str, block_level: str):
489     # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
490     try:
491         cursor.execute(
492             "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
493             (
494                 time.time(),
495                 blocker,
496                 blocked,
497                 block_level
498             )
499         )
500
501         if cursor.rowcount == 0:
502             print("WARNING: Did not update any rows:", domain)
503
504     except BaseException as e:
505         print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level, e)
506         sys.exit(255)
507
508     # NOISY-DEBUG: print("DEBUG: EXIT!")
509
510 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
511     # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
512     if not validators.domain(blocker):
513         print("WARNING: Bad blocker:", blocker)
514         raise
515     elif not validators.domain(blocked):
516         print("WARNING: Bad blocked:", blocked)
517         raise
518
519     print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
520     try:
521         cursor.execute(
522             "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
523              (
524                  blocker,
525                  blocked,
526                  reason,
527                  block_level,
528                  time.time(),
529                  time.time()
530              ),
531         )
532
533     except BaseException as e:
534         print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen, e)
535         sys.exit(255)
536
537     # NOISY-DEBUG: print("DEBUG: EXIT!")
538
539 def add_instance(domain: str, origin: str, originator: str):
540     # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
541     if not validators.domain(domain):
542         print("WARNING: Bad domain name:", domain)
543         raise
544     elif origin is not None and not validators.domain(origin):
545         print("WARNING: Bad origin name:", origin)
546         raise
547
548     software = determine_software(domain)
549     # NOISY-DEBUG: print("DEBUG: Determined software:", software)
550
551     print(f"INFO: Adding new instance {domain} (origin: {origin})")
552     try:
553         cursor.execute(
554             "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
555             (
556                domain,
557                origin,
558                originator,
559                get_hash(domain),
560                software,
561                time.time()
562             ),
563         )
564
565         if domain in nodeinfos["nodeinfo_url"]:
566             # NOISY-DEBUG # NOISY-DEBUG: print("DEBUG: domain has pending nodeinfo being updated:", domain)
567             update_nodeinfos(domain)
568             try:
569                 # Prevent updating any pending errors, nodeinfo was found
570                 del pending_errors[domain]
571             except:
572                 pass
573         elif domain in pending_errors:
574             # NOISY-DEBUG: print("DEBUG: domain has pending error being updated:", domain)
575             update_last_error(domain, pending_errors[domain])
576             del pending_errors[domain]
577
578     except BaseException as e:
579         print("ERROR: failed SQL query:", domain, e)
580         sys.exit(255)
581     else:
582         # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
583         update_last_nodeinfo(domain)
584
585     # NOISY-DEBUG: print("DEBUG: EXIT!")
586
587 def send_bot_post(instance: str, blocks: dict):
588     message = instance + " has blocked the following instances:\n\n"
589     truncated = False
590
591     if len(blocks) > 20:
592         truncated = True
593         blocks = blocks[0 : 19]
594
595     for block in blocks:
596         if block["reason"] == None or block["reason"] == '':
597             message = message + block["blocked"] + " with unspecified reason\n"
598         else:
599             if len(block["reason"]) > 420:
600                 block["reason"] = block["reason"][0:419] + "[…]"
601
602             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
603
604     if truncated:
605         message = message + "(the list has been truncated to the first 20 entries)"
606
607     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
608
609     req = reqto.post(
610         f"{config['bot_instance']}/api/v1/statuses",
611         data={
612             "status"      : message,
613             "visibility"  : config['bot_visibility'],
614             "content_type": "text/plain"
615         },
616         headers=botheaders,
617         timeout=10
618     ).json()
619
620     return True
621
622 def get_mastodon_blocks(domain: str) -> dict:
623     # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
624     blocks = {
625         "Suspended servers": [],
626         "Filtered media"   : [],
627         "Limited servers"  : [],
628         "Silenced servers" : [],
629     }
630
631     try:
632         doc = bs4.BeautifulSoup(
633             reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
634             "html.parser",
635         )
636     except BaseException as e:
637         print("ERROR: Cannot fetch from domain:", domain, e)
638         update_last_error(domain, e)
639         return {}
640
641     for header in doc.find_all("h3"):
642         header_text = tidyup(header.text)
643
644         if header_text in language_mapping:
645             print(f"DEBUG: header_text='{header_text}'")
646             header_text = language_mapping[header_text]
647
648         if header_text in blocks or header_text.lower() in blocks:
649             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
650             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
651                 blocks[header_text].append(
652                     {
653                         "domain": tidyup(line.find("span").text),
654                         "hash"  : tidyup(line.find("span")["title"][9:]),
655                         "reason": tidyup(line.find_all("td")[1].text),
656                     }
657                 )
658
659     # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
660     return {
661         "reject"        : blocks["Suspended servers"],
662         "media_removal" : blocks["Filtered media"],
663         "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
664     }
665
666 def get_friendica_blocks(domain: str) -> dict:
667     # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
668     blocks = []
669
670     try:
671         doc = bs4.BeautifulSoup(
672             reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
673             "html.parser",
674         )
675     except BaseException as e:
676         print("WARNING: Failed to fetch /friendica from domain:", domain, e)
677         update_last_error(domain, e)
678         return {}
679
680     blocklist = doc.find(id="about_blocklist")
681
682     # Prevents exceptions:
683     if blocklist is None:
684         # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
685         return {}
686
687     for line in blocklist.find("table").find_all("tr")[1:]:
688         blocks.append({
689             "domain": tidyup(line.find_all("td")[0].text),
690             "reason": tidyup(line.find_all("td")[1].text)
691         })
692
693     # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
694     return {
695         "reject": blocks
696     }
697
698 def get_misskey_blocks(domain: str) -> dict:
699     # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
700     blocks = {
701         "suspended": [],
702         "blocked"  : []
703     }
704
705     counter = 0
706     step = 99
707     while True:
708         # iterating through all "suspended" (follow-only in its terminology)
709         # instances page-by-page, since that troonware doesn't support
710         # sending them all at once
711         try:
712             if counter == 0:
713                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
714                 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
715                     "sort"     : "+caughtAt",
716                     "host"     : None,
717                     "suspended": True,
718                     "limit"    : step
719                 }))
720             else:
721                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
722                 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
723                     "sort"     : "+caughtAt",
724                     "host"     : None,
725                     "suspended": True,
726                     "limit"    : step,
727                     "offset"   : counter-1
728                 }))
729
730             # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
731             if len(doc) == 0:
732                 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
733                 break
734
735             for instance in doc:
736                 # just in case
737                 if instance["isSuspended"]:
738                     blocks["suspended"].append(
739                         {
740                             "domain": tidyup(instance["host"]),
741                             # no reason field, nothing
742                             "reason": ""
743                         }
744                     )
745
746             if len(doc) < step:
747                 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
748                 break
749
750             # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
751             counter = counter + step
752
753         except BaseException as e:
754             print("WARNING: Caught error, exiting loop:", domain, e)
755             update_last_error(domain, e)
756             counter = 0
757             break
758
759     while True:
760         # same shit, different asshole ("blocked" aka full suspend)
761         try:
762             if counter == 0:
763                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
764                 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
765                     "sort"   : "+caughtAt",
766                     "host"   : None,
767                     "blocked": True,
768                     "limit"  : step
769                 }))
770             else:
771                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
772                 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
773                     "sort"   : "+caughtAt",
774                     "host"   : None,
775                     "blocked": True,
776                     "limit"  : step,
777                     "offset" : counter-1
778                 }))
779
780             # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
781             if len(doc) == 0:
782                 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
783                 break
784
785             for instance in doc:
786                 if instance["isBlocked"]:
787                     blocks["blocked"].append({
788                         "domain": tidyup(instance["host"]),
789                         "reason": ""
790                     })
791
792             if len(doc) < step:
793                 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
794                 break
795
796             # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
797             counter = counter + step
798
799         except BaseException as e:
800             print("ERROR: Exception during POST:", domain, e)
801             update_last_error(domain, e)
802             counter = 0
803             break
804
805     # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
806     return {
807         "reject"        : blocks["blocked"],
808         "followers_only": blocks["suspended"]
809     }
810
811 def tidyup(string: str) -> str:
812     # some retards put their blocks in variable case
813     string = string.lower().strip()
814
815     # other retards put the port
816     string = re.sub("\:\d+$", "", string)
817
818     # bigger retards put the schema in their blocklist, sometimes even without slashes
819     string = re.sub("^https?\:(\/*)", "", string)
820
821     # and trailing slash
822     string = re.sub("\/$", "", string)
823
824     # and the @
825     string = re.sub("^\@", "", string)
826
827     # the biggest retards of them all try to block individual users
828     string = re.sub("(.+)\@", "", string)
829
830     return string