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