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 "user-agent": config["useragent"]
27 connection = sqlite3.connect("blocks.db")
28 cursor = connection.cursor()
30 def is_blacklisted(domain: str) -> bool:
32 for peer in blacklist:
38 def get_hash(domain: str) -> str:
39 return sha256(domain.encode("utf-8")).hexdigest()
41 def update_last_blocked(domain: str):
42 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
44 cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
51 print("ERROR: failed SQL query:", domain)
54 def update_last_error(domain: str, res: any):
55 # NOISY-DEBUG: print("DEBUG: domain,res.status_code:", domain, res.status_code, res.reason)
57 cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ?", [
65 print("ERROR: failed SQL query:", domain)
68 def update_last_nodeinfo(domain: str):
69 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
71 cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
78 print("ERROR: failed SQL query:", domain)
83 def get_peers(domain: str) -> list:
84 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
88 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
90 if not res.ok or res.status_code >= 400:
91 print("WARNING: Cannot fetch peers:", domain)
92 update_last_error(domain, res)
94 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
98 print("WARNING: Some error during get():", domain)
100 update_last_nodeinfo(domain)
102 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
105 def post_json_api(domain: str, path: str, data: str) -> list:
106 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
109 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
111 if not res.ok or res.status_code >= 400:
112 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
113 update_last_error(domain, res)
116 update_last_nodeinfo(domain)
119 print("WARNING: Some error during post():", domain, path, data)
121 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
124 def fetch_nodeinfo(domain: str) -> list:
125 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
127 nodeinfo = fetch_wellknown_nodeinfo(domain)
128 # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
130 if len(nodeinfo) > 0:
131 # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
135 f"https://{domain}/nodeinfo/2.1.json",
136 f"https://{domain}/nodeinfo/2.1",
137 f"https://{domain}/nodeinfo/2.0.json",
138 f"https://{domain}/nodeinfo/2.0",
139 f"https://{domain}/nodeinfo/1.0",
140 f"https://{domain}/api/v1/instance"
144 for request in requests:
146 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
147 res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
149 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
150 if res.ok and res.json() is not None:
151 # NOISY-DEBUG: print("DEBUG: Success:", request)
154 elif not res.ok or res.status_code >= 400:
155 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
156 update_last_error(domain, res)
160 # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
163 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
164 if json is None or len(json) == 0:
165 print("WARNING: Failed fetching nodeinfo from domain:", domain)
167 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
170 def fetch_wellknown_nodeinfo(domain: str) -> list:
171 # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
175 res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
176 # NOISY-DEBUG: print("DEBUG: domain,res.ok:", domain, res.ok)
177 if res.ok and res.json() is not None:
178 nodeinfo = res.json()
179 # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
180 if "links" in nodeinfo:
181 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
182 for link in nodeinfo["links"]:
183 # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
184 if link["rel"] in ["http://nodeinfo.diaspora.software/ns/schema/2.0", "http://nodeinfo.diaspora.software/ns/schema/2.1"]:
185 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
186 res = reqto.get(link["href"])
187 # NOISY-DEBUG: print("DEBUG: href,res.ok:", link["href"], res.ok)
188 if res.ok and res.json() is not None:
189 # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
193 print("WARNING: Unknown 'rel' value:", domain, link["rel"])
195 print("WARNING: nodeinfo does not contain 'links':", domain)
198 print("WARNING: Failed fetching .well-known info:", domain)
201 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
204 def determine_software(domain: str) -> str:
205 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
208 json = fetch_nodeinfo(domain)
209 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
211 if json is None or len(json) == 0:
212 # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
215 # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
216 if "software" not in json or "name" not in json["software"]:
217 print("WARNING: JSON response does not include [software][name], guessing ...")
219 for element in {"uri", "title", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account"}:
223 # NOISY-DEBUG: print("DEBUG: Found elements:", found)
224 if found == len(json):
225 # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
228 print("WARNING: Cannot guess software type:", domain, found, len(json))
231 software = tidyup(json["software"]["name"])
233 # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
234 if software in ["akkoma", "rebased"]:
235 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
237 elif software in ["hometown", "ecko"]:
238 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
239 software = "mastodon"
240 elif software in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
241 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
243 elif software.find("/") > 0:
244 print("WARNING: Spliting of path:", software)
245 software = software.split("/")[-1];
246 elif software.find("|") > 0:
247 print("WARNING: Spliting of path:", software)
248 software = software.split("|")[0].strip();
251 print("WARNING: tidyup() left no software name behind:", domain)
254 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
257 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
258 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
261 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
272 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
275 def update_last_seen(blocker: str, blocked: str, block_level: str):
276 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
279 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
289 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
292 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
293 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
294 if blocker.find("@") > 0:
295 print("WARNING: Bad blocker:", blocker)
297 elif blocked.find("@") > 0:
298 print("WARNING: Bad blocked:", blocked)
301 print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
304 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
316 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
319 def add_instance(domain: str, origin: str, originator: str):
320 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
321 if domain.find("@") > 0:
322 print("WARNING: Bad domain name:", domain)
324 elif origin is not None and origin.find("@") > 0:
325 print("WARNING: Bad origin name:", origin)
328 software = determine_software(domain)
329 # NOISY-DEBUG: print("DEBUG: Determined software:", software)
331 print(f"INFO: Adding new instance {domain} (origin: {origin})")
334 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
346 print("ERROR: failed SQL query:", domain)
349 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
350 update_last_nodeinfo(domain)
352 def send_bot_post(instance: str, blocks: dict):
353 message = instance + " has blocked the following instances:\n\n"
358 blocks = blocks[0 : 19]
361 if block["reason"] == None or block["reason"] == '':
362 message = message + block["blocked"] + " with unspecified reason\n"
364 if len(block["reason"]) > 420:
365 block["reason"] = block["reason"][0:419] + "[…]"
367 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
370 message = message + "(the list has been truncated to the first 20 entries)"
372 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
374 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
375 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
376 headers=botheaders, timeout=10).json()
380 def get_mastodon_blocks(domain: str) -> dict:
381 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
383 "Suspended servers": [],
384 "Filtered media" : [],
385 "Limited servers" : [],
386 "Silenced servers" : [],
390 "Silenced instances": "Silenced servers",
391 "Suspended instances": "Suspended servers",
392 "Gesperrte Server": "Suspended servers",
393 "Gefilterte Medien": "Filtered media",
394 "Stummgeschaltete Server": "Silenced servers",
395 "停止済みのサーバー": "Suspended servers",
396 "メディアを拒否しているサーバー": "Filtered media",
397 "サイレンス済みのサーバー": "Silenced servers",
398 "שרתים מושעים": "Suspended servers",
399 "מדיה מסוננת": "Filtered media",
400 "שרתים מוגבלים": "Silenced servers",
401 "Serveurs suspendus": "Suspended servers",
402 "Médias filtrés": "Filtered media",
403 "Serveurs limités": "Silenced servers",
408 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
412 print("ERROR: Cannot fetch from domain:", domain)
415 for header in doc.find_all("h3"):
416 header_text = header.text
418 if header_text in translations:
419 header_text = translations[header_text]
421 if header_text in blocks:
422 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
423 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
424 blocks[header_text].append(
426 "domain": tidyup(line.find("span").text),
427 "hash" : tidyup(line.find("span")["title"][9:]),
428 "reason": tidyup(line.find_all("td")[1].text),
432 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
434 "reject" : blocks["Suspended servers"],
435 "media_removal" : blocks["Filtered media"],
436 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
439 def get_friendica_blocks(domain: str) -> dict:
440 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
445 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
449 print("WARNING: Failed to fetch /friendica from domain:", domain)
452 blocklist = doc.find(id="about_blocklist")
454 # Prevents exceptions:
455 if blocklist is None:
456 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
459 for line in blocklist.find("table").find_all("tr")[1:]:
461 "domain": tidyup(line.find_all("td")[0].text),
462 "reason": tidyup(line.find_all("td")[1].text)
465 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
470 def get_misskey_blocks(domain: str) -> dict:
471 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
481 # iterating through all "suspended" (follow-only in its terminology)
482 # instances page-by-page, since that troonware doesn't support
483 # sending them all at once
486 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
487 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
488 "sort" : "+caughtAt",
494 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
495 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
496 "sort" : "+caughtAt",
503 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
505 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
510 if instance["isSuspended"]:
511 blocks["suspended"].append(
513 "domain": tidyup(instance["host"]),
514 # no reason field, nothing
520 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
523 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
524 counter = counter + step
527 print("WARNING: Caught error, exiting loop:", domain)
532 # same shit, different asshole ("blocked" aka full suspend)
535 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
536 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
537 "sort" : "+caughtAt",
543 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
544 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
545 "sort" : "+caughtAt",
552 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
554 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
558 if instance["isBlocked"]:
559 blocks["blocked"].append({
560 "domain": tidyup(instance["host"]),
565 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
568 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
569 counter = counter + step
575 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
577 "reject" : blocks["blocked"],
578 "followers_only": blocks["suspended"]
582 print("WARNING: API request failed for domain:", domain)
585 def tidyup(string: str) -> str:
586 # some retards put their blocks in variable case
587 string = string.lower().strip()
589 # other retards put the port
590 string = re.sub("\:\d+$", "", string)
592 # bigger retards put the schema in their blocklist, sometimes even without slashes
593 string = re.sub("^https?\:(\/*)", "", string)
596 string = re.sub("\/$", "", string)
599 string = re.sub("^\@", "", string)
601 # the biggest retards of them all try to block individual users
602 string = re.sub("(.+)\@", "", string)