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 conn = sqlite3.connect("blocks.db")
30 def is_blacklisted(domain: str) -> bool:
31 # NOISY-DEBUG: print("DEBUG: Checking blacklist for domain:", domain)
33 for peer in blacklist:
34 # NOISY-DEBUG: print("DEBUG: domain,peer:", domain, peer)
38 # NOISY-DEBUG: print("DEBUG: blacklisted:", blacklisted)
41 def get_hash(domain: str) -> str:
42 # NOISY-DEBUG: print("DEBUG: Calculating hash for domain:", domain)
43 return sha256(domain.encode("utf-8")).hexdigest()
45 def update_last_blocked(domain: str):
46 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
49 c.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
56 print("ERROR: failed SQL query:", domain)
59 def update_last_error(domain: str, res: any):
60 # NOISY-DEBUG: print("DEBUG: domain,res.status_code:", domain, res.status_code, res.reason)
62 c.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ?", [
70 print("ERROR: failed SQL query:", domain)
73 def update_last_nodeinfo(domain: str):
74 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
76 c.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
83 print("ERROR: failed SQL query:", domain)
86 def get_peers(domain: str) -> list:
87 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
91 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=config["timeout"])
93 if not res.ok or res.status_code >= 400:
94 print("WARNING: Cannot fetch peers:", domain)
95 update_last_error(domain, res)
97 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
101 print("WARNING: Some error during get():", domain)
103 update_last_nodeinfo(domain)
105 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
108 def post_json_api(domain: str, path: str, data: str) -> list:
109 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
111 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=config["timeout"])
113 if not res.ok or res.status_code >= 400:
114 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
115 update_last_error(domain, res)
118 update_last_nodeinfo(domain)
121 print("WARNING: Some error during post():", domain, path, data)
123 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
126 def fetch_nodeinfo(domain: str) -> list:
127 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
130 f"https://{domain}/nodeinfo/2.1.json",
131 f"https://{domain}/nodeinfo/2.0",
132 f"https://{domain}/nodeinfo/2.0.json",
133 f"https://{domain}/nodeinfo/2.1",
134 f"https://{domain}/api/v1/instance"
138 for request in requests:
139 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
140 res = reqto.get(request, headers=headers, timeout=config["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 print("WARNING: Failed fetching nodeinfo from domain:", domain)
155 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
156 update_last_nodeinfo(domain)
158 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
161 def determine_software(domain: str) -> str:
162 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
166 json = fetch_nodeinfo(domain)
167 # NOISY-DEBUG: print("DEBUG: json():", len(json))
169 if json["software"]["name"] in ["akkoma", "rebased"]:
170 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, json["software"]["name"])
172 elif json["software"]["name"] in ["hometown", "ecko"]:
173 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, json["software"]["name"])
174 software = "mastodon"
175 elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
176 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, json["software"]["name"])
179 # NOISY-DEBUG: print("DEBUG: Using name:", domain, json["software"]["name"])
180 software = json["software"]["name"].lower()
183 print("WARNING: Could not determine software type:", domain)
185 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
188 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
189 # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
192 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
203 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
206 def update_last_seen(blocker: str, blocked: str, block_level: str):
207 # NOISY: print("--- Updating last_seen for:", blocker, blocked, block_level)
210 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
220 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
223 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
224 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
225 if blocker.find("@") > 0:
226 print("WARNING: Bad blocker:", blocker)
228 elif blocked.find("@") > 0:
229 print("WARNING: Bad blocked:", blocked)
232 print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
235 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
247 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
250 def add_instance(domain: str, origin: str, originator: str):
251 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
252 if domain.find("@") > 0:
253 print("WARNING: Bad domain name:", domain)
255 elif origin is not None and origin.find("@") > 0:
256 print("WARNING: Bad origin name:", origin)
259 print(f"--- Adding new instance {domain} (origin: {origin})")
262 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
268 determine_software(domain),
274 print("ERROR: failed SQL query:", domain)
277 def send_bot_post(instance: str, blocks: dict):
278 message = instance + " has blocked the following instances:\n\n"
283 blocks = blocks[0 : 19]
286 if block["reason"] == None or block["reason"] == '':
287 message = message + block["blocked"] + " with unspecified reason\n"
289 if len(block["reason"]) > 420:
290 block["reason"] = block["reason"][0:419] + "[…]"
292 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
295 message = message + "(the list has been truncated to the first 20 entries)"
297 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
299 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
300 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
301 headers=botheaders, timeout=10).json()
305 def get_mastodon_blocks(domain: str) -> dict:
306 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
308 "Suspended servers": [],
309 "Filtered media": [],
310 "Limited servers": [],
311 "Silenced servers": [],
315 "Silenced instances": "Silenced servers",
316 "Suspended instances": "Suspended servers",
317 "Gesperrte Server": "Suspended servers",
318 "Gefilterte Medien": "Filtered media",
319 "Stummgeschaltete Server": "Silenced servers",
320 "停止済みのサーバー": "Suspended servers",
321 "メディアを拒否しているサーバー": "Filtered media",
322 "サイレンス済みのサーバー": "Silenced servers",
323 "שרתים מושעים": "Suspended servers",
324 "מדיה מסוננת": "Filtered media",
325 "שרתים מוגבלים": "Silenced servers",
326 "Serveurs suspendus": "Suspended servers",
327 "Médias filtrés": "Filtered media",
328 "Serveurs limités": "Silenced servers",
333 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=config["timeout"]).text,
337 print("ERROR: Cannot fetch from domain:", domain)
340 for header in doc.find_all("h3"):
341 header_text = header.text
343 if header_text in translations:
344 header_text = translations[header_text]
346 if header_text in blocks:
347 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
348 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
349 blocks[header_text].append(
351 "domain": line.find("span").text,
352 "hash": line.find("span")["title"][9:],
353 "reason": line.find_all("td")[1].text.strip(),
357 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
359 "reject": blocks["Suspended servers"],
360 "media_removal": blocks["Filtered media"],
361 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
364 def get_friendica_blocks(domain: str) -> dict:
365 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
370 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=config["timeout"]).text,
374 print("WARNING: Failed to fetch /friendica from domain:", domain)
377 blocklist = doc.find(id="about_blocklist")
379 # Prevents exceptions:
380 if blocklist is None:
381 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
384 for line in blocklist.find("table").find_all("tr")[1:]:
386 "domain": line.find_all("td")[0].text.strip(),
387 "reason": line.find_all("td")[1].text.strip()
390 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
395 def get_misskey_blocks(domain: str) -> dict:
396 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
406 # iterating through all "suspended" (follow-only in its terminology)
407 # instances page-by-page, since that troonware doesn't support
408 # sending them all at once
411 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
412 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
419 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
420 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
428 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
430 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
435 if instance["isSuspended"]:
436 blocks["suspended"].append(
438 "domain": instance["host"],
439 # no reason field, nothing
445 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
448 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
449 counter = counter + step
452 print("WARNING: Caught error, exiting loop:", domain)
457 # same shit, different asshole ("blocked" aka full suspend)
460 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
461 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
468 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
469 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
477 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
479 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
483 if instance["isBlocked"]:
484 blocks["blocked"].append({
485 "domain": instance["host"],
490 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
493 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
494 counter = counter + step
500 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
502 "reject": blocks["blocked"],
503 "followers_only": blocks["suspended"]
507 print("WARNING: API request failed for domain:", domain)
510 def tidyup(domain: str) -> str:
511 # some retards put their blocks in variable case
512 domain = domain.lower()
514 # other retards put the port
515 domain = re.sub("\:\d+$", "", domain)
517 # bigger retards put the schema in their blocklist, sometimes even without slashes
518 domain = re.sub("^https?\:(\/*)", "", domain)
521 domain = re.sub("\/$", "", domain)
524 domain = re.sub("^\@", "", domain)
526 # the biggest retards of them all try to block individual users
527 domain = re.sub("(.+)\@", "", domain)