]> git.mxchange.org Git - fba.git/blob - fetch_blocks.py
Domain unshielding for Friendica
[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     # the biggest retards of them all try to block individual users
189     domain = re.sub("(.+)\@", "", domain)
190     return domain
191
192 conn = sqlite3.connect("blocks.db")
193 c = conn.cursor()
194
195 c.execute(
196     "select domain, software from instances where software in ('pleroma', 'mastodon', 'friendica', 'misskey', 'gotosocial')"
197 )
198
199 for blocker, software in c.fetchall():
200     blocker = tidyup(blocker)
201     if software == "pleroma":
202         print(blocker)
203         try:
204             # Blocks
205             federation = get(
206                 f"https://{blocker}/nodeinfo/2.1.json", headers=headers, timeout=5
207             ).json()["metadata"]["federation"]
208             if "mrf_simple" in federation:
209                 for block_level, blocks in (
210                     {**federation["mrf_simple"],
211                     **{"quarantined_instances": federation["quarantined_instances"]}}
212                 ).items():
213                     for blocked in blocks:
214                         blocked = tidyup(blocked)
215                         if blocked == "":
216                             continue
217                         if blocked.count("*") > 1:
218                             # -ACK!-oma also started obscuring domains without hash
219                             c.execute(
220                                 "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
221                             )
222                             searchres = c.fetchone()
223                             if searchres != None:
224                                 blocked = searchres[0]
225
226                         c.execute(
227                             "select domain from instances where domain = ?", (blocked,)
228                         )
229                         if c.fetchone() == None:
230                             c.execute(
231                                 "insert into instances select ?, ?, ?",
232                                 (blocked, get_hash(blocked), get_type(blocked)),
233                             )
234                         c.execute(
235                             "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
236                             (blocker, blocked, block_level),
237                         )
238                         if c.fetchone() == None:
239                             c.execute(
240                                 "insert into blocks select ?, ?, '', ?",
241                                 (blocker, blocked, block_level),
242                             )
243             conn.commit()
244             # Reasons
245             if "mrf_simple_info" in federation:
246                 for block_level, info in (
247                     {**federation["mrf_simple_info"],
248                     **(federation["quarantined_instances_info"]
249                     if "quarantined_instances_info" in federation
250                     else {})}
251                 ).items():
252                     for blocked, reason in info.items():
253                         blocked = tidyup(blocked)
254                         c.execute(
255                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ?",
256                             (reason["reason"], blocker, blocked, block_level),
257                         )
258             conn.commit()
259         except Exception as e:
260             print("error:", e, blocker)
261     elif software == "mastodon":
262         print(blocker)
263         try:
264             json = get_mastodon_blocks(blocker)
265             for block_level, blocks in json.items():
266                 for instance in blocks:
267                     blocked, blocked_hash, reason = instance.values()
268                     blocked = tidyup(blocked)
269                     if blocked.count("*") <= 1:
270                         c.execute(
271                             "select hash from instances where hash = ?", (blocked_hash,)
272                         )
273                         if c.fetchone() == None:
274                             c.execute(
275                                 "insert into instances select ?, ?, ?",
276                                 (blocked, get_hash(blocked), get_type(blocked)),
277                             )
278                     else:
279                         # Doing the hash search for instance names as well to tidy up DB
280                         c.execute(
281                             "select domain from instances where hash = ?", (blocked_hash,)
282                         )
283                         searchres = c.fetchone()
284                         if searchres != None:
285                             blocked = searchres[0]
286
287                     c.execute(
288                         "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
289                         (blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
290                     )
291                     if c.fetchone() == None:
292                         c.execute(
293                             "insert into blocks select ?, ?, ?, ?",
294                             (
295                                 blocker,
296                                 blocked if blocked.count("*") <= 1 else blocked_hash,
297                                 reason,
298                                 block_level,
299                             ),
300                         )
301             conn.commit()
302         except Exception as e:
303             print("error:", e, blocker)
304     elif software == "friendica" or software == "misskey":
305         print(blocker)
306         try:
307             if software == "friendica":
308                 json = get_friendica_blocks(blocker)
309             elif software == "misskey":
310                 json = get_pisskey_blocks(blocker)
311             for block_level, blocks in json.items():
312                 for instance in blocks:
313                     blocked, reason = instance.values()
314                     blocked = tidyup(blocked)
315
316                     if blocked.count("*") > 0:
317                         # Some friendica servers also obscure domains without hash
318                         c.execute(
319                             "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
320                         )
321                         searchres = c.fetchone()
322                         if searchres != None:
323                             blocked = searchres[0]
324
325                     c.execute(
326                         "select domain from instances where domain = ?", (blocked,)
327                     )
328                     if c.fetchone() == None:
329                         c.execute(
330                             "insert into instances select ?, ?, ?",
331                             (blocked, get_hash(blocked), get_type(blocked)),
332                         )
333                     c.execute(
334                         "select * from blocks where blocker = ? and blocked = ?",
335                         (blocker, blocked),
336                     )
337                     if c.fetchone() == None:
338                         c.execute(
339                             "insert into blocks select ?, ?, ?, ?",
340                             (
341                                 blocker,
342                                 blocked,
343                                 reason,
344                                 block_level,
345                             ),
346                         )
347             conn.commit()
348         except Exception as e:
349             print("error:", e, blocker)
350     elif software == "gotosocial":
351         print(blocker)
352         try:
353             # Blocks
354             federation = get(
355                 f"https://{blocker}/api/v1/instance/peers?filter=suspended", headers=headers, timeout=5
356             ).json()
357             for peer in federation:
358                 blocked = peer["domain"].lower()
359
360                 if blocked.count("*") > 0:
361                     # GTS does not have hashes for obscured domains, so we have to guess it
362                     c.execute(
363                         "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
364                     )
365                     searchres = c.fetchone()
366                     if searchres != None:
367                         blocked = searchres[0]
368
369                 c.execute(
370                     "select domain from instances where domain = ?", (blocked,)
371                 )
372                 if c.fetchone() == None:
373                     c.execute(
374                         "insert into instances select ?, ?, ?",
375                         (blocked, get_hash(blocked), get_type(blocked)),
376                     )
377                 c.execute(
378                     "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
379                     (blocker, blocked, "reject"),
380                 )
381                 if c.fetchone() == None:
382                     c.execute(
383                         "insert into blocks select ?, ?, ?, ?",
384                            (blocker, blocked, "", "reject"),
385                     )
386
387                 if "public_comment" in peer:
388                     reason = peer["public_comment"]
389                     c.execute(
390                         "select * from blocks where blocker = ? and blocked = ? and reason != ? and block_level = ?",
391                         (blocker, blocked, "", "reject"),
392                     )
393                     if c.fetchone() == None:
394                         c.execute(
395                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ?",
396                             (reason, blocker, blocked, "reject"),
397                         )
398             conn.commit()
399         except Exception as e:
400             print("error:", e, blocker)
401 conn.close()