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=5)
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=5)
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=5)
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 SELECT ?, ?, ?, ?, ?, ?",
233 print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
236 def add_instance(domain: str, origin: str):
237 # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin)
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("--- Adding new instance:", domain, origin)
248 "INSERT INTO instances (domain,origin,hash,software) VALUES (?, ?, ?, ?)",
253 determine_software(domain)
258 print("ERROR: failed SQL query:", domain)
261 def send_bot_post(instance: str, blocks: dict):
262 message = instance + " has blocked the following instances:\n\n"
267 blocks = blocks[0 : 19]
270 if block["reason"] == None or block["reason"] == '':
271 message = message + block["blocked"] + " with unspecified reason\n"
273 if len(block["reason"]) > 420:
274 block["reason"] = block["reason"][0:419] + "[…]"
276 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
279 message = message + "(the list has been truncated to the first 20 entries)"
281 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
283 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
284 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
285 headers=botheaders, timeout=10).json()
289 def get_mastodon_blocks(domain: str) -> dict:
290 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
292 "Suspended servers": [],
293 "Filtered media": [],
294 "Limited servers": [],
295 "Silenced servers": [],
299 "Silenced instances": "Silenced servers",
300 "Suspended instances": "Suspended servers",
301 "Gesperrte Server": "Suspended servers",
302 "Gefilterte Medien": "Filtered media",
303 "Stummgeschaltete Server": "Silenced servers",
304 "停止済みのサーバー": "Suspended servers",
305 "メディアを拒否しているサーバー": "Filtered media",
306 "サイレンス済みのサーバー": "Silenced servers",
307 "שרתים מושעים": "Suspended servers",
308 "מדיה מסוננת": "Filtered media",
309 "שרתים מוגבלים": "Silenced servers",
310 "Serveurs suspendus": "Suspended servers",
311 "Médias filtrés": "Filtered media",
312 "Serveurs limités": "Silenced servers",
317 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
321 print("ERROR: Cannot fetch from domain:", domain)
324 for header in doc.find_all("h3"):
325 header_text = header.text
327 if header_text in translations:
328 header_text = translations[header_text]
330 if header_text in blocks:
331 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
332 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
333 blocks[header_text].append(
335 "domain": line.find("span").text,
336 "hash": line.find("span")["title"][9:],
337 "reason": line.find_all("td")[1].text.strip(),
341 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
343 "reject": blocks["Suspended servers"],
344 "media_removal": blocks["Filtered media"],
345 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
348 def get_friendica_blocks(domain: str) -> dict:
349 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
354 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
358 print("WARNING: Failed to fetch /friendica from domain:", domain)
361 blocklist = doc.find(id="about_blocklist")
363 # Prevents exceptions:
364 if blocklist is None:
365 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
368 for line in blocklist.find("table").find_all("tr")[1:]:
370 "domain": line.find_all("td")[0].text.strip(),
371 "reason": line.find_all("td")[1].text.strip()
374 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
379 def get_misskey_blocks(domain: str) -> dict:
380 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
390 # iterating through all "suspended" (follow-only in its terminology)
391 # instances page-by-page, since that troonware doesn't support
392 # sending them all at once
395 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
396 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
403 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
404 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
412 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
414 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
419 if instance["isSuspended"]:
420 blocks["suspended"].append(
422 "domain": instance["host"],
423 # no reason field, nothing
429 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
432 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
433 counter = counter + step
436 print("WARNING: Caught error, exiting loop:", domain)
441 # same shit, different asshole ("blocked" aka full suspend)
444 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
445 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
452 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
453 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
461 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
463 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
467 if instance["isBlocked"]:
468 blocks["blocked"].append({
469 "domain": instance["host"],
474 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
477 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
478 counter = counter + step
484 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
486 "reject": blocks["blocked"],
487 "followers_only": blocks["suspended"]
491 print("WARNING: API request failed for domain:", domain)
494 def tidyup(domain: str) -> str:
495 # some retards put their blocks in variable case
496 domain = domain.lower()
498 # other retards put the port
499 domain = re.sub("\:\d+$", "", domain)
501 # bigger retards put the schema in their blocklist, sometimes even without slashes
502 domain = re.sub("^https?\:(\/*)", "", domain)
505 domain = re.sub("\/$", "", domain)
508 domain = re.sub("^\@", "", domain)
510 # the biggest retards of them all try to block individual users
511 domain = re.sub("(.+)\@", "", domain)