]> git.mxchange.org Git - fba.git/blob - fetch_blocks.py
Friendica support & possible fix for duplicate values when parsing Masto
[fba.git] / fetch_blocks.py
1 from requests import get
2 from hashlib import sha256
3 import sqlite3
4 from bs4 import BeautifulSoup
5
6 headers = {
7     "user-agent": "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0"
8 }
9
10
11 def get_mastodon_blocks(domain: str) -> dict:
12     blocks = {
13         "Suspended servers": [],
14         "Filtered media": [],
15         "Limited servers": [],
16         "Silenced servers": [],
17     }
18
19     translations = {
20         "Gesperrte Server": "Suspended servers",
21         "Gefilterte Medien": "Filtered media",
22         "Stummgeschaltete Server": "Silenced servers",
23         "停止済みのサーバー": "Suspended servers",
24         "メディアを拒否しているサーバー": "Filtered media",
25         "サイレンス済みのサーバー": "Silenced servers",
26         "Serveurs suspendus": "Suspended servers",
27         "Médias filtrés": "Filtered media",
28         "Serveurs limités": "Silenced servers",
29     }
30
31     try:
32         doc = BeautifulSoup(
33             get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
34             "html.parser",
35         )
36     except:
37         return {}
38
39     for header in doc.find_all("h3"):
40         for line in header.find_next_siblings("table")[0].find_all("tr")[1:]:
41             header_text = header.text
42             if header_text in translations:
43                     header_text = translations[header_text]
44             if header_text in blocks:
45                 blocks[header_text].append(
46                     {
47                         "domain": line.find("span").text,
48                         "hash": line.find("span")["title"][9:],
49                         "reason": line.find_all("td")[1].text.strip(),
50                     }
51                 )
52     return {
53         "reject": blocks["Suspended servers"],
54         "media_removal": blocks["Filtered media"],
55         "federated_timeline_removal": blocks["Limited servers"]
56         + blocks["Silenced servers"],
57     }
58
59 def get_friendica_blocks(domain: str) -> dict:
60     blocks = []
61
62     try:
63         doc = BeautifulSoup(
64             get(f"https://{domain}/friendica", headers=headers, timeout=5).text,
65             "html.parser",
66         )
67     except:
68         return {}
69
70     blocklist = doc.find(id="about_blocklist")
71     for line in blocklist.find("table").find_all("tr")[1:]:
72             blocks.append(
73                 {
74                     "domain": line.find_all("td")[0].text.strip(),
75                     "reason": line.find_all("td")[1].text.strip()
76                 }
77             )
78
79     return {
80         "reject": blocks
81     }
82
83 def get_hash(domain: str) -> str:
84     return sha256(domain.encode("utf-8")).hexdigest()
85
86
87 def get_type(domain: str) -> str:
88     try:
89         res = get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5)
90         if res.status_code == 404:
91             res = get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5)
92         if res.ok and "text/html" in res.headers["content-type"]:
93             res = get(f"https://{domain}/nodeinfo/2.1", headers=headers, timeout=5)
94         if res.ok:
95             if res.json()["software"]["name"] == "akkoma":
96                 return "pleroma"
97             elif res.json()["software"]["name"] == "hometown":
98                 return "mastodon"
99             else:
100                 return res.json()["software"]["name"]
101         elif res.status_code == 404:
102             res = get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5)
103         if res.ok:
104             return "mastodon"
105     except:
106         return None
107
108
109 conn = sqlite3.connect("blocks.db")
110 c = conn.cursor()
111
112 c.execute(
113     "select domain, software from instances where software in ('pleroma', 'mastodon')"
114 )
115
116 for blocker, software in c.fetchall():
117     if software == "pleroma":
118         print(blocker)
119         try:
120             # Blocks
121             federation = get(
122                 f"https://{blocker}/nodeinfo/2.1.json", headers=headers, timeout=5
123             ).json()["metadata"]["federation"]
124             if "mrf_simple" in federation:
125                 for block_level, blocks in (
126                     {**federation["mrf_simple"],
127                     **{"quarantined_instances": federation["quarantined_instances"]}}
128                 ).items():
129                     for blocked in blocks:
130                         if blocked == "":
131                             continue
132                         blocked == blocked.lower()
133                         blocker == blocker.lower()
134                         c.execute(
135                             "select domain from instances where domain = ?", (blocked,)
136                         )
137                         if c.fetchone() == None:
138                             c.execute(
139                                 "insert into instances select ?, ?, ?",
140                                 (blocked, get_hash(blocked), get_type(blocked)),
141                             )
142                         c.execute(
143                             "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
144                             (blocker, blocked, block_level),
145                         )
146                         if c.fetchone() == None:
147                             c.execute(
148                                 "insert into blocks select ?, ?, '', ?",
149                                 (blocker, blocked, block_level),
150                             )
151             conn.commit()
152             # Reasons
153             if "mrf_simple_info" in federation:
154                 for block_level, info in (
155                     {**federation["mrf_simple_info"],
156                     **(federation["quarantined_instances_info"]
157                     if "quarantined_instances_info" in federation
158                     else {})}
159                 ).items():
160                     for blocked, reason in info.items():
161                         blocker == blocker.lower()
162                         blocked == blocked.lower()
163                         c.execute(
164                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ?",
165                             (reason["reason"], blocker, blocked, block_level),
166                         )
167             conn.commit()
168         except Exception as e:
169             print("error:", e, blocker)
170     elif software == "mastodon":
171         print(blocker)
172         try:
173             json = get_mastodon_blocks(blocker)
174             for block_level, blocks in json.items():
175                 for instance in blocks:
176                     blocked, blocked_hash, reason = instance.values()
177                     blocked == blocked.lower()
178                     blocker == blocker.lower()
179                     if blocked.count("*") <= 1:
180                         c.execute(
181                             "select hash from instances where hash = ?", (blocked_hash,)
182                         )
183                         if c.fetchone() == None:
184                             c.execute(
185                                 "insert into instances select ?, ?, ?",
186                                 (blocked, get_hash(blocked), get_type(blocked)),
187                             )
188                     c.execute(
189                         "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
190                         (blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
191                     )
192                     if c.fetchone() == None:
193                         c.execute(
194                             "insert into blocks select ?, ?, ?, ?",
195                             (
196                                 blocker,
197                                 blocked if blocked.count("*") <= 1 else blocked_hash,
198                                 reason,
199                                 block_level,
200                             ),
201                         )
202             conn.commit()
203         except Exception as e:
204             print("error:", e, blocker)
205     elif software == "friendica"
206         print(blocker)
207         try:
208             json = get_friendica_blocks(blocker)
209             for blocks in json.items():
210                 for instance in blocks:
211                     blocked, reason = instance.values()
212                     blocked == blocked.lower()
213                     blocker == blocker.lower()
214                     c.execute(
215                         "select domain from instances where domain = ?", (blocked,)
216                     )
217                     if c.fetchone() == None:
218                         c.execute(
219                             "insert into instances select ?, ?, ?",
220                             (blocked, get_hash(blocked), get_type(blocked)),
221                         )
222                     c.execute(
223                         "select * from blocks where blocker = ? and blocked = ?",
224                         (blocker, blocked),
225                     )
226                     if c.fetchone() == None:
227                         c.execute(
228                             "insert into blocks select ?, ?, ?, ?",
229                             (
230                                 blocker,
231                                 blocked,
232                                 reason,
233                                 "reject",
234                             ),
235                         )
236             conn.commit()
237         except Exception as e:
238             print("error:", e, blocker)
239 conn.close()