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