]> git.mxchange.org Git - fba.git/blob - fetch_blocks.py
reformatted
[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": "fedi-block-api (https://gitlab.com/EnjuAihara/fedi-block-api)"
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     try:
20         doc = BeautifulSoup(
21             get(f"https://{domain}/about/more", headers=headers, timeout=5).text,
22             "html.parser",
23         )
24     except:
25         return {}
26
27     for header in doc.find_all("h3"):
28         for line in header.find_next_siblings("table")[0].find_all("tr")[1:]:
29             if header.text in blocks:
30                 blocks[header.text].append(
31                     {
32                         "domain": line.find("span").text,
33                         "hash": line.find("span")["title"][9:],
34                         "reason": line.find_all("td")[1].text.strip(),
35                     }
36                 )
37     return {
38         "reject": blocks["Suspended servers"],
39         "media_removal": blocks["Filtered media"],
40         "federated_timeline_removal": blocks["Limited servers"]
41         + blocks["Silenced servers"],
42     }
43
44
45 def get_hash(domain: str) -> str:
46     return sha256(domain.encode("utf-8")).hexdigest()
47
48
49 def get_type(domain: str) -> str:
50     try:
51         res = get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5)
52         if res.status_code == 404:
53             res = get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5)
54         if res.ok:
55             return res.json()["software"]["name"]
56         elif res.status_code == 404:
57             res = get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5)
58         if res.ok:
59             return "mastodon"
60     except:
61         return None
62
63
64 conn = sqlite3.connect("blocks.db")
65 c = conn.cursor()
66
67 c.execute(
68     "select domain, software from instances where software in ('pleroma', 'mastodon')"
69 )
70
71 for blocker, software in c.fetchall():
72     if software == "pleroma":
73         print(blocker)
74         try:
75             # Blocks
76             c.execute("delete from blocks where blocker = ?", (blocker,))
77             federation = get(
78                 f"https://{blocker}/nodeinfo/2.1.json", headers=headers, timeout=5
79             ).json()["metadata"]["federation"]
80             if "mrf_simple" in federation:
81                 for block_level, blocks in (
82                     federation["mrf_simple"]
83                     | {"quarantined_instances": federation["quarantined_instances"]}
84                 ).items():
85                     for blocked in blocks:
86                         if blocked == "":
87                             continue
88                         c.execute(
89                             "select domain from instances where domain = ?", (blocked,)
90                         )
91                         if c.fetchone() == None:
92                             c.execute(
93                                 "insert into instances select ?, ?, ?",
94                                 (blocked, get_hash(blocked), get_type(blocked)),
95                             )
96                         c.execute(
97                             "insert into blocks select ?, ?, '', ?",
98                             (blocker, blocked, block_level),
99                         )
100             conn.commit()
101             # Reasons
102             if "mrf_simple_info" in federation:
103                 for block_level, info in (
104                     federation["mrf_simple_info"]
105                     | federation["quarantined_instances_info"]
106                     if "quarantined_instances_info" in federation
107                     else {}
108                 ).items():
109                     for blocked, reason in info.items():
110                         c.execute(
111                             "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ?",
112                             (reason["reason"], blocker, blocked, block_level),
113                         )
114             conn.commit()
115         except Exception as e:
116             print("error:", e, blocker)
117     elif software == "mastodon":
118         print(blocker)
119         try:
120             c.execute("delete from blocks where blocker = ?", (blocker,))
121             json = get_mastodon_blocks(blocker)
122             for block_level, blocks in json.items():
123                 for instance in blocks:
124                     blocked, blocked_hash, reason = instance.values()
125                     if blocked.count("*") <= 1:
126                         c.execute(
127                             "select hash from instances where hash = ?", (blocked_hash,)
128                         )
129                         if c.fetchone() == None:
130                             c.execute(
131                                 "insert into instances select ?, ?, ?",
132                                 (blocked, get_hash(blocked), get_type(blocked)),
133                             )
134                     c.execute(
135                         "insert into blocks select ?, ?, ?, ?",
136                         (
137                             blocker,
138                             blocked if blocked.count("*") <= 1 else blocked_hash,
139                             reason,
140                             block_level,
141                         ),
142                     )
143             conn.commit()
144         except Exception as e:
145             print("error:", e, blocker)
146 conn.close()