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 = ? WHERE domain = ?", [
44 print("ERROR: failed SQL query:", domain)
47 def update_last_error(domain: str, res: any):
48 # NOISY-DEBUG: print("DEBUG: domain,res.status_code", domain, res.status_code)
51 c.execute("UPDATE instances SET last_status_code = ? WHERE domain = ?", [
57 print("ERROR: failed SQL query:", domain)
60 def update_last_nodeinfo(domain: str):
61 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
64 c.execute("UPDATE instances SET last_nodeinfo = ? WHERE domain = ?", [
70 print("ERROR: failed SQL query:", domain)
73 def get_peers(domain: str) -> list:
74 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
78 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=config["timeout"])
80 if not res.ok or res.status_code >= 400:
81 print("WARNING: Cannot fetch peers:", domain)
82 update_last_error(domain, res)
84 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
88 print("WARNING: Some error during get():", domain)
90 update_last_nodeinfo(domain)
92 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
95 def post_json_api(domain: str, path: str, data: str) -> list:
97 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
98 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=config["timeout"])
100 if not res.ok or res.status_code >= 400:
101 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
102 update_last_error(domain, res)
105 update_last_nodeinfo(domain)
108 print("WARNING: Some error during post():", domain, path, data)
110 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
113 def fetch_nodeinfo(domain: str) -> list:
114 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
117 f"https://{domain}/nodeinfo/2.1.json",
118 f"https://{domain}/nodeinfo/2.0",
119 f"https://{domain}/nodeinfo/2.0.json",
120 f"https://{domain}/nodeinfo/2.1",
121 f"https://{domain}/api/v1/instance"
125 for request in requests:
126 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
127 res = reqto.get(request, headers=headers, timeout=config["timeout"])
129 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
130 if res.ok and res.json() is not None:
131 # NOISY-DEBUG: print("DEBUG: Success:", request)
134 elif not res.ok or res.status_code >= 400:
135 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
136 update_last_error(domain, res)
140 print("WARNING: Failed fetching nodeinfo from domain:", domain)
142 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
143 update_last_nodeinfo(domain)
145 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
148 def determine_software(domain: str) -> str:
149 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
153 json = fetch_nodeinfo(domain)
154 # NOISY-DEBUG: print("DEBUG: json():", len(json))
156 if json["software"]["name"] in ["akkoma", "rebased"]:
157 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, json["software"]["name"])
159 elif json["software"]["name"] in ["hometown", "ecko"]:
160 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, json["software"]["name"])
161 software = "mastodon"
162 elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
163 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, json["software"]["name"])
166 # NOISY-DEBUG: print("DEBUG: Using name:", domain, json["software"]["name"])
167 software = json["software"]["name"]
170 print("WARNING: Could not determine software type:", domain)
172 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
175 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
176 # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
179 "UPDATE blocks SET reason = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
189 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
192 def update_last_seen(last_seen: int, blocker: str, blocked: str, block_level: str):
193 # NOISY: print("--- Updating last_seen:", last_seen, blocker, blocked, block_level)
196 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
206 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
209 def block_instance(blocker: str, blocked: str, reason: str, block_level: str, first_added: int, last_seen: int):
210 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level,first_added,last_seen:", blocker, blocked, reason, block_level, first_added, last_seen)
211 if blocker.find("@") > 0:
212 print("WARNING: Bad blocker:", blocker)
214 elif blocked.find("@") > 0:
215 print("WARNING: Bad blocked:", blocked)
218 print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
221 "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
233 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
236 def add_instance(domain: str, origin: str, originator: str):
237 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
238 if domain.find("@") > 0:
239 print("WARNING: Bad domain name:", domain)
241 elif origin is not None and origin.find("@") > 0:
242 print("WARNING: Bad origin name:", origin)
245 print(f"--- Adding new instance {domain} (origin: {origin})")
248 "INSERT INTO instances (domain,origin,originator,hash,software) VALUES (?, ?, ?, ?, ?)",
254 determine_software(domain)
259 print("ERROR: failed SQL query:", domain)
262 def send_bot_post(instance: str, blocks: dict):
263 message = instance + " has blocked the following instances:\n\n"
268 blocks = blocks[0 : 19]
271 if block["reason"] == None or block["reason"] == '':
272 message = message + block["blocked"] + " with unspecified reason\n"
274 if len(block["reason"]) > 420:
275 block["reason"] = block["reason"][0:419] + "[…]"
277 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
280 message = message + "(the list has been truncated to the first 20 entries)"
282 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
284 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
285 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
286 headers=botheaders, timeout=10).json()
290 def get_mastodon_blocks(domain: str) -> dict:
291 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
293 "Suspended servers": [],
294 "Filtered media": [],
295 "Limited servers": [],
296 "Silenced servers": [],
300 "Silenced instances": "Silenced servers",
301 "Suspended instances": "Suspended servers",
302 "Gesperrte Server": "Suspended servers",
303 "Gefilterte Medien": "Filtered media",
304 "Stummgeschaltete Server": "Silenced servers",
305 "停止済みのサーバー": "Suspended servers",
306 "メディアを拒否しているサーバー": "Filtered media",
307 "サイレンス済みのサーバー": "Silenced servers",
308 "שרתים מושעים": "Suspended servers",
309 "מדיה מסוננת": "Filtered media",
310 "שרתים מוגבלים": "Silenced servers",
311 "Serveurs suspendus": "Suspended servers",
312 "Médias filtrés": "Filtered media",
313 "Serveurs limités": "Silenced servers",
318 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=config["timeout"]).text,
322 print("ERROR: Cannot fetch from domain:", domain)
325 for header in doc.find_all("h3"):
326 header_text = header.text
328 if header_text in translations:
329 header_text = translations[header_text]
331 if header_text in blocks:
332 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
333 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
334 blocks[header_text].append(
336 "domain": line.find("span").text,
337 "hash": line.find("span")["title"][9:],
338 "reason": line.find_all("td")[1].text.strip(),
342 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
344 "reject": blocks["Suspended servers"],
345 "media_removal": blocks["Filtered media"],
346 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
349 def get_friendica_blocks(domain: str) -> dict:
350 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
355 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=config["timeout"]).text,
359 print("WARNING: Failed to fetch /friendica from domain:", domain)
362 blocklist = doc.find(id="about_blocklist")
364 # Prevents exceptions:
365 if blocklist is None:
366 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
369 for line in blocklist.find("table").find_all("tr")[1:]:
371 "domain": line.find_all("td")[0].text.strip(),
372 "reason": line.find_all("td")[1].text.strip()
375 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
380 def get_misskey_blocks(domain: str) -> dict:
381 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
391 # iterating through all "suspended" (follow-only in its terminology)
392 # instances page-by-page, since that troonware doesn't support
393 # sending them all at once
396 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
397 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
404 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
405 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
413 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
415 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
420 if instance["isSuspended"]:
421 blocks["suspended"].append(
423 "domain": instance["host"],
424 # no reason field, nothing
430 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
433 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
434 counter = counter + step
437 print("WARNING: Caught error, exiting loop:", domain)
442 # same shit, different asshole ("blocked" aka full suspend)
445 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
446 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
453 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
454 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
462 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
464 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
468 if instance["isBlocked"]:
469 blocks["blocked"].append({
470 "domain": instance["host"],
475 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
478 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
479 counter = counter + step
485 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
487 "reject": blocks["blocked"],
488 "followers_only": blocks["suspended"]
492 print("WARNING: API request failed for domain:", domain)
495 def tidyup(domain: str) -> str:
496 # some retards put their blocks in variable case
497 domain = domain.lower()
499 # other retards put the port
500 domain = re.sub("\:\d+$", "", domain)
502 # bigger retards put the schema in their blocklist, sometimes even without slashes
503 domain = re.sub("^https?\:(\/*)", "", domain)
506 domain = re.sub("\/$", "", domain)
509 domain = re.sub("^\@", "", domain)
511 # the biggest retards of them all try to block individual users
512 domain = re.sub("(.+)\@", "", domain)