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 get_hash(domain: str) -> str:
31 # NOISY-DEBUG: print("DEBUG: Calculating hash for domain:", domain)
32 return sha256(domain.encode("utf-8")).hexdigest()
34 def update_last_blocked(domain: str):
35 # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
38 c.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
45 print("ERROR: failed SQL query:", domain)
48 def update_last_error(domain: str, res: any):
49 # NOISY-DEBUG: print("DEBUG: domain,res.status_code", domain, res.status_code)
52 c.execute("UPDATE instances SET last_status_code = ?, last_updated = ? WHERE domain = ?", [
59 print("ERROR: failed SQL query:", domain)
62 def update_last_nodeinfo(domain: str):
63 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
66 c.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
73 print("ERROR: failed SQL query:", domain)
76 def get_peers(domain: str) -> list:
77 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
81 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=config["timeout"])
83 if not res.ok or res.status_code >= 400:
84 print("WARNING: Cannot fetch peers:", domain)
85 update_last_error(domain, res)
87 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
91 print("WARNING: Some error during get():", domain)
93 update_last_nodeinfo(domain)
95 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
98 def post_json_api(domain: str, path: str, data: str) -> list:
100 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
101 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=config["timeout"])
103 if not res.ok or res.status_code >= 400:
104 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
105 update_last_error(domain, res)
108 update_last_nodeinfo(domain)
111 print("WARNING: Some error during post():", domain, path, data)
113 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
116 def fetch_nodeinfo(domain: str) -> list:
117 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
120 f"https://{domain}/nodeinfo/2.1.json",
121 f"https://{domain}/nodeinfo/2.0",
122 f"https://{domain}/nodeinfo/2.0.json",
123 f"https://{domain}/nodeinfo/2.1",
124 f"https://{domain}/api/v1/instance"
128 for request in requests:
129 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
130 res = reqto.get(request, headers=headers, timeout=config["timeout"])
132 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
133 if res.ok and res.json() is not None:
134 # NOISY-DEBUG: print("DEBUG: Success:", request)
137 elif not res.ok or res.status_code >= 400:
138 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
139 update_last_error(domain, res)
143 print("WARNING: Failed fetching nodeinfo from domain:", domain)
145 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
146 update_last_nodeinfo(domain)
148 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
151 def determine_software(domain: str) -> str:
152 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
156 json = fetch_nodeinfo(domain)
157 # NOISY-DEBUG: print("DEBUG: json():", len(json))
159 if json["software"]["name"] in ["akkoma", "rebased"]:
160 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, json["software"]["name"])
162 elif json["software"]["name"] in ["hometown", "ecko"]:
163 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, json["software"]["name"])
164 software = "mastodon"
165 elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
166 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, json["software"]["name"])
169 # NOISY-DEBUG: print("DEBUG: Using name:", domain, json["software"]["name"])
170 software = json["software"]["name"]
173 print("WARNING: Could not determine software type:", domain)
175 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
178 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
179 # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
182 "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
193 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
196 def update_last_seen(blocker: str, blocked: str, block_level: str):
197 # NOISY: print("--- Updating last_seen for:", blocker, blocked, block_level)
200 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
210 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
213 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
214 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
215 if blocker.find("@") > 0:
216 print("WARNING: Bad blocker:", blocker)
218 elif blocked.find("@") > 0:
219 print("WARNING: Bad blocked:", blocked)
222 print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
225 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
237 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
240 def add_instance(domain: str, origin: str, originator: str):
241 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
242 if domain.find("@") > 0:
243 print("WARNING: Bad domain name:", domain)
245 elif origin is not None and origin.find("@") > 0:
246 print("WARNING: Bad origin name:", origin)
249 print(f"--- Adding new instance {domain} (origin: {origin})")
252 "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
258 determine_software(domain),
264 print("ERROR: failed SQL query:", domain)
267 def send_bot_post(instance: str, blocks: dict):
268 message = instance + " has blocked the following instances:\n\n"
273 blocks = blocks[0 : 19]
276 if block["reason"] == None or block["reason"] == '':
277 message = message + block["blocked"] + " with unspecified reason\n"
279 if len(block["reason"]) > 420:
280 block["reason"] = block["reason"][0:419] + "[…]"
282 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
285 message = message + "(the list has been truncated to the first 20 entries)"
287 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
289 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
290 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
291 headers=botheaders, timeout=10).json()
295 def get_mastodon_blocks(domain: str) -> dict:
296 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
298 "Suspended servers": [],
299 "Filtered media": [],
300 "Limited servers": [],
301 "Silenced servers": [],
305 "Silenced instances": "Silenced servers",
306 "Suspended instances": "Suspended servers",
307 "Gesperrte Server": "Suspended servers",
308 "Gefilterte Medien": "Filtered media",
309 "Stummgeschaltete Server": "Silenced servers",
310 "停止済みのサーバー": "Suspended servers",
311 "メディアを拒否しているサーバー": "Filtered media",
312 "サイレンス済みのサーバー": "Silenced servers",
313 "שרתים מושעים": "Suspended servers",
314 "מדיה מסוננת": "Filtered media",
315 "שרתים מוגבלים": "Silenced servers",
316 "Serveurs suspendus": "Suspended servers",
317 "Médias filtrés": "Filtered media",
318 "Serveurs limités": "Silenced servers",
323 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=config["timeout"]).text,
327 print("ERROR: Cannot fetch from domain:", domain)
330 for header in doc.find_all("h3"):
331 header_text = header.text
333 if header_text in translations:
334 header_text = translations[header_text]
336 if header_text in blocks:
337 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
338 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
339 blocks[header_text].append(
341 "domain": line.find("span").text,
342 "hash": line.find("span")["title"][9:],
343 "reason": line.find_all("td")[1].text.strip(),
347 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
349 "reject": blocks["Suspended servers"],
350 "media_removal": blocks["Filtered media"],
351 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
354 def get_friendica_blocks(domain: str) -> dict:
355 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
360 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=config["timeout"]).text,
364 print("WARNING: Failed to fetch /friendica from domain:", domain)
367 blocklist = doc.find(id="about_blocklist")
369 # Prevents exceptions:
370 if blocklist is None:
371 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
374 for line in blocklist.find("table").find_all("tr")[1:]:
376 "domain": line.find_all("td")[0].text.strip(),
377 "reason": line.find_all("td")[1].text.strip()
380 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
385 def get_misskey_blocks(domain: str) -> dict:
386 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
396 # iterating through all "suspended" (follow-only in its terminology)
397 # instances page-by-page, since that troonware doesn't support
398 # sending them all at once
401 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
402 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
409 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
410 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
418 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
420 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
425 if instance["isSuspended"]:
426 blocks["suspended"].append(
428 "domain": instance["host"],
429 # no reason field, nothing
435 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
438 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
439 counter = counter + step
442 print("WARNING: Caught error, exiting loop:", domain)
447 # same shit, different asshole ("blocked" aka full suspend)
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({
458 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
459 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
467 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
469 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
473 if instance["isBlocked"]:
474 blocks["blocked"].append({
475 "domain": instance["host"],
480 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
483 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
484 counter = counter + step
490 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
492 "reject": blocks["blocked"],
493 "followers_only": blocks["suspended"]
497 print("WARNING: API request failed for domain:", domain)
500 def tidyup(domain: str) -> str:
501 # some retards put their blocks in variable case
502 domain = domain.lower()
504 # other retards put the port
505 domain = re.sub("\:\d+$", "", domain)
507 # bigger retards put the schema in their blocklist, sometimes even without slashes
508 domain = re.sub("^https?\:(\/*)", "", domain)
511 domain = re.sub("\/$", "", domain)
514 domain = re.sub("^\@", "", domain)
516 # the biggest retards of them all try to block individual users
517 domain = re.sub("(.+)\@", "", domain)