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_error(domain: str, res: any):
35 # NOISY-DEBUG: print("DEBUG: domain,res.status_code", domain, res.status_code)
38 c.execute("UPDATE instances SET last_status_code = ? WHERE domain = ?", [
44 print("ERROR: failed SQL query:", domain)
47 def update_last_nodeinfo(domain: str):
48 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
51 c.execute("UPDATE instances SET last_nodeinfo = ? WHERE domain = ?", [
57 print("ERROR: failed SQL query:", domain)
60 def get_peers(domain: str) -> list:
61 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
65 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=5)
67 if not res.ok or res.status_code >= 400:
68 print("WARNING: Cannot fetch peers:", domain)
69 update_last_error(domain, res)
71 # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
75 print("WARNING: Some error during get():", domain)
77 update_last_nodeinfo(domain)
79 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
82 def post_json_api(domain: str, path: str, data: str) -> list:
84 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
85 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=5)
87 if not res.ok or res.status_code >= 400:
88 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
89 update_last_error(domain, res)
92 update_last_nodeinfo(domain)
95 print("WARNING: Some error during post():", domain, path, data)
97 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
100 def fetch_nodeinfo(domain: str) -> list:
101 # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
104 f"https://{domain}/nodeinfo/2.1.json",
105 f"https://{domain}/nodeinfo/2.0",
106 f"https://{domain}/nodeinfo/2.0.json",
107 f"https://{domain}/nodeinfo/2.1",
108 f"https://{domain}/api/v1/instance"
112 for request in requests:
113 # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
114 res = reqto.get(request, headers=headers, timeout=5)
116 # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
117 if res.ok and res.json() is not None:
118 # NOISY-DEBUG: print("DEBUG: Success:", request)
121 elif not res.ok or res.status_code >= 400:
122 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
123 update_last_error(domain, res)
127 print("WARNING: Failed fetching nodeinfo from domain:", domain)
129 # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
130 update_last_nodeinfo(domain)
132 # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
135 def determine_software(domain: str) -> str:
136 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
140 json = fetch_nodeinfo(domain)
141 # NOISY-DEBUG: print("DEBUG: json():", len(json))
143 if json["software"]["name"] in ["akkoma", "rebased"]:
144 # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, json["software"]["name"])
146 elif json["software"]["name"] in ["hometown", "ecko"]:
147 # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, json["software"]["name"])
148 software = "mastodon"
149 elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
150 # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, json["software"]["name"])
153 # NOISY-DEBUG: print("DEBUG: Using name:", domain, json["software"]["name"])
154 software = json["software"]["name"]
157 print("WARNING: Could not determine software type:", domain)
159 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
162 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
163 # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
166 "UPDATE blocks SET reason = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
176 print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
179 def update_last_seen(last_seen: int, blocker: str, blocked: str, block_level: str):
180 # NOISY: print("--- Updating last_seen:", last_seen, blocker, blocked, block_level)
183 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
193 print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
196 def block_instance(blocker: str, blocked: str, reason: str, block_level: str, first_added: int, last_seen: int):
197 # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level,first_added,last_seen:", blocker, blocked, reason, block_level, first_added, last_seen)
198 if blocker.find("@") > 0:
199 print("WARNING: Bad blocker:", blocker)
201 elif blocked.find("@") > 0:
202 print("WARNING: Bad blocked:", blocked)
205 print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
208 "INSERT INTO blocks SELECT ?, ?, ?, ?, ?, ?",
220 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
223 def add_instance(domain: str):
224 # NOISY-DEBUG: print("DEBUG: domain:", domain)
225 if domain.find("@") > 0:
226 print("WARNING: Bad domain name:", domain)
229 print("--- Adding new instance:", domain)
232 "INSERT INTO instances (domain,hash,software) VALUES (?, ?, ?)",
236 determine_software(domain)
241 print("ERROR: failed SQL query:", domain)
244 def send_bot_post(instance: str, blocks: dict):
245 message = instance + " has blocked the following instances:\n\n"
250 blocks = blocks[0 : 19]
253 if block["reason"] == None or block["reason"] == '':
254 message = message + block["blocked"] + " with unspecified reason\n"
256 if len(block["reason"]) > 420:
257 block["reason"] = block["reason"][0:419] + "[…]"
259 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
262 message = message + "(the list has been truncated to the first 20 entries)"
264 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
266 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
267 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
268 headers=botheaders, timeout=10).json()
272 def get_mastodon_blocks(domain: str) -> dict:
273 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
275 "Suspended servers": [],
276 "Filtered media": [],
277 "Limited servers": [],
278 "Silenced servers": [],
282 "Silenced instances": "Silenced servers",
283 "Suspended instances": "Suspended servers",
284 "Gesperrte Server": "Suspended servers",
285 "Gefilterte Medien": "Filtered media",
286 "Stummgeschaltete Server": "Silenced servers",
287 "停止済みのサーバー": "Suspended servers",
288 "メディアを拒否しているサーバー": "Filtered media",
289 "サイレンス済みのサーバー": "Silenced servers",
290 "שרתים מושעים": "Suspended servers",
291 "מדיה מסוננת": "Filtered media",
292 "שרתים מוגבלים": "Silenced servers",
293 "Serveurs suspendus": "Suspended servers",
294 "Médias filtrés": "Filtered media",
295 "Serveurs limités": "Silenced servers",
300 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
304 print("ERROR: Cannot fetch from domain:", domain)
307 for header in doc.find_all("h3"):
308 header_text = header.text
310 if header_text in translations:
311 header_text = translations[header_text]
313 if header_text in blocks:
314 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
315 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
316 blocks[header_text].append(
318 "domain": line.find("span").text,
319 "hash": line.find("span")["title"][9:],
320 "reason": line.find_all("td")[1].text.strip(),
324 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
326 "reject": blocks["Suspended servers"],
327 "media_removal": blocks["Filtered media"],
328 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
331 def get_friendica_blocks(domain: str) -> dict:
332 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
337 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
341 print("WARNING: Failed to fetch /friendica from domain:", domain)
344 blocklist = doc.find(id="about_blocklist")
346 # Prevents exceptions:
347 if blocklist is None:
348 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
351 for line in blocklist.find("table").find_all("tr")[1:]:
353 "domain": line.find_all("td")[0].text.strip(),
354 "reason": line.find_all("td")[1].text.strip()
357 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
362 def get_misskey_blocks(domain: str) -> dict:
363 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
373 # iterating through all "suspended" (follow-only in its terminology)
374 # instances page-by-page, since that troonware doesn't support
375 # sending them all at once
378 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
379 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
386 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
387 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
395 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
397 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
402 if instance["isSuspended"]:
403 blocks["suspended"].append(
405 "domain": instance["host"],
406 # no reason field, nothing
412 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
415 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
416 counter = counter + step
419 print("WARNING: Caught error, exiting loop:", domain)
424 # same shit, different asshole ("blocked" aka full suspend)
427 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
428 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
435 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
436 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
444 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
446 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
450 if instance["isBlocked"]:
451 blocks["blocked"].append({
452 "domain": instance["host"],
457 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
460 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
461 counter = counter + step
467 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
469 "reject": blocks["blocked"],
470 "followers_only": blocks["suspended"]
474 print("WARNING: API request failed for domain:", domain)
477 def tidyup(domain: str) -> str:
478 # some retards put their blocks in variable case
479 domain = domain.lower()
481 # other retards put the port
482 domain = re.sub("\:\d+$", "", domain)
484 # bigger retards put the schema in their blocklist, sometimes even without slashes
485 domain = re.sub("^https?\:(\/*)", "", domain)
488 domain = re.sub("\/$", "", domain)
491 domain = re.sub("^\@", "", domain)
493 # the biggest retards of them all try to block individual users
494 domain = re.sub("(.+)\@", "", domain)