]> git.mxchange.org Git - fba.git/blob - fba/networks/mastodon.py
Continued:
[fba.git] / fba / networks / mastodon.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 import inspect
18
19 import bs4
20 import validators
21
22 from fba import blacklist
23 from fba import config
24 from fba import csrf
25 from fba import fba
26 from fba import network
27
28 from fba.helpers import tidyup
29
30 from fba.models import blocks
31 from fba.models import instances
32
33 language_mapping = {
34     # English -> English
35     "Silenced instances"            : "Silenced servers",
36     "Suspended instances"           : "Suspended servers",
37     "Limited instances"             : "Limited servers",
38     "Filtered media"                : "Filtered media",
39     # Mappuing German -> English
40     "Gesperrte Server"              : "Suspended servers",
41     "Gefilterte Medien"             : "Filtered media",
42     "Stummgeschaltete Server"       : "Silenced servers",
43     # Japanese -> English
44     "停止済みのサーバー"            : "Suspended servers",
45     "制限中のサーバー"              : "Limited servers",
46     "メディアを拒否しているサーバー": "Filtered media",
47     "サイレンス済みのサーバー"      : "Silenced servers",
48     # ??? -> English
49     "שרתים מושעים"                  : "Suspended servers",
50     "מדיה מסוננת"                   : "Filtered media",
51     "שרתים מוגבלים"                 : "Silenced servers",
52     # French -> English
53     "Serveurs suspendus"            : "Suspended servers",
54     "Médias filtrés"                : "Filtered media",
55     "Serveurs limités"              : "Limited servers",
56     "Serveurs modérés"              : "Limited servers",
57 }
58
59 def fetch_blocks_from_about(domain: str) -> dict:
60     # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
61     if not isinstance(domain, str):
62         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
63     elif domain == "":
64         raise ValueError("Parameter 'domain' is empty")
65
66     # DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
67     doc = None
68     for path in ["/about/more", "/about"]:
69         try:
70             # DEBUG: print(f"DEBUG: Fetching path='{path}' from domain='{domain}' ...")
71             doc = bs4.BeautifulSoup(
72                 network.fetch_response(
73                     domain,
74                     path,
75                     network.web_headers,
76                     (config.get("connection_timeout"), config.get("read_timeout"))
77                 ).text,
78                 "html.parser",
79             )
80
81             if len(doc.find_all("h3")) > 0:
82                 # DEBUG: print(f"DEBUG: path='{path}' had some headlines - BREAK!")
83                 break
84
85         except BaseException as exception:
86             print("ERROR: Cannot fetch from domain:", domain, exception)
87             instances.set_last_error(domain, exception)
88             break
89
90     blocklist = {
91         "Suspended servers": [],
92         "Filtered media"   : [],
93         "Limited servers"  : [],
94         "Silenced servers" : [],
95     }
96
97     # DEBUG: print(f"DEBUG: doc[]='{type(doc)}'")
98     if doc is None:
99         print(f"WARNING: Cannot fetch any /about pages for domain='{domain}' - EXIT!")
100         return blocklist
101
102     for header in doc.find_all("h3"):
103         header_text = tidyup.reason(header.text)
104
105         # DEBUG: print(f"DEBUG: header_text='{header_text}'")
106         if header_text in language_mapping:
107             # DEBUG: print(f"DEBUG: header_text='{header_text}'")
108             header_text = language_mapping[header_text]
109         else:
110             print(f"WARNING: header_text='{header_text}' not found in language mapping table")
111
112         if header_text in blocklist or header_text.lower() in blocklist:
113             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
114             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
115                 blocklist[header_text].append({
116                     "domain": tidyup.domain(line.find("span").text),
117                     "hash"  : tidyup.domain(line.find("span")["title"][9:]),
118                     "reason": tidyup.reason(line.find_all("td")[1].text),
119                 })
120         else:
121             print(f"WARNING: header_text='{header_text}' not found in blocklist()={len(blocklist)}")
122
123     # DEBUG: print("DEBUG: Returning blocklist for domain:", domain)
124     return {
125         "reject"        : blocklist["Suspended servers"],
126         "media_removal" : blocklist["Filtered media"],
127         "followers_only": blocklist["Limited servers"] + blocklist["Silenced servers"],
128     }
129
130 def fetch_blocks(domain: str, origin: str, nodeinfo_url: str):
131     # DEBUG: print(f"DEBUG: domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}' - CALLED!")
132     if not isinstance(domain, str):
133         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
134     elif domain == "":
135         raise ValueError("Parameter 'domain' is empty")
136     elif not isinstance(origin, str) and origin is not None:
137         raise ValueError(f"Parameter origin[]='{type(origin)}' is not 'str'")
138     elif origin == "":
139         raise ValueError("Parameter 'origin' is empty")
140     elif not isinstance(nodeinfo_url, str):
141         raise ValueError(f"Parameter nodeinfo_url[]='{type(nodeinfo_url)}' is not 'str'")
142     elif nodeinfo_url == "":
143         raise ValueError("Parameter 'nodeinfo_url' is empty")
144
145     # No CSRF by default, you don't have to add network.api_headers by yourself here
146     headers = tuple()
147
148     try:
149         # DEBUG: print(f"DEBUG: Checking CSRF for domain='{domain}'")
150         headers = csrf.determine(domain, dict())
151     except network.exceptions as exception:
152         print(f"WARNING: Exception '{type(exception)}' during checking CSRF (fetch_blocks,{__name__}) - EXIT!")
153         return
154
155     try:
156         # json endpoint for newer mastodongs
157         found_blocks = list()
158         blocklist = list()
159
160         rows = {
161             "reject"        : [],
162             "media_removal" : [],
163             "followers_only": [],
164             "report_removal": [],
165         }
166
167         # DEBUG: print("DEBUG: Querying API domain_blocks:", domain)
168         data = network.get_json_api(
169             domain,
170             "/api/v1/instance/domain_blocks",
171             headers,
172             (config.get("connection_timeout"), config.get("read_timeout"))
173         )
174
175         # DEBUG: print(f"DEBUG: data[]='{type(data)}'")
176         if "error_message" in data:
177             # DEBUG: print(f"DEBUG: Was not able to fetch domain_blocks from domain='{domain}': status_code='{data['status_code']}',error_message='{data['error_message']}'")
178             instances.set_last_error(domain, data)
179             return
180         elif "json" in data and "error" in data["json"]:
181             print(f"WARNING: JSON API returned error message: '{data['json']['error']}'")
182             instances.set_last_error(domain, data)
183             return
184         else:
185             # Getting blocklist
186             blocklist = data["json"]
187
188         if len(blocklist) > 0:
189             print(f"INFO: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon' ...")
190             for block in blocklist:
191                 # Check type
192                 # DEBUG: print(f"DEBUG: block[]='{type(block)}'")
193                 if not isinstance(block, dict):
194                     # DEBUG: print(f"DEBUG: block[]='{type(block)}' is of type 'dict' - SKIPPED!")
195                     continue
196
197                 # Map block -> entry
198                 # DEBUG: print(f"DEBUG: block[{type(block)}]='{block}'")
199                 entry = {
200                     "domain": block["domain"],
201                     "hash"  : block["digest"],
202                     "reason": block["comment"] if "comment" in block else None
203                 }
204
205                 # DEBUG: print("DEBUG: severity,domain,hash,comment:", block['severity'], block['domain'], block['digest'], block['comment'])
206                 if block['severity'] == 'suspend':
207                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
208                     rows['reject'].append(entry)
209                 elif block['severity'] == 'silence':
210                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
211                     rows['followers_only'].append(entry)
212                 elif block['severity'] == 'reject_media':
213                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
214                     rows['media_removal'].append(entry)
215                 elif block['severity'] == 'reject_reports':
216                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
217                     rows['report_removal'].append(entry)
218                 else:
219                     print(f"WARNING: Unknown severity='{block['severity']}', domain='{block['domain']}'")
220         else:
221             # DEBUG: print(f"DEBUG: domain='{domain}' has returned zero rows, trying /about/more page ...")
222             rows = fetch_blocks_from_about(domain)
223
224         print(f"INFO: Checking {len(rows.items())} entries from domain='{domain}',software='mastodon' ...")
225         for block_level, blocklist in rows.items():
226             # DEBUG: print("DEBUG: domain,block_level,blocklist():", domain, block_level, len(blocklist))
227             block_level = tidyup.domain(block_level)
228
229             # DEBUG: print("DEBUG: AFTER-block_level:", block_level)
230             if block_level == "":
231                 print("WARNING: block_level is empty, domain:", domain)
232                 continue
233
234             # DEBUG: print(f"DEBUG: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon',block_level='{block_level}' ...")
235             for block in blocklist:
236                 # DEBUG: print(f"DEBUG: block[]='{type(block)}'")
237                 blocked, blocked_hash, reason = block.values()
238                 # DEBUG: print(f"DEBUG: blocked='{blocked}',blocked_hash='{blocked_hash}',reason='{reason}':")
239                 blocked = tidyup.domain(blocked)
240                 reason  = tidyup.reason(reason) if reason is not None and reason != "" else None
241                 # DEBUG: print(f"DEBUG: blocked='{blocked}',reason='{reason}' - AFTER!")
242
243                 if blocked == "":
244                     print("WARNING: blocked is empty:", domain)
245                     continue
246                 elif blacklist.is_blacklisted(blocked):
247                     # DEBUG: print(f"DEBUG: blocked='{blocked}' is blacklisted - skipping!")
248                     continue
249                 elif blocked.count("*") > 0:
250                     # Doing the hash search for instance names as well to tidy up DB
251                     row = instances.deobscure("*", blocked, blocked_hash)
252
253                     # DEBUG: print(f"DEBUG: row[]='{type(row)}'")
254                     if row is None:
255                         print(f"WARNING: Cannot deobsfucate blocked='{blocked}',blocked_hash='{blocked_hash}' - SKIPPED!")
256                         continue
257
258                     # DEBUG: print("DEBUG: Updating domain: ", row[0])
259                     blocked      = row[0]
260                     origin       = row[1]
261                     nodeinfo_url = row[2]
262                 elif blocked.count("?") > 0:
263                     # Doing the hash search for instance names as well to tidy up DB
264                     row = instances.deobscure("?", blocked, blocked_hash)
265
266                     # DEBUG: print(f"DEBUG: row[]='{type(row)}'")
267                     if row is None:
268                         print(f"WARNING: Cannot deobsfucate blocked='{blocked}',blocked_hash='{blocked_hash}' - SKIPPED!")
269                         continue
270
271                     # DEBUG: print("DEBUG: Updating domain: ", row[0])
272                     blocked      = row[0]
273                     origin       = row[1]
274                     nodeinfo_url = row[2]
275
276                 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
277                 if not validators.domain(blocked):
278                     print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - SKIPPED!")
279                     continue
280                 elif blocked.endswith(".arpa"):
281                     print(f"WARNING: blocked='{blocked}' is a reversed .arpa domain and should not be used generally.")
282                     continue
283                 elif not instances.is_registered(blocked):
284                     # DEBUG: print(f"DEBUG: Domain blocked='{blocked}' wasn't found, adding ..., domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}'")
285                     instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
286
287                 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
288                 if not validators.domain(blocked):
289                     print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - SKIPPED!")
290                     continue
291                 elif blocked.endswith(".arpa"):
292                     print(f"WARNING: blocked='{blocked}' is a reversed .arpa domain and should not be used generally.")
293                     continue
294                 elif not instances.is_registered(blocked):
295                     # DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, domain)
296                     instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
297
298                 if not blocks.is_instance_blocked(domain, blocked, block_level):
299                     # DEBUG: print("DEBUG: Blocking:", domain, blocked, block_level)
300                     blocks.add_instance(domain, blocked, reason, block_level)
301
302                     if block_level == "reject":
303                         found_blocks.append({
304                             "blocked": blocked,
305                             "reason" : reason
306                         })
307                 else:
308                     # DEBUG: print(f"DEBUG: Updating block last seen and reason for domain='{domain}',blocked='{blocked}' ...")
309                     blocks.update_last_seen(domain, blocked, block_level)
310                     blocks.update_reason(reason, domain, blocked, block_level)
311
312         # DEBUG: print("DEBUG: Committing changes ...")
313         fba.connection.commit()
314     except network.exceptions as exception:
315         print(f"ERROR: domain='{domain}',software='mastodon',exception[{type(exception)}]:'{str(exception)}'")
316
317     # DEBUG: print("DEBUG: EXIT!")