11 with open("config.json") as f:
12 config = json.loads(f.read())
14 # Don't check these, known trolls/flooders/testing/developing
16 # Floods network with fake nodes as "research" project
17 "activitypub-troll.cf",
23 "social.shrimpcam.pw",
25 "mastotroll.netz.org",
26 # Testing/developing installations
30 # Array with pending errors needed to be written to database
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",
42 # HTTP headers for requests
44 "user-agent": config["useragent"],
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
51 # Detection mode: AUTO_DISCOVERY or STATIC_CHECKS
55 # Where to fetch peers (other instances)
59 # URL for fetching peers
60 get_peers_url = "/api/v1/instance/peers"
63 connection = sqlite3.connect("blocks.db")
64 cursor = connection.cursor()
66 def is_blacklisted(domain: str) -> bool:
68 for peer in blacklist:
74 def get_hash(domain: str) -> str:
75 return hashlib.sha256(domain.encode("utf-8")).hexdigest()
77 def update_last_blocked(domain: str):
78 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
80 cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
86 if cursor.rowcount == 0:
87 print("WARNING: Did not update any rows:", domain)
89 except BaseException as e:
90 print("ERROR: failed SQL query:", domain, e)
93 # NOISY-DEBUG: print("DEBUG: EXIT!")
95 def update_nodeinfos(domain: str):
96 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
100 # NOISY-DEBUG: print("DEBUG: key:", key)
101 if domain in nodeinfos[key]:
102 # NOISY-DEBUG: print(f"DEBUG: Adding '{nodeinfos[key][domain]}' for key='{key}' ...")
103 fields.append(nodeinfos[key][domain])
104 sql_string += f" {key} = ?,"
106 fields.append(domain)
107 # NOISY-DEBUG: print(f"DEBUG: sql_string='{sql_string}',fields()={len(fields)}")
109 sql = "UPDATE instances SET" + sql_string + " last_status_code = NULL, last_error_details = NULL WHERE domain = ? LIMIT 1"
110 # NOISY-DEBUG: print("DEBUG: sql:", sql)
113 # NOISY-DEBUG: print("DEBUG: Executing SQL:", sql)
114 cursor.execute(sql, fields)
115 # NOISY-DEBUG: print(f"DEBUG: Success! (rowcount={cursor.rowcount })")
117 if cursor.rowcount == 0:
118 print("WARNING: Did not update any rows:", domain)
120 except BaseException as e:
121 print(f"ERROR: failed SQL query: domain='{domain}',sql='{sql}',exception='{e}'")
124 # NOISY-DEBUG: print("DEBUG: Deleting nodeinfos for domain:", domain)
125 for key in nodeinfos:
127 # NOISY-DEBUG: print("DEBUG: Deleting key:", key)
128 del nodeinfos[key][domain]
132 # NOISY-DEBUG: print("DEBUG: EXIT!")
134 def update_last_error(domain: str, res: any):
135 # NOISY-DEBUG: print("DEBUG: domain,res[]:", domain, type(res))
137 # NOISY-DEBUG: print("DEBUG: BEFORE res[]:", type(res))
138 if isinstance(res, BaseException) or isinstance(res, json.JSONDecodeError):
141 # NOISY-DEBUG: print("DEBUG: AFTER res[]:", type(res))
143 # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res}'");
144 cursor.execute("UPDATE instances SET last_status_code = 999, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
150 # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res.reason}'");
151 cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
158 if cursor.rowcount == 0:
159 # NOISY-DEBUG: print("DEBUG: Did not update any rows:", domain)
160 pending_errors[domain] = res
162 except BaseException as e:
163 print("ERROR: failed SQL query:", domain, e)
166 # NOISY-DEBUG: print("DEBUG: EXIT!")
168 def update_last_nodeinfo(domain: str):
169 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
171 cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
177 if cursor.rowcount == 0:
178 print("WARNING: Did not update any rows:", domain)
180 except BaseException as e:
181 print("ERROR: failed SQL query:", domain, e)
185 # NOISY-DEBUG: print("DEBUG: EXIT!")
187 def get_peers(domain: str, software: str) -> list:
188 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain, software)
191 if software == "lemmy":
192 # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is Lemmy, fetching JSON ...")
194 res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
196 # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
197 if res.ok and isinstance(res.json(), dict):
198 # NOISY-DEBUG: print("DEBUG: Success, res.json():", len(res.json()))
201 if "federated_instances" in json and "linked" in json["federated_instances"]:
202 # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
203 peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
205 except BaseException as e:
206 print("WARNING: Exception during fetching JSON:", domain, e)
208 update_last_nodeinfo(domain)
210 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
212 elif software == "peertube":
213 # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
216 for mode in ["followers", "following"]:
217 print(f"DEBUG: domain='{domain}',mode='{mode}'")
220 res = reqto.get(f"https://{domain}/api/v1/server/{mode}?start={start}&count=100", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
222 # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
223 if res.ok and isinstance(res.json(), dict):
224 # NOISY-DEBUG: uccess, res.json():", len(res.json()))
228 # NOISY-DEBUG: print(f"DEBUG: Found {len(json['data'])} record(s).")
229 for record in json["data"]:
230 # NOISY-DEBUG: print(f"DEBUG: record()={len(record)}")
231 if mode in record and "host" in record[mode]:
232 # NOISY-DEBUG: print(f"DEBUG: Found host={record[mode]['host']}, adding ...")
233 peers.append(record[mode]["host"])
235 print(f"WARNING: record from '{domain}' has no '{mode}' or 'host' record: {record}")
237 if len(json["data"]) < 100:
238 # NOISY-DEBUG: print("DEBUG: Reached end of JSON response:", domain)
241 # Continue with next row
244 except BaseException as e:
245 print("WARNING: Exception during fetching JSON:", domain, e)
247 update_last_nodeinfo(domain)
249 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
252 # NOISY-DEBUG: print(f"DEBUG: Fetching '{get_peers_url}' from '{domain}' ...")
254 res = reqto.get(f"https://{domain}{get_peers_url}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
256 if not res.ok or res.status_code >= 400:
257 res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
259 if "federated_instances" in json and "linked" in json["federated_instances"]:
260 # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
261 peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
263 print("WARNING: Could not reach any JSON API:", domain)
264 update_last_error(domain, res)
266 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
268 nodeinfos["get_peers_url"][domain] = get_peers_url
270 except BaseException as e:
271 print("WARNING: Some error during get():", domain, e)
272 update_last_error(domain, e)
274 update_last_nodeinfo(domain)
276 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
279 def post_json_api(domain: str, path: str, data: str) -> list:
280 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
283 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
285 if not res.ok or res.status_code >= 400:
286 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
287 update_last_error(domain, res)
290 update_last_nodeinfo(domain)
292 except BaseException as e:
293 print("WARNING: Some error during post():", domain, path, data, e)
295 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
298 def fetch_nodeinfo(domain: str) -> list:
299 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
301 nodeinfo = fetch_wellknown_nodeinfo(domain)
302 # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
304 if len(nodeinfo) > 0:
305 # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
309 f"https://{domain}/nodeinfo/2.1.json",
310 f"https://{domain}/nodeinfo/2.1",
311 f"https://{domain}/nodeinfo/2.0.json",
312 f"https://{domain}/nodeinfo/2.0",
313 f"https://{domain}/nodeinfo/1.0",
314 f"https://{domain}/api/v1/instance"
318 for request in requests:
320 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
321 res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
323 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
324 if res.ok and isinstance(res.json(), dict):
325 # NOISY-DEBUG: print("DEBUG: Success:", request)
327 nodeinfos["detection_mode"][domain] = "STATIC_CHECK"
328 nodeinfos["nodeinfo_url"][domain] = request
330 elif not res.ok or res.status_code >= 400:
331 print("WARNING: Failed fetching nodeinfo from domain:", domain)
332 update_last_error(domain, res)
335 except BaseException as e:
336 # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
337 update_last_error(domain, e)
340 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
341 if not isinstance(json, dict) or len(json) == 0:
342 print("WARNING: Failed fetching nodeinfo from domain:", domain)
344 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
347 def fetch_wellknown_nodeinfo(domain: str) -> list:
348 # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
352 res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
353 # NOISY-DEBUG: print("DEBUG: domain,res.ok,res.json[]:", domain, res.ok, type(res.json()))
354 if res.ok and isinstance(res.json(), dict):
355 nodeinfo = res.json()
356 # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
357 if "links" in nodeinfo:
358 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
359 for link in nodeinfo["links"]:
360 # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
361 if link["rel"] in nodeinfo_identifier:
362 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
363 res = reqto.get(link["href"])
364 # NOISY-DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
365 if res.ok and isinstance(res.json(), dict):
366 # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
368 nodeinfos["detection_mode"][domain] = "AUTO_DISCOVERY"
369 nodeinfos["nodeinfo_url"][domain] = link["href"]
372 print("WARNING: Unknown 'rel' value:", domain, link["rel"])
374 print("WARNING: nodeinfo does not contain 'links':", domain)
376 except BaseException as e:
377 print("WARNING: Failed fetching .well-known info:", domain)
378 update_last_error(domain, e)
381 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
384 def determine_software(domain: str) -> str:
385 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
388 json = fetch_nodeinfo(domain)
389 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
391 if not isinstance(json, dict) or len(json) == 0:
392 # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
395 # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
396 if "status" in json and json["status"] == "error" and "message" in json:
397 print("WARNING: JSON response is an error:", json["message"])
398 update_last_error(domain, json["message"])
400 elif "software" not in json or "name" not in json["software"]:
401 print("WARNING: JSON response does not include [software][name], guessing ...")
403 for element in {"uri", "title", "short_description", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account", "registrations", "approval_required"}:
404 # NOISY-DEBUG: print("DEBUG: element:", element)
408 # NOISY-DEBUG: print("DEBUG: Found elements:", found)
409 if found == len(json):
410 # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
413 print(f"WARNING: Cannot guess software type: domain='{domain}',found={found},json()={len(json)}")
416 software = tidyup(json["software"]["name"])
418 # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
419 if software in ["akkoma", "rebased"]:
420 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
422 elif software in ["hometown", "ecko"]:
423 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
424 software = "mastodon"
425 elif software in ["calckey", "groundpolis", "foundkey", "cherrypick", "meisskey"]:
426 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
428 elif software.find("/") > 0:
429 print("WARNING: Spliting of path:", software)
430 software = software.split("/")[-1];
431 elif software.find("|") > 0:
432 print("WARNING: Spliting of path:", software)
433 software = software.split("|")[0].strip();
436 print("WARNING: tidyup() left no software name behind:", domain)
439 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
442 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
443 # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
446 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
456 if cursor.rowcount == 0:
457 print("WARNING: Did not update any rows:", domain)
459 except BaseException as e:
460 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level, e)
463 def update_last_seen(blocker: str, blocked: str, block_level: str):
464 # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
467 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
476 if cursor.rowcount == 0:
477 print("WARNING: Did not update any rows:", domain)
479 except BaseException as e:
480 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level, e)
483 # NOISY-DEBUG: print("DEBUG: EXIT!")
485 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
486 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
487 if not validators.domain(blocker):
488 print("WARNING: Bad blocker:", blocker)
490 elif not validators.domain(blocked):
491 print("WARNING: Bad blocked:", blocked)
494 print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
497 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
508 except BaseException as e:
509 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen, e)
512 # NOISY-DEBUG: print("DEBUG: EXIT!")
514 def add_instance(domain: str, origin: str, originator: str):
515 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
516 if not validators.domain(domain):
517 print("WARNING: Bad domain name:", domain)
519 elif origin is not None and not validators.domain(origin):
520 print("WARNING: Bad origin name:", origin)
523 software = determine_software(domain)
524 # NOISY-DEBUG: print("DEBUG: Determined software:", software)
526 print(f"INFO: Adding new instance {domain} (origin: {origin})")
529 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
540 if domain in nodeinfos["nodeinfo_url"]:
541 # NOISY-DEBUG # NOISY-DEBUG: print("DEBUG: domain has pending nodeinfo being updated:", domain)
542 update_nodeinfos(domain)
544 # Prevent updating any pending errors, nodeinfo was found
545 del pending_errors[domain]
548 elif domain in pending_errors:
549 # NOISY-DEBUG: print("DEBUG: domain has pending error being updated:", domain)
550 update_last_error(domain, pending_errors[domain])
551 del pending_errors[domain]
553 except BaseException as e:
554 print("ERROR: failed SQL query:", domain, e)
557 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
558 update_last_nodeinfo(domain)
560 # NOISY-DEBUG: print("DEBUG: EXIT!")
562 def send_bot_post(instance: str, blocks: dict):
563 message = instance + " has blocked the following instances:\n\n"
568 blocks = blocks[0 : 19]
571 if block["reason"] == None or block["reason"] == '':
572 message = message + block["blocked"] + " with unspecified reason\n"
574 if len(block["reason"]) > 420:
575 block["reason"] = block["reason"][0:419] + "[…]"
577 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
580 message = message + "(the list has been truncated to the first 20 entries)"
582 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
585 f"{config['bot_instance']}/api/v1/statuses",
588 "visibility" : config['bot_visibility'],
589 "content_type": "text/plain"
597 def get_mastodon_blocks(domain: str) -> dict:
598 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
600 "Suspended servers": [],
601 "Filtered media" : [],
602 "Limited servers" : [],
603 "Silenced servers" : [],
607 "Silenced instances" : "Silenced servers",
608 "Suspended instances" : "Suspended servers",
609 "Gesperrte Server" : "Suspended servers",
610 "Gefilterte Medien" : "Filtered media",
611 "Stummgeschaltete Server" : "Silenced servers",
612 "停止済みのサーバー" : "Suspended servers",
613 "制限中のサーバー" : "Limited servers",
614 "メディアを拒否しているサーバー": "Filtered media",
615 "サイレンス済みのサーバー" : "Silenced servers",
616 "שרתים מושעים" : "Suspended servers",
617 "מדיה מסוננת" : "Filtered media",
618 "שרתים מוגבלים" : "Silenced servers",
619 "Serveurs suspendus" : "Suspended servers",
620 "Médias filtrés" : "Filtered media",
621 "Serveurs limités" : "Limited servers",
622 "Serveurs modérés" : "Limited servers",
626 doc = bs4.BeautifulSoup(
627 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
630 except BaseException as e:
631 print("ERROR: Cannot fetch from domain:", domain, e)
632 update_last_error(domain, e)
635 for header in doc.find_all("h3"):
636 header_text = header.text
638 if header_text in translations:
639 header_text = translations[header_text]
641 if header_text in blocks or header_text.lower() in blocks:
642 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
643 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
644 blocks[header_text].append(
646 "domain": tidyup(line.find("span").text),
647 "hash" : tidyup(line.find("span")["title"][9:]),
648 "reason": tidyup(line.find_all("td")[1].text),
652 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
654 "reject" : blocks["Suspended servers"],
655 "media_removal" : blocks["Filtered media"],
656 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
659 def get_friendica_blocks(domain: str) -> dict:
660 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
664 doc = bs4.BeautifulSoup(
665 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
668 except BaseException as e:
669 print("WARNING: Failed to fetch /friendica from domain:", domain, e)
670 update_last_error(domain, e)
673 blocklist = doc.find(id="about_blocklist")
675 # Prevents exceptions:
676 if blocklist is None:
677 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
680 for line in blocklist.find("table").find_all("tr")[1:]:
682 "domain": tidyup(line.find_all("td")[0].text),
683 "reason": tidyup(line.find_all("td")[1].text)
686 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
691 def get_misskey_blocks(domain: str) -> dict:
692 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
701 # iterating through all "suspended" (follow-only in its terminology)
702 # instances page-by-page, since that troonware doesn't support
703 # sending them all at once
706 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
707 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
708 "sort" : "+caughtAt",
714 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
715 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
716 "sort" : "+caughtAt",
723 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
725 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
730 if instance["isSuspended"]:
731 blocks["suspended"].append(
733 "domain": tidyup(instance["host"]),
734 # no reason field, nothing
740 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
743 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
744 counter = counter + step
746 except BaseException as e:
747 print("WARNING: Caught error, exiting loop:", domain, e)
748 update_last_error(domain, e)
753 # same shit, different asshole ("blocked" aka full suspend)
756 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
757 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
758 "sort" : "+caughtAt",
764 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
765 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
766 "sort" : "+caughtAt",
773 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
775 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
779 if instance["isBlocked"]:
780 blocks["blocked"].append({
781 "domain": tidyup(instance["host"]),
786 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
789 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
790 counter = counter + step
792 except BaseException as e:
793 print("ERROR: Exception during POST:", domain, e)
794 update_last_error(domain, e)
798 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
800 "reject" : blocks["blocked"],
801 "followers_only": blocks["suspended"]
804 def tidyup(string: str) -> str:
805 # some retards put their blocks in variable case
806 string = string.lower().strip()
808 # other retards put the port
809 string = re.sub("\:\d+$", "", string)
811 # bigger retards put the schema in their blocklist, sometimes even without slashes
812 string = re.sub("^https?\:(\/*)", "", string)
815 string = re.sub("\/$", "", string)
818 string = re.sub("^\@", "", string)
820 # the biggest retards of them all try to block individual users
821 string = re.sub("(.+)\@", "", string)