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)
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",
69 "停止済みのサーバー" : "Suspended servers",
70 "制限中のサーバー" : "Limited servers",
71 "メディアを拒否しているサーバー": "Filtered media",
72 "サイレンス済みのサーバー" : "Silenced servers",
74 "שרתים מושעים" : "Suspended servers",
75 "מדיה מסוננת" : "Filtered media",
76 "שרתים מוגבלים" : "Silenced servers",
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",
84 # URL for fetching peers
85 get_peers_url = "/api/v1/instance/peers"
88 connection = sqlite3.connect("blocks.db")
89 cursor = connection.cursor()
91 def is_blacklisted(domain: str) -> bool:
93 for peer in blacklist:
99 def get_hash(domain: str) -> str:
100 return hashlib.sha256(domain.encode("utf-8")).hexdigest()
102 def update_last_blocked(domain: str):
103 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
105 cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
111 if cursor.rowcount == 0:
112 print("WARNING: Did not update any rows:", domain)
114 except BaseException as e:
115 print("ERROR: failed SQL query:", domain, e)
118 # NOISY-DEBUG: print("DEBUG: EXIT!")
120 def update_nodeinfos(domain: str):
121 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
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} = ?,"
131 fields.append(domain)
132 # NOISY-DEBUG: print(f"DEBUG: sql_string='{sql_string}',fields()={len(fields)}")
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)
138 # NOISY-DEBUG: print("DEBUG: Executing SQL:", sql)
139 cursor.execute(sql, fields)
140 # NOISY-DEBUG: print(f"DEBUG: Success! (rowcount={cursor.rowcount })")
142 if cursor.rowcount == 0:
143 print("WARNING: Did not update any rows:", domain)
145 except BaseException as e:
146 print(f"ERROR: failed SQL query: domain='{domain}',sql='{sql}',exception='{e}'")
149 # NOISY-DEBUG: print("DEBUG: Deleting nodeinfos for domain:", domain)
150 for key in nodeinfos:
152 # NOISY-DEBUG: print("DEBUG: Deleting key:", key)
153 del nodeinfos[key][domain]
157 # NOISY-DEBUG: print("DEBUG: EXIT!")
159 def update_last_error(domain: str, res: any):
160 # NOISY-DEBUG: print("DEBUG: domain,res[]:", domain, type(res))
162 # NOISY-DEBUG: print("DEBUG: BEFORE res[]:", type(res))
163 if isinstance(res, BaseException) or isinstance(res, json.JSONDecodeError):
166 # NOISY-DEBUG: print("DEBUG: AFTER res[]:", type(res))
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", [
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", [
183 if cursor.rowcount == 0:
184 # NOISY-DEBUG: print("DEBUG: Did not update any rows:", domain)
185 pending_errors[domain] = res
187 except BaseException as e:
188 print("ERROR: failed SQL query:", domain, e)
191 # NOISY-DEBUG: print("DEBUG: EXIT!")
193 def update_last_nodeinfo(domain: str):
194 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
196 cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
202 if cursor.rowcount == 0:
203 print("WARNING: Did not update any rows:", domain)
205 except BaseException as e:
206 print("ERROR: failed SQL query:", domain, e)
210 # NOISY-DEBUG: print("DEBUG: EXIT!")
212 def get_peers(domain: str, software: str) -> list:
213 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain, software)
216 if software == "lemmy":
217 # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is Lemmy, fetching JSON ...")
219 res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
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()))
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"]
230 except BaseException as e:
231 print("WARNING: Exception during fetching JSON:", domain, e)
233 update_last_nodeinfo(domain)
235 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
237 elif software == "peertube":
238 # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
241 for mode in ["followers", "following"]:
242 # NOISY-DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
245 res = reqto.get(f"https://{domain}/api/v1/server/{mode}?start={start}&count=100", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
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: print("DEBUG: Success, res.json():", len(res.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"])
260 print(f"WARNING: record from '{domain}' has no '{mode}' or 'host' record: {record}")
262 if len(json["data"]) < 100:
263 # NOISY-DEBUG: print("DEBUG: Reached end of JSON response:", domain)
266 # Continue with next row
269 except BaseException as e:
270 print("WARNING: Exception during fetching JSON:", domain, e)
272 update_last_nodeinfo(domain)
274 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
277 # NOISY-DEBUG: print(f"DEBUG: Fetching '{get_peers_url}' from '{domain}' ...")
279 res = reqto.get(f"https://{domain}{get_peers_url}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
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"]))
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"]
288 print("WARNING: Could not reach any JSON API:", domain)
289 update_last_error(domain, res)
291 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
293 nodeinfos["get_peers_url"][domain] = get_peers_url
295 except BaseException as e:
296 print("WARNING: Some error during get():", domain, e)
297 update_last_error(domain, e)
299 update_last_nodeinfo(domain)
301 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
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)
308 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
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)
315 update_last_nodeinfo(domain)
317 except BaseException as e:
318 print("WARNING: Some error during post():", domain, path, data, e)
320 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
323 def fetch_nodeinfo(domain: str) -> list:
324 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
326 nodeinfo = fetch_wellknown_nodeinfo(domain)
327 # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
329 if len(nodeinfo) > 0:
330 # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
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"
343 for request in requests:
345 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
346 res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
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)
352 nodeinfos["detection_mode"][domain] = "STATIC_CHECK"
353 nodeinfos["nodeinfo_url"][domain] = request
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)
360 except BaseException as e:
361 # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
362 update_last_error(domain, e)
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)
369 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
372 def fetch_wellknown_nodeinfo(domain: str) -> list:
373 # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
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"])
390 # NOISY-DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
391 if res.ok and isinstance(res.json(), dict):
392 # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
394 nodeinfos["detection_mode"][domain] = "AUTO_DISCOVERY"
395 nodeinfos["nodeinfo_url"][domain] = link["href"]
398 print("WARNING: Unknown 'rel' value:", domain, link["rel"])
400 print("WARNING: nodeinfo does not contain 'links':", domain)
402 except BaseException as e:
403 print("WARNING: Failed fetching .well-known info:", domain)
404 update_last_error(domain, e)
407 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
410 def determine_software(domain: str) -> str:
411 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
414 json = fetch_nodeinfo(domain)
415 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
417 if not isinstance(json, dict) or len(json) == 0:
418 # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
421 # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
422 if "status" in json and json["status"] == "error" and "message" in json:
423 print("WARNING: JSON response is an error:", json["message"])
424 update_last_error(domain, json["message"])
426 elif "software" not in json or "name" not in json["software"]:
427 print("WARNING: JSON response does not include [software][name], guessing ...")
429 for element in {"uri", "title", "short_description", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account", "registrations", "approval_required"}:
430 # NOISY-DEBUG: print("DEBUG: element:", element)
434 # NOISY-DEBUG: print("DEBUG: Found elements:", found)
435 if found == len(json):
436 # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
439 print(f"WARNING: Cannot guess software type: domain='{domain}',found={found},json()={len(json)}")
442 software = tidyup(json["software"]["name"])
444 # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
445 if software in ["akkoma", "rebased"]:
446 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
448 elif software in ["hometown", "ecko"]:
449 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
450 software = "mastodon"
451 elif software in ["calckey", "groundpolis", "foundkey", "cherrypick", "meisskey"]:
452 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
454 elif software.find("/") > 0:
455 print("WARNING: Spliting of path:", software)
456 software = software.split("/")[-1];
457 elif software.find("|") > 0:
458 print("WARNING: Spliting of path:", software)
459 software = software.split("|")[0].strip();
462 print("WARNING: tidyup() left no software name behind:", domain)
465 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
468 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
469 # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
472 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
482 if cursor.rowcount == 0:
483 print("WARNING: Did not update any rows:", domain)
485 except BaseException as e:
486 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level, e)
489 def update_last_seen(blocker: str, blocked: str, block_level: str):
490 # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
493 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
502 if cursor.rowcount == 0:
503 print("WARNING: Did not update any rows:", domain)
505 except BaseException as e:
506 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level, e)
509 # NOISY-DEBUG: print("DEBUG: EXIT!")
511 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
512 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
513 if not validators.domain(blocker):
514 print("WARNING: Bad blocker:", blocker)
516 elif not validators.domain(blocked):
517 print("WARNING: Bad blocked:", blocked)
520 print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
523 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
534 except BaseException as e:
535 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen, e)
538 # NOISY-DEBUG: print("DEBUG: EXIT!")
540 def add_instance(domain: str, origin: str, originator: str):
541 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
542 if not validators.domain(domain):
543 print("WARNING: Bad domain name:", domain)
545 elif origin is not None and not validators.domain(origin):
546 print("WARNING: Bad origin name:", origin)
549 software = determine_software(domain)
550 # NOISY-DEBUG: print("DEBUG: Determined software:", software)
552 print(f"INFO: Adding new instance {domain} (origin: {origin})")
555 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
566 if domain in nodeinfos["nodeinfo_url"]:
567 # NOISY-DEBUG # NOISY-DEBUG: print("DEBUG: domain has pending nodeinfo being updated:", domain)
568 update_nodeinfos(domain)
570 # Prevent updating any pending errors, nodeinfo was found
571 del pending_errors[domain]
574 elif domain in pending_errors:
575 # NOISY-DEBUG: print("DEBUG: domain has pending error being updated:", domain)
576 update_last_error(domain, pending_errors[domain])
577 del pending_errors[domain]
579 except BaseException as e:
580 print("ERROR: failed SQL query:", domain, e)
583 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
584 update_last_nodeinfo(domain)
586 # NOISY-DEBUG: print("DEBUG: EXIT!")
588 def send_bot_post(instance: str, blocks: dict):
589 message = instance + " has blocked the following instances:\n\n"
594 blocks = blocks[0 : 19]
597 if block["reason"] == None or block["reason"] == '':
598 message = message + block["blocked"] + " with unspecified reason\n"
600 if len(block["reason"]) > 420:
601 block["reason"] = block["reason"][0:419] + "[…]"
603 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
606 message = message + "(the list has been truncated to the first 20 entries)"
608 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
611 f"{config['bot_instance']}/api/v1/statuses",
614 "visibility" : config['bot_visibility'],
615 "content_type": "text/plain"
623 def get_mastodon_blocks(domain: str) -> dict:
624 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
626 "Suspended servers": [],
627 "Filtered media" : [],
628 "Limited servers" : [],
629 "Silenced servers" : [],
633 doc = bs4.BeautifulSoup(
634 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
637 except BaseException as e:
638 print("ERROR: Cannot fetch from domain:", domain, e)
639 update_last_error(domain, e)
642 for header in doc.find_all("h3"):
643 header_text = tidyup(header.text)
645 if header_text in language_mapping:
646 # NOISY-DEBUG: print(f"DEBUG: header_text='{header_text}'")
647 header_text = language_mapping[header_text]
649 if header_text in blocks or header_text.lower() in blocks:
650 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
651 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
652 blocks[header_text].append(
654 "domain": tidyup(line.find("span").text),
655 "hash" : tidyup(line.find("span")["title"][9:]),
656 "reason": tidyup(line.find_all("td")[1].text),
660 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
662 "reject" : blocks["Suspended servers"],
663 "media_removal" : blocks["Filtered media"],
664 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
667 def get_friendica_blocks(domain: str) -> dict:
668 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
672 doc = bs4.BeautifulSoup(
673 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
676 except BaseException as e:
677 print("WARNING: Failed to fetch /friendica from domain:", domain, e)
678 update_last_error(domain, e)
681 blocklist = doc.find(id="about_blocklist")
683 # Prevents exceptions:
684 if blocklist is None:
685 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
688 for line in blocklist.find("table").find_all("tr")[1:]:
690 "domain": tidyup(line.find_all("td")[0].text),
691 "reason": tidyup(line.find_all("td")[1].text)
694 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
699 def get_misskey_blocks(domain: str) -> dict:
700 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
709 # iterating through all "suspended" (follow-only in its terminology)
710 # instances page-by-page, since that troonware doesn't support
711 # sending them all at once
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",
722 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
723 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
724 "sort" : "+caughtAt",
731 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
733 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
738 if instance["isSuspended"]:
739 blocks["suspended"].append(
741 "domain": tidyup(instance["host"]),
742 # no reason field, nothing
748 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
751 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
752 counter = counter + step
754 except BaseException as e:
755 print("WARNING: Caught error, exiting loop:", domain, e)
756 update_last_error(domain, e)
761 # same shit, different asshole ("blocked" aka full suspend)
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",
772 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
773 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
774 "sort" : "+caughtAt",
781 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
783 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
787 if instance["isBlocked"]:
788 blocks["blocked"].append({
789 "domain": tidyup(instance["host"]),
794 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
797 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
798 counter = counter + step
800 except BaseException as e:
801 print("ERROR: Exception during POST:", domain, e)
802 update_last_error(domain, e)
806 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
808 "reject" : blocks["blocked"],
809 "followers_only": blocks["suspended"]
812 def tidyup(string: str) -> str:
813 # some retards put their blocks in variable case
814 string = string.lower().strip()
816 # other retards put the port
817 string = re.sub("\:\d+$", "", string)
819 # bigger retards put the schema in their blocklist, sometimes even without slashes
820 string = re.sub("^https?\:(\/*)", "", string)
823 string = re.sub("\/$", "", string)
826 string = re.sub("^\@", "", string)
828 # the biggest retards of them all try to block individual users
829 string = re.sub("(.+)\@", "", string)