1 from bs4 import BeautifulSoup
2 from hashlib import sha256
11 with open("config.json") as f:
12 config = json.loads(f.read())
15 "activitypub-troll.cf",
18 "social.shrimpcam.pw",
19 "mastotroll.netz.org",
24 "http://nodeinfo.diaspora.software/ns/schema/2.1",
25 "http://nodeinfo.diaspora.software/ns/schema/2.0",
26 "http://nodeinfo.diaspora.software/ns/schema/1.1",
27 "http://nodeinfo.diaspora.software/ns/schema/1.0",
31 "user-agent": config["useragent"]
34 connection = sqlite3.connect("blocks.db")
35 cursor = connection.cursor()
37 def is_blacklisted(domain: str) -> bool:
39 for peer in blacklist:
45 def get_hash(domain: str) -> str:
46 return sha256(domain.encode("utf-8")).hexdigest()
48 def update_last_blocked(domain: str):
49 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
51 cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
58 print("ERROR: failed SQL query:", domain)
61 def update_last_error(domain: str, res: any):
62 # NOISY-DEBUG: print("DEBUG: domain,res.status_code:", domain, res.status_code, res.reason)
64 cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ?", [
72 print("ERROR: failed SQL query:", domain)
75 def update_last_nodeinfo(domain: str):
76 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
78 cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
85 print("ERROR: failed SQL query:", domain)
90 def get_peers(domain: str) -> list:
91 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
95 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
97 if not res.ok or res.status_code >= 400:
98 print("WARNING: Cannot fetch peers:", domain)
99 update_last_error(domain, res)
101 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
105 print("WARNING: Some error during get():", domain)
107 update_last_nodeinfo(domain)
109 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
112 def post_json_api(domain: str, path: str, data: str) -> list:
113 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
116 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
118 if not res.ok or res.status_code >= 400:
119 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
120 update_last_error(domain, res)
123 update_last_nodeinfo(domain)
126 print("WARNING: Some error during post():", domain, path, data)
128 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
131 def fetch_nodeinfo(domain: str) -> list:
132 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
134 nodeinfo = fetch_wellknown_nodeinfo(domain)
135 # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
137 if len(nodeinfo) > 0:
138 # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
142 f"https://{domain}/nodeinfo/2.1.json",
143 f"https://{domain}/nodeinfo/2.1",
144 f"https://{domain}/nodeinfo/2.0.json",
145 f"https://{domain}/nodeinfo/2.0",
146 f"https://{domain}/nodeinfo/1.0",
147 f"https://{domain}/api/v1/instance"
151 for request in requests:
153 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
154 res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
156 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
157 if res.ok and res.json() is not None:
158 # NOISY-DEBUG: print("DEBUG: Success:", request)
161 elif not res.ok or res.status_code >= 400:
162 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
163 update_last_error(domain, res)
167 # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
170 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
171 if json is None or len(json) == 0:
172 print("WARNING: Failed fetching nodeinfo from domain:", domain)
174 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
177 def fetch_wellknown_nodeinfo(domain: str) -> list:
178 # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
182 res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
183 # NOISY-DEBUG: print("DEBUG: domain,res.ok:", domain, res.ok)
184 if res.ok and res.json() is not None:
185 nodeinfo = res.json()
186 # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
187 if "links" in nodeinfo:
188 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
189 for link in nodeinfo["links"]:
190 # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
191 if link["rel"] in nodeinfos:
192 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
193 res = reqto.get(link["href"])
194 # NOISY-DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
195 if res.ok and res.json() is not None:
196 # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
200 print("WARNING: Unknown 'rel' value:", domain, link["rel"])
202 print("WARNING: nodeinfo does not contain 'links':", domain)
205 print("WARNING: Failed fetching .well-known info:", domain)
208 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
211 def determine_software(domain: str) -> str:
212 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
215 json = fetch_nodeinfo(domain)
216 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
218 if json is None or len(json) == 0:
219 # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
222 # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
223 if "software" not in json or "name" not in json["software"]:
224 print("WARNING: JSON response does not include [software][name], guessing ...")
226 for element in {"uri", "title", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account"}:
230 # NOISY-DEBUG: print("DEBUG: Found elements:", found)
231 if found == len(json):
232 # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
235 print("WARNING: Cannot guess software type:", domain, found, len(json))
238 software = tidyup(json["software"]["name"])
240 # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
241 if software in ["akkoma", "rebased"]:
242 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
244 elif software in ["hometown", "ecko"]:
245 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
246 software = "mastodon"
247 elif software in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
248 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
250 elif software.find("/") > 0:
251 print("WARNING: Spliting of path:", software)
252 software = software.split("/")[-1];
253 elif software.find("|") > 0:
254 print("WARNING: Spliting of path:", software)
255 software = software.split("|")[0].strip();
258 print("WARNING: tidyup() left no software name behind:", domain)
261 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
264 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
265 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
268 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
279 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
282 def update_last_seen(blocker: str, blocked: str, block_level: str):
283 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
286 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
296 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
299 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
300 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
301 if blocker.find("@") > 0:
302 print("WARNING: Bad blocker:", blocker)
304 elif blocked.find("@") > 0:
305 print("WARNING: Bad blocked:", blocked)
308 print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
311 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
323 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
326 def add_instance(domain: str, origin: str, originator: str):
327 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
328 if domain.find("@") > 0:
329 print("WARNING: Bad domain name:", domain)
331 elif origin is not None and origin.find("@") > 0:
332 print("WARNING: Bad origin name:", origin)
335 software = determine_software(domain)
336 # NOISY-DEBUG: print("DEBUG: Determined software:", software)
338 print(f"INFO: Adding new instance {domain} (origin: {origin})")
341 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
353 print("ERROR: failed SQL query:", domain)
356 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
357 update_last_nodeinfo(domain)
359 def send_bot_post(instance: str, blocks: dict):
360 message = instance + " has blocked the following instances:\n\n"
365 blocks = blocks[0 : 19]
368 if block["reason"] == None or block["reason"] == '':
369 message = message + block["blocked"] + " with unspecified reason\n"
371 if len(block["reason"]) > 420:
372 block["reason"] = block["reason"][0:419] + "[…]"
374 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
377 message = message + "(the list has been truncated to the first 20 entries)"
379 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
381 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
382 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
383 headers=botheaders, timeout=10).json()
387 def get_mastodon_blocks(domain: str) -> dict:
388 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
390 "Suspended servers": [],
391 "Filtered media" : [],
392 "Limited servers" : [],
393 "Silenced servers" : [],
397 "Silenced instances": "Silenced servers",
398 "Suspended instances": "Suspended servers",
399 "Gesperrte Server": "Suspended servers",
400 "Gefilterte Medien": "Filtered media",
401 "Stummgeschaltete Server": "Silenced servers",
402 "停止済みのサーバー": "Suspended servers",
403 "メディアを拒否しているサーバー": "Filtered media",
404 "サイレンス済みのサーバー": "Silenced servers",
405 "שרתים מושעים": "Suspended servers",
406 "מדיה מסוננת": "Filtered media",
407 "שרתים מוגבלים": "Silenced servers",
408 "Serveurs suspendus": "Suspended servers",
409 "Médias filtrés": "Filtered media",
410 "Serveurs limités": "Silenced servers",
415 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
419 print("ERROR: Cannot fetch from domain:", domain)
422 for header in doc.find_all("h3"):
423 header_text = header.text
425 if header_text in translations:
426 header_text = translations[header_text]
428 if header_text in blocks:
429 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
430 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
431 blocks[header_text].append(
433 "domain": tidyup(line.find("span").text),
434 "hash" : tidyup(line.find("span")["title"][9:]),
435 "reason": tidyup(line.find_all("td")[1].text),
439 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
441 "reject" : blocks["Suspended servers"],
442 "media_removal" : blocks["Filtered media"],
443 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
446 def get_friendica_blocks(domain: str) -> dict:
447 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
452 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
456 print("WARNING: Failed to fetch /friendica from domain:", domain)
459 blocklist = doc.find(id="about_blocklist")
461 # Prevents exceptions:
462 if blocklist is None:
463 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
466 for line in blocklist.find("table").find_all("tr")[1:]:
468 "domain": tidyup(line.find_all("td")[0].text),
469 "reason": tidyup(line.find_all("td")[1].text)
472 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
477 def get_misskey_blocks(domain: str) -> dict:
478 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
488 # iterating through all "suspended" (follow-only in its terminology)
489 # instances page-by-page, since that troonware doesn't support
490 # sending them all at once
493 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
494 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
495 "sort" : "+caughtAt",
501 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
502 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
503 "sort" : "+caughtAt",
510 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
512 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
517 if instance["isSuspended"]:
518 blocks["suspended"].append(
520 "domain": tidyup(instance["host"]),
521 # no reason field, nothing
527 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
530 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
531 counter = counter + step
534 print("WARNING: Caught error, exiting loop:", domain)
539 # same shit, different asshole ("blocked" aka full suspend)
542 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
543 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
544 "sort" : "+caughtAt",
550 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
551 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
552 "sort" : "+caughtAt",
559 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
561 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
565 if instance["isBlocked"]:
566 blocks["blocked"].append({
567 "domain": tidyup(instance["host"]),
572 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
575 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
576 counter = counter + step
582 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
584 "reject" : blocks["blocked"],
585 "followers_only": blocks["suspended"]
589 print("WARNING: API request failed for domain:", domain)
592 def tidyup(string: str) -> str:
593 # some retards put their blocks in variable case
594 string = string.lower().strip()
596 # other retards put the port
597 string = re.sub("\:\d+$", "", string)
599 # bigger retards put the schema in their blocklist, sometimes even without slashes
600 string = re.sub("^https?\:(\/*)", "", string)
603 string = re.sub("\/$", "", string)
606 string = re.sub("^\@", "", string)
608 # the biggest retards of them all try to block individual users
609 string = re.sub("(.+)\@", "", string)