1 from bs4 import BeautifulSoup
2 from hashlib import sha256
10 with open("config.json") as f:
11 config = json.loads(f.read())
14 "activitypub-troll.cf",
17 "social.shrimpcam.pw",
22 "user-agent": config["useragent"]
25 conn = sqlite3.connect("blocks.db")
28 def get_hash(domain: str) -> str:
29 # NOISY-DEBUG: print("DEBUG: Calculating hash for domain:", domain)
30 return sha256(domain.encode("utf-8")).hexdigest()
32 def get_peers(domain: str) -> str:
33 # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
37 res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=5)
40 print("WARNING: Cannot fetch peers:", domain, res.status_code)
42 # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
45 def post_json_api(domain: str, path: str, data: str) -> list:
46 # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
47 res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=5)
50 print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
54 # NOISY-DEBUG: print("DEBUG: Returning doc():", len(doc))
57 def determine_software(domain: str) -> str:
58 # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
61 res = reqto.get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5)
63 # NOISY-DEBUG: print("DEBUG: domain,res.ok,res.status_code:", domain, res.ok, res.status_code)
64 if res.status_code == 404:
65 res = reqto.get(f"https://{domain}/nodeinfo/2.0", headers=headers, timeout=5)
67 if res.status_code == 404:
68 res = reqto.get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5)
70 if res.ok and "text/html" in res.headers["content-type"]:
71 res = reqto.get(f"https://{domain}/nodeinfo/2.1", headers=headers, timeout=5)
75 # NOISY-DEBUG: print("DEBUG: json():", len(json))
77 if json["software"]["name"] in ["akkoma", "rebased"]:
79 elif json["software"]["name"] in ["hometown", "ecko"]:
81 elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
84 software = json["software"]["name"]
85 elif res.status_code == 404:
86 res = reqto.get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5)
90 print("WARNING: Failed fetching instance meta data")
92 # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
95 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
96 # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
99 "UPDATE blocks SET reason = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
109 print("ERROR: failed SQL query")
112 def update_last_seen(last_seen: int, blocker: str, blocked: str, block_level: str):
113 # NOISY: print("--- Updating last_seen:", last_seen, blocker, blocked, block_level)
116 "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
126 print("ERROR: failed SQL query")
129 def block_instance(blocker: str, blocked: str, reason: str, block_level: str, first_added: int, last_seen: int):
130 print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
133 "INSERT INTO blocks SELECT ?, ?, ?, ?, ?, ?",
145 print("ERROR: failed SQL query")
148 def add_instance(domain: str):
149 print("--- Adding new instance:", domain)
152 "INSERT INTO instances SELECT ?, ?, ?",
156 determine_software(domain)
161 print("ERROR: failed SQL query")
164 def send_bot_post(instance: str, blocks: dict):
165 message = instance + " has blocked the following instances:\n\n"
170 blocks = blocks[0 : 19]
173 if block["reason"] == None or block["reason"] == '':
174 message = message + block["blocked"] + " with unspecified reason\n"
176 if len(block["reason"]) > 420:
177 block["reason"] = block["reason"][0:419] + "[…]"
179 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
182 message = message + "(the list has been truncated to the first 20 entries)"
184 botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
186 req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
187 data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
188 headers=botheaders, timeout=10).json()
192 def get_mastodon_blocks(domain: str) -> dict:
193 # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
195 "Suspended servers": [],
196 "Filtered media": [],
197 "Limited servers": [],
198 "Silenced servers": [],
202 "Silenced instances": "Silenced servers",
203 "Suspended instances": "Suspended servers",
204 "Gesperrte Server": "Suspended servers",
205 "Gefilterte Medien": "Filtered media",
206 "Stummgeschaltete Server": "Silenced servers",
207 "停止済みのサーバー": "Suspended servers",
208 "メディアを拒否しているサーバー": "Filtered media",
209 "サイレンス済みのサーバー": "Silenced servers",
210 "שרתים מושעים": "Suspended servers",
211 "מדיה מסוננת": "Filtered media",
212 "שרתים מוגבלים": "Silenced servers",
213 "Serveurs suspendus": "Suspended servers",
214 "Médias filtrés": "Filtered media",
215 "Serveurs limités": "Silenced servers",
220 reqto.get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
224 print("ERROR: Cannot fetch from domain:", domain)
227 for header in doc.find_all("h3"):
228 header_text = header.text
230 if header_text in translations:
231 header_text = translations[header_text]
233 if header_text in blocks:
234 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
235 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
236 blocks[header_text].append(
238 "domain": line.find("span").text,
239 "hash": line.find("span")["title"][9:],
240 "reason": line.find_all("td")[1].text.strip(),
244 # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
246 "reject": blocks["Suspended servers"],
247 "media_removal": blocks["Filtered media"],
248 "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
251 def get_friendica_blocks(domain: str) -> dict:
252 # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
257 reqto.get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
261 print("WARNING: Failed to fetch /friendica from domain:", domain)
264 blocklist = doc.find(id="about_blocklist")
266 # Prevents exceptions:
267 if blocklist is None:
268 # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
271 for line in blocklist.find("table").find_all("tr")[1:]:
273 "domain": line.find_all("td")[0].text.strip(),
274 "reason": line.find_all("td")[1].text.strip()
277 # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
282 def get_misskey_blocks(domain: str) -> dict:
283 # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
293 # iterating through all "suspended" (follow-only in its terminology)
294 # instances page-by-page, since that troonware doesn't support
295 # sending them all at once
298 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
299 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
306 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
307 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
315 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
317 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
322 if instance["isSuspended"]:
323 blocks["suspended"].append(
325 "domain": instance["host"],
326 # no reason field, nothing
331 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
332 counter = counter + step
335 print("WARNING: Caught error, exiting loop:", domain)
340 # same shit, different asshole ("blocked" aka full suspend)
343 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
344 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
351 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
352 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
360 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
362 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
366 if instance["isBlocked"]:
367 blocks["blocked"].append({
368 "domain": instance["host"],
371 counter = counter + step
377 # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
379 "reject": blocks["blocked"],
380 "followers_only": blocks["suspended"]
384 print("WARNING: API request failed for domain:", domain)
387 def tidyup(domain: str) -> str:
388 # some retards put their blocks in variable case
389 domain = domain.lower()
391 # other retards put the port
392 domain = re.sub("\:\d+$", "", domain)
394 # bigger retards put the schema in their blocklist, sometimes even without slashes
395 domain = re.sub("^https?\:(\/*)", "", domain)
398 domain = re.sub("\/$", "", domain)
401 domain = re.sub("^\@", "", domain)
403 # the biggest retards of them all try to block individual users
404 domain = re.sub("(.+)\@", "", domain)