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