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)
128 f"https://{domain}/nodeinfo/2.1.json",
129 f"https://{domain}/nodeinfo/2.1",
130 f"https://{domain}/nodeinfo/2.0.json",
131 f"https://{domain}/nodeinfo/2.0",
132 f"https://{domain}/nodeinfo/1.0",
133 f"https://{domain}/api/v1/instance"
137 for request in requests:
139 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
140 res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
142 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
143 if res.ok and res.json() is not None:
144 # NOISY-DEBUG: print("DEBUG: Success:", request)
147 elif not res.ok or res.status_code >= 400:
148 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
149 update_last_error(domain, res)
153 # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
156 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
157 if json is None or len(json) == 0:
158 print("WARNING: Failed fetching nodeinfo from domain:", domain)
160 # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
163 def determine_software(domain: str) -> str:
164 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
167 json = fetch_nodeinfo(domain)
168 # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
170 if json is None or len(json) == 0:
171 # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
174 # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
175 if "software" not in json or "name" not in json["software"]:
176 print("WARNING: JSON response does not include [software][name], guessing ...")
178 for element in {"uri", "title", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account"}:
182 # NOISY-DEBUG: print("DEBUG: Found elements:", found)
183 if found == len(json):
184 # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
187 print("WARNING: Cannot guess software type:", domain, found, len(json))
190 software = tidyup(json["software"]["name"])
192 # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
193 if software in ["akkoma", "rebased"]:
194 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
196 elif software in ["hometown", "ecko"]:
197 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
198 software = "mastodon"
199 elif software in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
200 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
202 elif software.find("/") > 0:
203 print("WARNING: Spliting of path:", software)
204 software = software.split("/")[-1];
207 print("WARNING: tidyup() left no software name behind:", domain)
210 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
213 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
214 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
217 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
228 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
231 def update_last_seen(blocker: str, blocked: str, block_level: str):
232 # NOISY: # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
235 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
245 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
248 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
249 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
250 if blocker.find("@") > 0:
251 print("WARNING: Bad blocker:", blocker)
253 elif blocked.find("@") > 0:
254 print("WARNING: Bad blocked:", blocked)
257 print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
260 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
272 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
275 def add_instance(domain: str, origin: str, originator: str):
276 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
277 if domain.find("@") > 0:
278 print("WARNING: Bad domain name:", domain)
280 elif origin is not None and origin.find("@") > 0:
281 print("WARNING: Bad origin name:", origin)
284 software = determine_software(domain)
285 # NOISY-DEBUG: print("DEBUG: Determined software:", software)
287 print(f"INFO: Adding new instance {domain} (origin: {origin})")
290 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
302 print("ERROR: failed SQL query:", domain)
305 # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
306 update_last_nodeinfo(domain)
308 def send_bot_post(instance: str, blocks: dict):
309 message = instance + " has blocked the following instances:\n\n"
314 blocks = blocks[0 : 19]
317 if block["reason"] == None or block["reason"] == '':
318 message = message + block["blocked"] + " with unspecified reason\n"
320 if len(block["reason"]) > 420:
321 block["reason"] = block["reason"][0:419] + "[…]"
323 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
326 message = message + "(the list has been truncated to the first 20 entries)"
328 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
330 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
331 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
332 headers=botheaders, timeout=10).json()
336 def get_mastodon_blocks(domain: str) -> dict:
337 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
339 "Suspended servers": [],
340 "Filtered media" : [],
341 "Limited servers" : [],
342 "Silenced servers" : [],
346 "Silenced instances": "Silenced servers",
347 "Suspended instances": "Suspended servers",
348 "Gesperrte Server": "Suspended servers",
349 "Gefilterte Medien": "Filtered media",
350 "Stummgeschaltete Server": "Silenced servers",
351 "停止済みのサーバー": "Suspended servers",
352 "メディアを拒否しているサーバー": "Filtered media",
353 "サイレンス済みのサーバー": "Silenced servers",
354 "שרתים מושעים": "Suspended servers",
355 "מדיה מסוננת": "Filtered media",
356 "שרתים מוגבלים": "Silenced servers",
357 "Serveurs suspendus": "Suspended servers",
358 "Médias filtrés": "Filtered media",
359 "Serveurs limités": "Silenced servers",
364 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
368 print("ERROR: Cannot fetch from domain:", domain)
371 for header in doc.find_all("h3"):
372 header_text = header.text
374 if header_text in translations:
375 header_text = translations[header_text]
377 if header_text in blocks:
378 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
379 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
380 blocks[header_text].append(
382 "domain": tidyup(line.find("span").text),
383 "hash" : tidyup(line.find("span")["title"][9:]),
384 "reason": tidyup(line.find_all("td")[1].text),
388 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
390 "reject" : blocks["Suspended servers"],
391 "media_removal" : blocks["Filtered media"],
392 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
395 def get_friendica_blocks(domain: str) -> dict:
396 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
401 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
405 print("WARNING: Failed to fetch /friendica from domain:", domain)
408 blocklist = doc.find(id="about_blocklist")
410 # Prevents exceptions:
411 if blocklist is None:
412 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
415 for line in blocklist.find("table").find_all("tr")[1:]:
417 "domain": tidyup(line.find_all("td")[0].text),
418 "reason": tidyup(line.find_all("td")[1].text)
421 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
426 def get_misskey_blocks(domain: str) -> dict:
427 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
437 # iterating through all "suspended" (follow-only in its terminology)
438 # instances page-by-page, since that troonware doesn't support
439 # sending them all at once
442 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
443 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
444 "sort" : "+caughtAt",
450 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
451 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
452 "sort" : "+caughtAt",
459 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
461 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
466 if instance["isSuspended"]:
467 blocks["suspended"].append(
469 "domain": tidyup(instance["host"]),
470 # no reason field, nothing
476 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
479 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
480 counter = counter + step
483 print("WARNING: Caught error, exiting loop:", domain)
488 # same shit, different asshole ("blocked" aka full suspend)
491 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
492 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
493 "sort" : "+caughtAt",
499 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
500 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
501 "sort" : "+caughtAt",
508 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
510 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
514 if instance["isBlocked"]:
515 blocks["blocked"].append({
516 "domain": tidyup(instance["host"]),
521 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
524 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
525 counter = counter + step
531 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
533 "reject" : blocks["blocked"],
534 "followers_only": blocks["suspended"]
538 print("WARNING: API request failed for domain:", domain)
541 def tidyup(string: str) -> str:
542 # some retards put their blocks in variable case
543 string = string.lower().strip()
545 # other retards put the port
546 string = re.sub("\:\d+$", "", string)
548 # bigger retards put the schema in their blocklist, sometimes even without slashes
549 string = re.sub("^https?\:(\/*)", "", string)
552 string = re.sub("\/$", "", string)
555 string = re.sub("^\@", "", string)
557 # the biggest retards of them all try to block individual users
558 string = re.sub("(.+)\@", "", string)