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