]> git.mxchange.org Git - fba.git/blob - fetch_blocks.py
Move useragent to config
[fba.git] / fetch_blocks.py
1 from requests import get
2 from requests import post
3 from hashlib import sha256
4 import sqlite3
5 from bs4 import BeautifulSoup
6 from json import dumps
7 from json import loads
8 import re
9 from time import time
10
11 with open("config.json") as f:
12     config = loads(f.read())
13
14 headers = {
15     "user-agent": config["useragent"]
16 }
17
18
19 def get_mastodon_blocks(domain: str) -> dict:
20     blocks = {
21         "Suspended servers": [],
22         "Filtered media": [],
23         "Limited servers": [],
24         "Silenced servers": [],
25     }
26
27     translations = {
28         "Silenced instances": "Silenced servers",
29         "Suspended instances": "Suspended servers",
30         "Gesperrte Server": "Suspended servers",
31         "Gefilterte Medien": "Filtered media",
32         "Stummgeschaltete Server": "Silenced servers",
33         "停止済みのサーバー": "Suspended servers",
34         "メディアを拒否しているサーバー": "Filtered media",
35         "サイレンス済みのサーバー": "Silenced servers",
36         "שרתים מושעים": "Suspended servers",
37         "מדיה מסוננת": "Filtered media",
38         "שרתים מוגבלים": "Silenced servers",
39         "Serveurs suspendus": "Suspended servers",
40         "Médias filtrés": "Filtered media",
41         "Serveurs limités": "Silenced servers",
42     }
43
44     try:
45         doc = BeautifulSoup(
46             get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
47             "html.parser",
48         )
49     except:
50         return {}
51
52     for header in doc.find_all("h3"):
53         header_text = header.text
54         if header_text in translations:
55             header_text = translations[header_text]
56         if header_text in blocks:
57             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
58             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
59                 blocks[header_text].append(
60                     {
61                         "domain": line.find("span").text,
62                         "hash": line.find("span")["title"][9:],
63                         "reason": line.find_all("td")[1].text.strip(),
64                     }
65                 )
66     return {
67         "reject": blocks["Suspended servers"],
68         "media_removal": blocks["Filtered media"],
69         "followers_only": blocks["Limited servers"]
70         + blocks["Silenced servers"],
71     }
72
73 def get_friendica_blocks(domain: str) -> dict:
74     blocks = []
75
76     try:
77         doc = BeautifulSoup(
78             get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
79             "html.parser",
80         )
81     except:
82         return {}
83
84     blocklist = doc.find(id="about_blocklist")
85     for line in blocklist.find("table").find_all("tr")[1:]:
86             blocks.append(
87                 {
88                     "domain": line.find_all("td")[0].text.strip(),
89                     "reason": line.find_all("td")[1].text.strip()
90                 }
91             )
92
93     return {
94         "reject": blocks
95     }
96
97 def get_pisskey_blocks(domain: str) -> dict:
98     blocks = {
99         "suspended": [],
100         "blocked": []
101     }
102
103     try:
104         counter = 0
105         step = 99
106         while True:
107             # iterating through all "suspended" (follow-only in its terminology) instances page-by-page, since that troonware doesn't support sending them all at once
108             try:
109                 if counter == 0:
110                     doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step}), headers=headers, timeout=5).json()
111                     if doc == []: raise
112                 else:
113                     doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step,"offset":counter-1}), headers=headers, timeout=5).json()
114                     if doc == []: raise
115                 for instance in doc:
116                     # just in case
117                     if instance["isSuspended"]:
118                         blocks["suspended"].append(
119                             {
120                                 "domain": instance["host"],
121                                 # no reason field, nothing
122                                 "reason": ""
123                             }
124                         )
125                 counter = counter + step
126             except:
127                 counter = 0
128                 break
129
130         while True:
131             # same shit, different asshole ("blocked" aka full suspend)
132             try:
133                 if counter == 0:
134                     doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step}), headers=headers, timeout=5).json()
135                     if doc == []: raise
136                 else:
137                     doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step,"offset":counter-1}), headers=headers, timeout=5).json()
138                     if doc == []: raise
139                 for instance in doc:
140                     if instance["isBlocked"]:
141                         blocks["blocked"].append(
142                             {
143                                 "domain": instance["host"],
144                                 "reason": ""
145                             }
146                         )
147                 counter = counter + step
148             except:
149                 counter = 0
150                 break
151
152         return {
153             "reject": blocks["blocked"],
154             "followers_only": blocks["suspended"]
155         }
156
157     except:
158         return {}
159
160 def get_hash(domain: str) -> str:
161     return sha256(domain.encode("utf-8")).hexdigest()
162
163
164 def get_type(domain: str) -> str:
165     try:
166         res = get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5)
167         if res.status_code == 404:
168             res = get(f"https://{domain}/nodeinfo/2.0", headers=headers, timeout=5)
169         if res.status_code == 404:
170             res = get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5)
171         if res.ok and "text/html" in res.headers["content-type"]:
172             res = get(f"https://{domain}/nodeinfo/2.1", headers=headers, timeout=5)
173         if res.ok:
174             if res.json()["software"]["name"] in ["akkoma", "rebased"]:
175                 return "pleroma"
176             elif res.json()["software"]["name"] in ["hometown", "ecko"]:
177                 return "mastodon"
178             elif res.json()["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
179                 return "misskey"
180             else:
181                 return res.json()["software"]["name"]
182         elif res.status_code == 404:
183             res = get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5)
184         if res.ok:
185             return "mastodon"
186     except:
187         return None
188
189 def tidyup(domain: str) -> str:
190     # some retards put their blocks in variable case
191     domain = domain.lower()
192     # other retards put the port
193     domain = re.sub("\:\d+$", "", domain)
194     # bigger retards put the schema in their blocklist, sometimes even without slashes
195     domain = re.sub("^https?\:(\/*)", "", domain)
196     # and trailing slash
197     domain = re.sub("\/$", "", domain)
198     # and the @
199     domain = re.sub("^\@", "", domain)
200     # the biggest retards of them all try to block individual users
201     domain = re.sub("(.+)\@", "", domain)
202     return domain
203
204 conn = sqlite3.connect("blocks.db")
205 c = conn.cursor()
206
207 c.execute(
208     "select domain, software from instances where software in ('pleroma', 'mastodon', 'friendica', 'misskey', 'gotosocial')"
209 )
210
211 for blocker, software in c.fetchall():
212     blocker = tidyup(blocker)
213     if software == "pleroma":
214         print(blocker)
215         try:
216             # Blocks
217             federation = get(
218                 f"https://{blocker}/nodeinfo/2.1.json", headers=headers, timeout=5
219             ).json()["metadata"]["federation"]
220             if "mrf_simple" in federation:
221                 for block_level, blocks in (
222                     {**federation["mrf_simple"],
223                     **{"quarantined_instances": federation["quarantined_instances"]}}
224                 ).items():
225                     for blocked in blocks:
226                         blocked = tidyup(blocked)
227                         if blocked == "":
228                             continue
229                         if blocked.count("*") > 1:
230                             # -ACK!-oma also started obscuring domains without hash
231                             c.execute(
232                                 "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
233                             )
234                             searchres = c.fetchone()
235                             if searchres != None:
236                                 blocked = searchres[0]
237
238                         c.execute(
239                             "select domain from instances where domain = ?", (blocked,)
240                         )
241                         if c.fetchone() == None:
242                             c.execute(
243                                 "insert into instances select ?, ?, ?",
244                                 (blocked, get_hash(blocked), get_type(blocked)),
245                             )
246                         timestamp = int(time())
247                         c.execute(
248                             "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
249                             (blocker, blocked, block_level),
250                         )
251                         if c.fetchone() == None:
252                             c.execute(
253                                 "insert into blocks select ?, ?, '', ?, ?, ?",
254                                 (blocker, blocked, block_level, timestamp, timestamp),
255                             )
256                         else:
257                             c.execute(
258                                 "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
259                                 (timestamp, blocker, blocked, block_level)
260                             )
261             conn.commit()
262             # Reasons
263             if "mrf_simple_info" in federation:
264                 for block_level, info in (
265                     {**federation["mrf_simple_info"],
266                     **(federation["quarantined_instances_info"]
267                     if "quarantined_instances_info" in federation
268                     else {})}
269                 ).items():
270                     for blocked, reason in info.items():
271                         blocked = tidyup(blocked)
272                         if blocked == "":
273                             continue
274                         if blocked.count("*") > 1:
275                             # same domain guess as above, but for reasons field
276                             c.execute(
277                                 "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
278                             )
279                             searchres = c.fetchone()
280                             if searchres != None:
281                                 blocked = searchres[0]
282                         c.execute(
283                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
284                             (reason["reason"], blocker, blocked, block_level),
285                         )
286             conn.commit()
287         except Exception as e:
288             print("error:", e, blocker)
289     elif software == "mastodon":
290         print(blocker)
291         try:
292             # json endpoint for newer mastodongs
293             try:
294                 json = {
295                     "reject": [],
296                     "media_removal": [],
297                     "followers_only": [],
298                     "report_removal": []
299                 }
300                 blocks = get(
301                     f"https://{blocker}/api/v1/instance/domain_blocks", headers=headers, timeout=5
302                 ).json()
303                 for block in blocks:
304                     entry = {'domain': block['domain'], 'hash': block['digest'], 'reason': block['comment']}
305                     if block['severity'] == 'suspend':
306                         json['reject'].append(entry)
307                     elif block['severity'] == 'silence':
308                         json['followers_only'].append(entry)
309                     elif block['severity'] == 'reject_media':
310                         json['media_removal'].append(entry)
311                     elif block['severity'] == 'reject_reports':
312                         json['report_removal'].append(entry)
313             except:
314                 json = get_mastodon_blocks(blocker)
315
316             for block_level, blocks in json.items():
317                 for instance in blocks:
318                     blocked, blocked_hash, reason = instance.values()
319                     blocked = tidyup(blocked)
320                     if blocked.count("*") <= 1:
321                         c.execute(
322                             "select hash from instances where hash = ?", (blocked_hash,)
323                         )
324                         if c.fetchone() == None:
325                             c.execute(
326                                 "insert into instances select ?, ?, ?",
327                                 (blocked, get_hash(blocked), get_type(blocked)),
328                             )
329                     else:
330                         # Doing the hash search for instance names as well to tidy up DB
331                         c.execute(
332                             "select domain from instances where hash = ?", (blocked_hash,)
333                         )
334                         searchres = c.fetchone()
335                         if searchres != None:
336                             blocked = searchres[0]
337
338                     timestamp = int(time())
339                     c.execute(
340                         "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
341                         (blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
342                     )
343                     if c.fetchone() == None:
344                         c.execute(
345                             "insert into blocks select ?, ?, ?, ?, ?, ?",
346                             (
347                                 blocker,
348                                 blocked if blocked.count("*") <= 1 else blocked_hash,
349                                 reason,
350                                 block_level,
351                                 timestamp,
352                                 timestamp,
353                             ),
354                         )
355                     else:
356                         c.execute(
357                             "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
358                             (timestamp, blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
359                         )
360                     if reason != '':
361                         c.execute(
362                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
363                             (reason, blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
364                         )
365             conn.commit()
366         except Exception as e:
367             print("error:", e, blocker)
368     elif software == "friendica" or software == "misskey":
369         print(blocker)
370         try:
371             if software == "friendica":
372                 json = get_friendica_blocks(blocker)
373             elif software == "misskey":
374                 json = get_pisskey_blocks(blocker)
375             for block_level, blocks in json.items():
376                 for instance in blocks:
377                     blocked, reason = instance.values()
378                     blocked = tidyup(blocked)
379
380                     if blocked.count("*") > 0:
381                         # Some friendica servers also obscure domains without hash
382                         c.execute(
383                             "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
384                         )
385                         searchres = c.fetchone()
386                         if searchres != None:
387                             blocked = searchres[0]
388
389                     if blocked.count("?") > 0:
390                         # Some obscure them with question marks, not sure if that's dependent on version or not
391                         c.execute(
392                             "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("?", "_"),)
393                         )
394                         searchres = c.fetchone()
395                         if searchres != None:
396                             blocked = searchres[0]
397
398                     c.execute(
399                         "select domain from instances where domain = ?", (blocked,)
400                     )
401                     if c.fetchone() == None:
402                         c.execute(
403                             "insert into instances select ?, ?, ?",
404                             (blocked, get_hash(blocked), get_type(blocked)),
405                         )
406
407                     timestamp = int(time())
408                     c.execute(
409                         "select * from blocks where blocker = ? and blocked = ? and reason = ?",
410                         (blocker, blocked, reason),
411                     )
412                     if c.fetchone() == None:
413                         c.execute(
414                             "insert into blocks select ?, ?, ?, ?, ?, ?",
415                             (
416                                 blocker,
417                                 blocked,
418                                 reason,
419                                 block_level,
420                                 timestamp,
421                                 timestamp
422                             ),
423                         )
424                     else:
425                         c.execute(
426                             "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
427                             (timestamp, blocker, blocked, block_level),
428                         )
429                     if reason != '':
430                         c.execute(
431                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
432                             (reason, blocker, blocked, block_level),
433                         )
434             conn.commit()
435         except Exception as e:
436             print("error:", e, blocker)
437     elif software == "gotosocial":
438         print(blocker)
439         try:
440             # Blocks
441             federation = get(
442                 f"https://{blocker}/api/v1/instance/peers?filter=suspended", headers=headers, timeout=5
443             ).json()
444             for peer in federation:
445                 blocked = peer["domain"].lower()
446
447                 if blocked.count("*") > 0:
448                     # GTS does not have hashes for obscured domains, so we have to guess it
449                     c.execute(
450                         "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
451                     )
452                     searchres = c.fetchone()
453                     if searchres != None:
454                         blocked = searchres[0]
455
456                 c.execute(
457                     "select domain from instances where domain = ?", (blocked,)
458                 )
459                 if c.fetchone() == None:
460                     c.execute(
461                         "insert into instances select ?, ?, ?",
462                         (blocked, get_hash(blocked), get_type(blocked)),
463                     )
464                 c.execute(
465                     "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
466                     (blocker, blocked, "reject"),
467                 )
468                 timestamp = int(time())
469                 if c.fetchone() == None:
470                     c.execute(
471                         "insert into blocks select ?, ?, ?, ?, ?, ?",
472                            (blocker, blocked, "", "reject", timestamp, timestamp),
473                     )
474                 else:
475                     c.execute(
476                         "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
477                         (timestamp, blocker, blocked, "reject"),
478                     )
479                 if "public_comment" in peer:
480                     reason = peer["public_comment"]
481                     c.execute(
482                         "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
483                         (reason, blocker, blocked, "reject"),
484                     )
485             conn.commit()
486         except Exception as e:
487             print("error:", e, blocker)
488 conn.close()