]> 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, originator: str):
237     # NOISY-DEBUG: print("DEBUG: domain,originator:", domain, originator)
238     if domain.find("@") > 0:
239         print("WARNING: Bad domain name:", domain)
240         raise
241     elif originator is not None and originator.find("@") > 0:
242         print("WARNING: Bad originator name:", originator)
243         raise
244
245     print("--- Adding new instance:", domain, originator)
246     try:
247         c.execute(
248             "INSERT INTO instances (domain,originator,hash,software) VALUES (?, ?, ?, ?)",
249             (
250                domain,
251                originator,
252                get_hash(domain),
253                determine_software(domain)
254             ),
255         )
256
257     except:
258         print("ERROR: failed SQL query:", domain)
259         sys.exit(255)
260
261 def send_bot_post(instance: str, blocks: dict):
262     message = instance + " has blocked the following instances:\n\n"
263     truncated = False
264
265     if len(blocks) > 20:
266         truncated = True
267         blocks = blocks[0 : 19]
268
269     for block in blocks:
270         if block["reason"] == None or block["reason"] == '':
271             message = message + block["blocked"] + " with unspecified reason\n"
272         else:
273             if len(block["reason"]) > 420:
274                 block["reason"] = block["reason"][0:419] + "[…]"
275
276             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
277
278     if truncated:
279         message = message + "(the list has been truncated to the first 20 entries)"
280
281     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
282
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()
286
287     return True
288
289 def get_mastodon_blocks(domain: str) -> dict:
290     # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
291     blocks = {
292         "Suspended servers": [],
293         "Filtered media": [],
294         "Limited servers": [],
295         "Silenced servers": [],
296     }
297
298     translations = {
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",
313     }
314
315     try:
316         doc = BeautifulSoup(
317             reqto.get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
318             "html.parser",
319         )
320     except:
321         print("ERROR: Cannot fetch from domain:", domain)
322         return {}
323
324     for header in doc.find_all("h3"):
325         header_text = header.text
326
327         if header_text in translations:
328             header_text = translations[header_text]
329
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(
334                     {
335                         "domain": line.find("span").text,
336                         "hash": line.find("span")["title"][9:],
337                         "reason": line.find_all("td")[1].text.strip(),
338                     }
339                 )
340
341     # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
342     return {
343         "reject": blocks["Suspended servers"],
344         "media_removal": blocks["Filtered media"],
345         "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
346     }
347
348 def get_friendica_blocks(domain: str) -> dict:
349     # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
350     blocks = []
351
352     try:
353         doc = BeautifulSoup(
354             reqto.get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
355             "html.parser",
356         )
357     except:
358         print("WARNING: Failed to fetch /friendica from domain:", domain)
359         return {}
360
361     blocklist = doc.find(id="about_blocklist")
362
363     # Prevents exceptions:
364     if blocklist is None:
365         # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
366         return {}
367
368     for line in blocklist.find("table").find_all("tr")[1:]:
369         blocks.append({
370             "domain": line.find_all("td")[0].text.strip(),
371             "reason": line.find_all("td")[1].text.strip()
372         })
373
374     # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
375     return {
376         "reject": blocks
377     }
378
379 def get_misskey_blocks(domain: str) -> dict:
380     # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
381     blocks = {
382         "suspended": [],
383         "blocked": []
384     }
385
386     try:
387         counter = 0
388         step = 99
389         while True:
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
393             try:
394                 if counter == 0:
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({
397                         "sort": "+caughtAt",
398                         "host": None,
399                         "suspended": True,
400                         "limit": step
401                     }))
402                 else:
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({
405                         "sort": "+caughtAt",
406                         "host": None,
407                         "suspended": True,
408                         "limit": step,
409                         "offset": counter-1
410                     }))
411
412                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
413                 if len(doc) == 0:
414                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
415                     break
416
417                 for instance in doc:
418                     # just in case
419                     if instance["isSuspended"]:
420                         blocks["suspended"].append(
421                             {
422                                 "domain": instance["host"],
423                                 # no reason field, nothing
424                                 "reason": ""
425                             }
426                         )
427
428                 if len(doc) < step:
429                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
430                     break
431
432                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
433                 counter = counter + step
434
435             except:
436                 print("WARNING: Caught error, exiting loop:", domain)
437                 counter = 0
438                 break
439
440         while True:
441             # same shit, different asshole ("blocked" aka full suspend)
442             try:
443                 if counter == 0:
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({
446                         "sort": "+caughtAt",
447                         "host": None,
448                         "blocked": True,
449                         "limit": step
450                     }))
451                 else:
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({
454                         "sort": "+caughtAt",
455                         "host": None,
456                         "blocked": True,
457                         "limit": step,
458                         "offset": counter-1
459                     }))
460
461                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
462                 if len(doc) == 0:
463                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
464                     break
465
466                 for instance in doc:
467                     if instance["isBlocked"]:
468                         blocks["blocked"].append({
469                             "domain": instance["host"],
470                             "reason": ""
471                         })
472
473                 if len(doc) < step:
474                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
475                     break
476
477                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
478                 counter = counter + step
479
480             except:
481                 counter = 0
482                 break
483
484         # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
485         return {
486             "reject": blocks["blocked"],
487             "followers_only": blocks["suspended"]
488         }
489
490     except:
491         print("WARNING: API request failed for domain:", domain)
492         return {}
493
494 def tidyup(domain: str) -> str:
495     # some retards put their blocks in variable case
496     domain = domain.lower()
497
498     # other retards put the port
499     domain = re.sub("\:\d+$", "", domain)
500
501     # bigger retards put the schema in their blocklist, sometimes even without slashes
502     domain = re.sub("^https?\:(\/*)", "", domain)
503
504     # and trailing slash
505     domain = re.sub("\/$", "", domain)
506
507     # and the @
508     domain = re.sub("^\@", "", domain)
509
510     # the biggest retards of them all try to block individual users
511     domain = re.sub("(.+)\@", "", domain)
512
513     return domain