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