]> 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 blocks
24 from fba import config
25 from fba import fba
26 from fba import instances
27 from fba import network
28 from fba.helpers import tidyup
29
30 language_mapping = {
31     # English -> English
32     "Silenced instances"            : "Silenced servers",
33     "Suspended instances"           : "Suspended servers",
34     "Limited instances"             : "Limited servers",
35     "Filtered media"                : "Filtered media",
36     # Mappuing German -> English
37     "Gesperrte Server"              : "Suspended servers",
38     "Gefilterte Medien"             : "Filtered media",
39     "Stummgeschaltete Server"       : "Silenced servers",
40     # Japanese -> English
41     "停止済みのサーバー"            : "Suspended servers",
42     "制限中のサーバー"              : "Limited servers",
43     "メディアを拒否しているサーバー": "Filtered media",
44     "サイレンス済みのサーバー"      : "Silenced servers",
45     # ??? -> English
46     "שרתים מושעים"                  : "Suspended servers",
47     "מדיה מסוננת"                   : "Filtered media",
48     "שרתים מוגבלים"                 : "Silenced servers",
49     # French -> English
50     "Serveurs suspendus"            : "Suspended servers",
51     "Médias filtrés"                : "Filtered media",
52     "Serveurs limités"              : "Limited servers",
53     "Serveurs modérés"              : "Limited servers",
54 }
55
56 def fetch_blocks_from_about(domain: str) -> dict:
57     # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
58     if not isinstance(domain, str):
59         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
60     elif domain == "":
61         raise ValueError("Parameter 'domain' is empty")
62
63     # DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
64     blocklist = {
65         "Suspended servers": [],
66         "Filtered media"   : [],
67         "Limited servers"  : [],
68         "Silenced servers" : [],
69     }
70
71     try:
72         doc = bs4.BeautifulSoup(
73             network.fetch_response(
74                 domain,
75                 "/about/more",
76                 network.web_headers,
77                 (config.get("connection_timeout"), config.get("read_timeout"))
78             ).text,
79             "html.parser",
80         )
81     except BaseException as exception:
82         print("ERROR: Cannot fetch from domain:", domain, exception)
83         instances.update_last_error(domain, exception)
84         return {}
85
86     for header in doc.find_all("h3"):
87         header_text = tidyup.reason(header.text)
88
89         # DEBUG: print(f"DEBUG: header_text='{header_text}'")
90         if header_text in language_mapping:
91             # DEBUG: print(f"DEBUG: header_text='{header_text}'")
92             header_text = language_mapping[header_text]
93         else:
94             print(f"WARNING: header_text='{header_text}' not found in language mapping table")
95
96         if header_text in blocklist or header_text.lower() in blocklist:
97             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
98             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
99                 blocklist[header_text].append(
100                     {
101                         "domain": tidyup.domain(line.find("span").text),
102                         "hash"  : tidyup.domain(line.find("span")["title"][9:]),
103                         "reason": tidyup.reason(line.find_all("td")[1].text),
104                     }
105                 )
106         else:
107             print(f"WARNING: header_text='{header_text}' not found in blocklist()={len(blocklist)}")
108
109     # DEBUG: print("DEBUG: Returning blocklist for domain:", domain)
110     return {
111         "reject"        : blocklist["Suspended servers"],
112         "media_removal" : blocklist["Filtered media"],
113         "followers_only": blocklist["Limited servers"] + blocklist["Silenced servers"],
114     }
115
116 def fetch_blocks(domain: str, origin: str, nodeinfo_url: str):
117     # DEBUG: print(f"DEBUG: domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}' - CALLED!")
118     if not isinstance(domain, str):
119         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
120     elif domain == "":
121         raise ValueError("Parameter 'domain' is empty")
122     elif not isinstance(origin, str) and origin is not None:
123         raise ValueError(f"Parameter origin[]={type(origin)} is not 'str'")
124     elif origin == "":
125         raise ValueError("Parameter 'origin' is empty")
126     elif not isinstance(nodeinfo_url, str):
127         raise ValueError(f"Parameter nodeinfo_url[]={type(nodeinfo_url)} is not 'str'")
128     elif nodeinfo_url == "":
129         raise ValueError("Parameter 'nodeinfo_url' is empty")
130
131     try:
132         # json endpoint for newer mastodongs
133         blockdict = list()
134         try:
135             rows = {
136                 "reject"        : [],
137                 "media_removal" : [],
138                 "followers_only": [],
139                 "report_removal": [],
140             }
141
142             # DEBUG: print("DEBUG: Querying API domain_blocks:", domain)
143             response = network.fetch_response(
144                 domain,
145                 "/api/v1/instance/domain_blocks",
146                 network.api_headers,
147                 (config.get("connection_timeout"), config.get("read_timeout"))
148             )
149
150             # DEBUG: print(f"DEBUG: response[]='{type(response)}'")
151             blocklist = network.json_from_response(response)
152
153             print(f"INFO: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon' ...")
154             for block in blocklist:
155                 entry = {
156                     'domain': block['domain'],
157                     'hash'  : block['digest'],
158                     'reason': block['comment']
159                 }
160
161                 # DEBUG: print("DEBUG: severity,domain,hash,comment:", block['severity'], block['domain'], block['digest'], block['comment'])
162                 if block['severity'] == 'suspend':
163                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
164                     rows['reject'].append(entry)
165                 elif block['severity'] == 'silence':
166                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
167                     rows['followers_only'].append(entry)
168                 elif block['severity'] == 'reject_media':
169                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
170                     rows['media_removal'].append(entry)
171                 elif block['severity'] == 'reject_reports':
172                     # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
173                     rows['report_removal'].append(entry)
174                 else:
175                     print("WARNING: Unknown severity:", block['severity'], block['domain'])
176
177         except BaseException as exception:
178             # DEBUG: print(f"DEBUG: Failed, trying mastodon-specific fetches: domain='{domain}',exception[{type(exception)}]={str(exception)}")
179             rows = fetch_blocks_from_about(domain)
180
181         print(f"INFO: Checking {len(rows.items())} entries from domain='{domain}',software='mastodon' ...")
182         for block_level, blocklist in rows.items():
183             # DEBUG: print("DEBUG: domain,block_level,blocklist():", domain, block_level, len(blocklist))
184             block_level = tidyup.domain(block_level)
185
186             # DEBUG: print("DEBUG: AFTER-block_level:", block_level)
187             if block_level == "":
188                 print("WARNING: block_level is empty, domain:", domain)
189                 continue
190
191             # DEBUG: print(f"DEBUG: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon',block_level='{block_level}' ...")
192             for block in blocklist:
193                 # DEBUG: print(f"DEBUG: block[]='{type(block)}'")
194                 blocked, blocked_hash, reason = block.values()
195                 # DEBUG: print(f"DEBUG: blocked='{blocked}',blocked_hash='{blocked_hash}',reason='{reason}':")
196                 blocked = tidyup.domain(blocked)
197                 reason  = tidyup.reason(reason) if reason is not None and reason != "" else None
198                 # DEBUG: print(f"DEBUG: blocked='{blocked}',reason='{reason}' - AFTER!")
199
200                 if blocked == "":
201                     print("WARNING: blocked is empty:", domain)
202                     continue
203                 elif blacklist.is_blacklisted(blocked):
204                     # DEBUG: print(f"DEBUG: blocked='{blocked}' is blacklisted - skipping!")
205                     continue
206                 elif blocked.count("*") > 0:
207                     # Doing the hash search for instance names as well to tidy up DB
208                     fba.cursor.execute(
209                         "SELECT domain, origin, nodeinfo_url FROM instances WHERE hash = ? LIMIT 1", [blocked_hash]
210                     )
211                     searchres = fba.cursor.fetchone()
212
213                     if searchres is None:
214                         print(f"WARNING: Cannot deobsfucate blocked='{blocked}',blocked_hash='{blocked_hash}' - SKIPPED!")
215                         continue
216
217                     # DEBUG: print("DEBUG: Updating domain: ", searchres[0])
218                     blocked = searchres[0]
219                     origin = searchres[1]
220                     nodeinfo_url = searchres[2]
221
222                     # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
223                     if not validators.domain(blocked):
224                         print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
225                         continue
226                     elif not instances.is_registered(blocked):
227                         # DEBUG: print(f"DEBUG: Domain blocked='{blocked}' wasn't found, adding ..., domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}'")
228                         instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
229                 elif not validators.domain(blocked):
230                     print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
231                     continue
232
233                 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
234                 if not validators.domain(blocked):
235                     print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
236                     continue
237                 elif not instances.is_registered(blocked):
238                     # DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, domain)
239                     instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
240
241                 blocking = blocked if blocked.count("*") <= 1 else blocked_hash
242                 # DEBUG: print(f"DEBUG: blocking='{blocking}',blocked='{blocked}',blocked_hash='{blocked_hash}'")
243
244                 if not blocks.is_instance_blocked(domain, blocked, block_level):
245                     # DEBUG: print("DEBUG: Blocking:", domain, blocked, block_level)
246                     blocks.add_instance(domain, blocking, reason, block_level)
247
248                     if block_level == "reject":
249                         blockdict.append({
250                             "blocked": blocked,
251                             "reason" : reason
252                         })
253                 else:
254                     # DEBUG: print(f"DEBUG: Updating block last seen and reason for domain='{domain}',blocking='{blocking}' ...")
255                     blocks.update_last_seen(domain, blocking, block_level)
256                     blocks.update_reason(reason, domain, blocking, block_level)
257
258         # DEBUG: print("DEBUG: Committing changes ...")
259         fba.connection.commit()
260     except BaseException as exception:
261         print(f"ERROR: domain='{domain}',software='mastodon',exception[{type(exception)}]:'{str(exception)}'")
262
263     # DEBUG: print("DEBUG: EXIT!")