]> git.mxchange.org Git - fba.git/blob - fba.py
Continued:
[fba.git] / fba.py
1 from bs4 import BeautifulSoup
2 from hashlib import sha256
3
4 import reqto
5 import re
6 import sqlite3
7 import json
8 import sys
9 import time
10
11 with open("config.json") as f:
12     config = json.loads(f.read())
13
14 blacklist = [
15     "activitypub-troll.cf",
16     "gab.best",
17     "4chan.icu",
18     "social.shrimpcam.pw",
19     "mastotroll.netz.org",
20     "ngrok.io",
21 ]
22
23 headers = {
24     "user-agent": config["useragent"]
25 }
26
27 conn = sqlite3.connect("blocks.db")
28 c = conn.cursor()
29
30 def is_blacklisted(domain: str) -> bool:
31     # NOISY-DEBUG: print("DEBUG: Checking blacklist for domain:", domain)
32     blacklisted = False
33     for peer in blacklist:
34         # NOISY-DEBUG: print("DEBUG: domain,peer:", domain, peer)
35         if peer in domain:
36             blacklisted = True
37
38     # NOISY-DEBUG: print("DEBUG: blacklisted:", blacklisted)
39     return blacklisted
40
41 def get_hash(domain: str) -> str:
42     # NOISY-DEBUG: print("DEBUG: Calculating hash for domain:", domain)
43     return sha256(domain.encode("utf-8")).hexdigest()
44
45 def update_last_blocked(domain: str):
46     # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
47
48     try:
49         c.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
50             time.time(),
51             time.time(),
52             domain
53         ])
54
55     except:
56         print("ERROR: failed SQL query:", domain)
57         sys.exit(255)
58
59 def update_last_error(domain: str, res: any):
60     # NOISY-DEBUG: print("DEBUG: domain,res.status_code", domain, res.status_code)
61
62     try:
63         c.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ?", [
64             res.status_code,
65             res.text,
66             time.time(),
67             domain
68         ])
69
70     except:
71         print("ERROR: failed SQL query:", domain)
72         sys.exit(255)
73
74 def update_last_nodeinfo(domain: str):
75     # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
76
77     try:
78         c.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
79             time.time(),
80             time.time(),
81             domain
82         ])
83
84     except:
85         print("ERROR: failed SQL query:", domain)
86         sys.exit(255)
87
88 def get_peers(domain: str) -> list:
89     # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
90     peers = None
91
92     try:
93         res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=config["timeout"])
94
95         if not res.ok or res.status_code >= 400:
96             print("WARNING: Cannot fetch peers:", domain)
97             update_last_error(domain, res)
98         else:
99             # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
100             peers = res.json()
101
102     except:
103         print("WARNING: Some error during get():", domain)
104
105     update_last_nodeinfo(domain)
106
107     # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
108     return peers
109
110 def post_json_api(domain: str, path: str, data: str) -> list:
111     try:
112         # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
113         res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=config["timeout"])
114
115         if not res.ok or res.status_code >= 400:
116             print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
117             update_last_error(domain, res)
118             raise
119
120         update_last_nodeinfo(domain)
121         json = res.json()
122     except:
123         print("WARNING: Some error during post():", domain, path, data)
124
125     # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
126     return json
127
128 def fetch_nodeinfo(domain: str) -> list:
129     # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
130
131     requests = [
132        f"https://{domain}/nodeinfo/2.1.json",
133        f"https://{domain}/nodeinfo/2.0",
134        f"https://{domain}/nodeinfo/2.0.json",
135        f"https://{domain}/nodeinfo/2.1",
136        f"https://{domain}/api/v1/instance"
137     ]
138
139     json = None
140     for request in requests:
141         # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
142         res = reqto.get(request, headers=headers, timeout=config["timeout"])
143
144         # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
145         if res.ok and res.json() is not None:
146             # NOISY-DEBUG: print("DEBUG: Success:", request)
147             json = res.json()
148             break
149         elif not res.ok or res.status_code >= 400:
150             # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
151             update_last_error(domain, res)
152             continue
153
154     if json is None:
155         print("WARNING: Failed fetching nodeinfo from domain:", domain)
156
157     # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
158     update_last_nodeinfo(domain)
159
160     # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
161     return json
162
163 def determine_software(domain: str) -> str:
164     # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
165     software = None
166
167     try:
168         json = fetch_nodeinfo(domain)
169         # NOISY-DEBUG: print("DEBUG: json():", len(json))
170
171         if json["software"]["name"] in ["akkoma", "rebased"]:
172             # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, json["software"]["name"])
173             software = "pleroma"
174         elif json["software"]["name"] in ["hometown", "ecko"]:
175             # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, json["software"]["name"])
176             software = "mastodon"
177         elif json["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
178             # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, json["software"]["name"])
179             software = "misskey"
180         else:
181             # NOISY-DEBUG: print("DEBUG: Using name:", domain, json["software"]["name"])
182             software = json["software"]["name"].lower()
183
184     except:
185         print("WARNING: Could not determine software type:", domain)
186
187     # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
188     return software
189
190 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
191     # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
192     try:
193         c.execute(
194             "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
195             (
196                 reason,
197                 time.time(),
198                 blocker,
199                 blocked,
200                 block_level
201             ),
202         )
203
204     except:
205         print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
206         sys.exit(255)
207
208 def update_last_seen(blocker: str, blocked: str, block_level: str):
209     # NOISY: print("--- Updating last_seen for:", blocker, blocked, block_level)
210     try:
211         c.execute(
212             "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
213             (
214                 time.time(),
215                 blocker,
216                 blocked,
217                 block_level
218             )
219         )
220
221     except:
222         print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
223         sys.exit(255)
224
225 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
226     # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
227     if blocker.find("@") > 0:
228         print("WARNING: Bad blocker:", blocker)
229         raise
230     elif blocked.find("@") > 0:
231         print("WARNING: Bad blocked:", blocked)
232         raise
233
234     print("--- New block:", blocker, blocked, reason, block_level, first_added, last_seen)
235     try:
236         c.execute(
237             "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
238              (
239                  blocker,
240                  blocked,
241                  reason,
242                  block_level,
243                  time.time(),
244                  time.time()
245              ),
246         )
247
248     except:
249         print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
250         sys.exit(255)
251
252 def add_instance(domain: str, origin: str, originator: str):
253     # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
254     if domain.find("@") > 0:
255         print("WARNING: Bad domain name:", domain)
256         raise
257     elif origin is not None and origin.find("@") > 0:
258         print("WARNING: Bad origin name:", origin)
259         raise
260
261     print(f"--- Adding new instance {domain} (origin: {origin})")
262     try:
263         c.execute(
264             "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
265             (
266                domain,
267                origin,
268                originator,
269                get_hash(domain),
270                determine_software(domain),
271                time.time()
272             ),
273         )
274
275     except:
276         print("ERROR: failed SQL query:", domain)
277         sys.exit(255)
278
279 def send_bot_post(instance: str, blocks: dict):
280     message = instance + " has blocked the following instances:\n\n"
281     truncated = False
282
283     if len(blocks) > 20:
284         truncated = True
285         blocks = blocks[0 : 19]
286
287     for block in blocks:
288         if block["reason"] == None or block["reason"] == '':
289             message = message + block["blocked"] + " with unspecified reason\n"
290         else:
291             if len(block["reason"]) > 420:
292                 block["reason"] = block["reason"][0:419] + "[…]"
293
294             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
295
296     if truncated:
297         message = message + "(the list has been truncated to the first 20 entries)"
298
299     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
300
301     req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
302         data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
303         headers=botheaders, timeout=10).json()
304
305     return True
306
307 def get_mastodon_blocks(domain: str) -> dict:
308     # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
309     blocks = {
310         "Suspended servers": [],
311         "Filtered media": [],
312         "Limited servers": [],
313         "Silenced servers": [],
314     }
315
316     translations = {
317         "Silenced instances": "Silenced servers",
318         "Suspended instances": "Suspended servers",
319         "Gesperrte Server": "Suspended servers",
320         "Gefilterte Medien": "Filtered media",
321         "Stummgeschaltete Server": "Silenced servers",
322         "停止済みのサーバー": "Suspended servers",
323         "メディアを拒否しているサーバー": "Filtered media",
324         "サイレンス済みのサーバー": "Silenced servers",
325         "שרתים מושעים": "Suspended servers",
326         "מדיה מסוננת": "Filtered media",
327         "שרתים מוגבלים": "Silenced servers",
328         "Serveurs suspendus": "Suspended servers",
329         "Médias filtrés": "Filtered media",
330         "Serveurs limités": "Silenced servers",
331     }
332
333     try:
334         doc = BeautifulSoup(
335             reqto.get(f"https://{domain}/about/more", headers=headers, timeout=config["timeout"]).text,
336             "html.parser",
337         )
338     except:
339         print("ERROR: Cannot fetch from domain:", domain)
340         return {}
341
342     for header in doc.find_all("h3"):
343         header_text = header.text
344
345         if header_text in translations:
346             header_text = translations[header_text]
347
348         if header_text in blocks:
349             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
350             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
351                 blocks[header_text].append(
352                     {
353                         "domain": line.find("span").text,
354                         "hash": line.find("span")["title"][9:],
355                         "reason": line.find_all("td")[1].text.strip(),
356                     }
357                 )
358
359     # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
360     return {
361         "reject": blocks["Suspended servers"],
362         "media_removal": blocks["Filtered media"],
363         "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
364     }
365
366 def get_friendica_blocks(domain: str) -> dict:
367     # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
368     blocks = []
369
370     try:
371         doc = BeautifulSoup(
372             reqto.get(f"https://{domain}/friendica", headers=headers, timeout=config["timeout"]).text,
373             "html.parser",
374         )
375     except:
376         print("WARNING: Failed to fetch /friendica from domain:", domain)
377         return {}
378
379     blocklist = doc.find(id="about_blocklist")
380
381     # Prevents exceptions:
382     if blocklist is None:
383         # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
384         return {}
385
386     for line in blocklist.find("table").find_all("tr")[1:]:
387         blocks.append({
388             "domain": line.find_all("td")[0].text.strip(),
389             "reason": line.find_all("td")[1].text.strip()
390         })
391
392     # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
393     return {
394         "reject": blocks
395     }
396
397 def get_misskey_blocks(domain: str) -> dict:
398     # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
399     blocks = {
400         "suspended": [],
401         "blocked": []
402     }
403
404     try:
405         counter = 0
406         step = 99
407         while True:
408             # iterating through all "suspended" (follow-only in its terminology)
409             # instances page-by-page, since that troonware doesn't support
410             # sending them all at once
411             try:
412                 if counter == 0:
413                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
414                     doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
415                         "sort": "+caughtAt",
416                         "host": None,
417                         "suspended": True,
418                         "limit": step
419                     }))
420                 else:
421                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
422                     doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
423                         "sort": "+caughtAt",
424                         "host": None,
425                         "suspended": True,
426                         "limit": step,
427                         "offset": counter-1
428                     }))
429
430                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
431                 if len(doc) == 0:
432                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
433                     break
434
435                 for instance in doc:
436                     # just in case
437                     if instance["isSuspended"]:
438                         blocks["suspended"].append(
439                             {
440                                 "domain": instance["host"],
441                                 # no reason field, nothing
442                                 "reason": ""
443                             }
444                         )
445
446                 if len(doc) < step:
447                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
448                     break
449
450                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
451                 counter = counter + step
452
453             except:
454                 print("WARNING: Caught error, exiting loop:", domain)
455                 counter = 0
456                 break
457
458         while True:
459             # same shit, different asshole ("blocked" aka full suspend)
460             try:
461                 if counter == 0:
462                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
463                     doc = post_json_api(domain,"/api/federation/instances", json.dumps({
464                         "sort": "+caughtAt",
465                         "host": None,
466                         "blocked": True,
467                         "limit": step
468                     }))
469                 else:
470                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
471                     doc = post_json_api(domain,"/api/federation/instances", json.dumps({
472                         "sort": "+caughtAt",
473                         "host": None,
474                         "blocked": True,
475                         "limit": step,
476                         "offset": counter-1
477                     }))
478
479                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
480                 if len(doc) == 0:
481                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
482                     break
483
484                 for instance in doc:
485                     if instance["isBlocked"]:
486                         blocks["blocked"].append({
487                             "domain": instance["host"],
488                             "reason": ""
489                         })
490
491                 if len(doc) < step:
492                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
493                     break
494
495                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
496                 counter = counter + step
497
498             except:
499                 counter = 0
500                 break
501
502         # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
503         return {
504             "reject": blocks["blocked"],
505             "followers_only": blocks["suspended"]
506         }
507
508     except:
509         print("WARNING: API request failed for domain:", domain)
510         return {}
511
512 def tidyup(domain: str) -> str:
513     # some retards put their blocks in variable case
514     domain = domain.lower()
515
516     # other retards put the port
517     domain = re.sub("\:\d+$", "", domain)
518
519     # bigger retards put the schema in their blocklist, sometimes even without slashes
520     domain = re.sub("^https?\:(\/*)", "", domain)
521
522     # and trailing slash
523     domain = re.sub("\/$", "", domain)
524
525     # and the @
526     domain = re.sub("^\@", "", domain)
527
528     # the biggest retards of them all try to block individual users
529     domain = re.sub("(.+)\@", "", domain)
530
531     return domain