]> 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 logging
18 import validators
19
20 import bs4
21
22 from fba.helpers import blacklist
23 from fba.helpers import config
24 from fba.helpers import domain as domain_helper
25 from fba.helpers import tidyup
26
27 from fba.http import network
28
29 from fba.models import blocks
30 from fba.models import instances
31
32 logging.basicConfig(level=logging.INFO)
33 logger = logging.getLogger(__name__)
34
35 # Language mapping X -> English
36 language_mapping = {
37     # English -> English
38     "Silenced instances"            : "Silenced servers",
39     "Suspended instances"           : "Suspended servers",
40     "Suspended servers"             : "Suspended servers",
41     "Limited instances"             : "Limited servers",
42     "Filtered media"                : "Filtered media",
43     # Mappuing German -> English
44     "Gesperrte Server"              : "Suspended servers",
45     "Gefilterte Medien"             : "Filtered media",
46     "Stummgeschaltete Server"       : "Silenced servers",
47     # Japanese -> English
48     "停止済みのサーバー"            : "Suspended servers",
49     "制限中のサーバー"              : "Limited servers",
50     "メディアを拒否しているサーバー": "Filtered media",
51     "サイレンス済みのサーバー"      : "Silenced servers",
52     # ??? -> English
53     "שרתים מושעים"                  : "Suspended servers",
54     "מדיה מסוננת"                   : "Filtered media",
55     "שרתים מוגבלים"                 : "Silenced servers",
56     # French -> English
57     "Serveurs suspendus"            : "Suspended servers",
58     "Médias filtrés"                : "Filtered media",
59     "Serveurs limités"              : "Limited servers",
60     "Serveurs modérés"              : "Limited servers",
61 }
62
63 def fetch_blocks_from_about(domain: str) -> dict:
64     logger.debug("domain='%s' - CALLED!", domain)
65     domain_helper.raise_on(domain)
66
67     if blacklist.is_blacklisted(domain):
68         raise Exception(f"domain='{domain}' is blacklisted but function is invoked.")
69     elif not instances.is_registered(domain):
70         raise Exception(f"domain='{domain}' is not registered but function is invoked.")
71
72     logger.info("Fetching mastodon blocks from domain='%s'", domain)
73     doc = None
74     for path in ["/about/more", "/about"]:
75         try:
76             logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
77             doc = bs4.BeautifulSoup(
78                 network.fetch_response(
79                     domain,
80                     path,
81                     network.web_headers,
82                     (config.get("connection_timeout"), config.get("read_timeout"))
83                 ).text,
84                 "html.parser",
85             )
86
87             if len(doc.find_all("h3")) > 0:
88                 logger.debug("path='%s' had some headlines - BREAK!", path)
89                 break
90
91         except network.exceptions as exception:
92             logger.warning("Cannot fetch from domain='%s',exception='%s'", domain, type(exception))
93             instances.set_last_error(domain, exception)
94             break
95
96     blocklist = {
97         "Suspended servers": [],
98         "Filtered media"   : [],
99         "Limited servers"  : [],
100         "Silenced servers" : [],
101     }
102
103     logger.debug("doc[]='%s'", type(doc))
104     if doc is None:
105         logger.warning("Cannot fetch any /about pages for domain='%s' - EXIT!", domain)
106         return list()
107
108     for header in doc.find_all("h3"):
109         header_text = tidyup.reason(header.text)
110
111         logger.debug("header_text='%s'", header_text)
112         if header_text in language_mapping:
113             logger.debug("Translating header_text='%s' ...", header_text)
114             header_text = language_mapping[header_text]
115         else:
116             logger.warning("header_text='%s' not found in language mapping table", header_text)
117
118         if header_text in blocklist or header_text.lower() in blocklist:
119             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
120             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
121                 domain = line.find("span").text
122                 digest = line.find("span")["title"][9:]
123                 reason = line.find_all("td")[1].text
124
125                 logger.debug("domain='%s',reason='%s' - BEFORE!", domain, reason)
126                 domain = tidyup.domain(domain) if domain != "" else None
127                 reason = tidyup.reason(reason) if reason != "" else None
128
129                 logger.debug("domain='%s',reason='%s' - AFTER!", domain, reason)
130                 if domain in [None, ""]:
131                     logger.warning("domain='%s' is empty,line='%s' - SKIPPED!", domain, line)
132                     continue
133
134                 logger.debug("Appending domain='%s',digest='%s',reason='%s' to blocklist header_text='%s' ...", domain, digest, reason, blocklist)
135                 blocklist[header_text].append({
136                     "domain": domain,
137                     "digest": digest,
138                     "reason": reason,
139                 })
140         else:
141             logger.warning("header_text='%s' not found in blocklist()=%d", header_text, len(blocklist))
142
143     logger.debug("Returning blocklist for domain='%s' - EXIT!", domain)
144     return {
145         "reject"        : blocklist["Suspended servers"],
146         "media_removal" : blocklist["Filtered media"],
147         "followers_only": blocklist["Limited servers"] + blocklist["Silenced servers"],
148     }
149
150 def fetch_blocks(domain: str) -> list:
151     logger.debug("domain='%s' - CALLED!", domain)
152     domain_helper.raise_on(domain)
153
154     if blacklist.is_blacklisted(domain):
155         raise Exception(f"domain='{domain}' is blacklisted but function is invoked.")
156     elif not instances.is_registered(domain):
157         raise Exception(f"domain='{domain}' is not registered but function is invoked.")
158
159     blocklist = list()
160
161     logger.debug("Invoking fetch_blocks_from_about(%s) ...", domain)
162     rows = fetch_blocks_from_about(domain)
163
164     logger.debug("rows[%s]()=%d", type(rows), len(rows))
165     if len(rows) > 0:
166         logger.debug("Checking %d entries from domain='%s' ...", len(rows), domain)
167         for block in rows:
168             # Check type
169             logger.debug("block[]='%s'", type(block))
170             if not isinstance(block, dict):
171                 logger.debug("block[]='%s' is of type 'dict' - SKIPPED!", type(block))
172                 continue
173             elif "domain" not in block:
174                 logger.debug("block='%s'", block)
175                 logger.warning("block()=%d does not contain element 'domain' - SKIPPED!", len(block))
176                 continue
177             elif not domain_helper.is_wanted(block["domain"]):
178                 logger.debug("block[domain]='%s' is not wanted - SKIPPED!", block["domain"])
179                 continue
180             elif "severity" not in block:
181                 logger.warning("block()=%d does not contain element 'severity' - SKIPPED!", len(block))
182                 continue
183             elif block["severity"] in ["accept", "accepted"]:
184                 logger.debug("block[domain]='%s' has unwanted severity level '%s' - SKIPPED!", block["domain"], block["severity"])
185                 continue
186             elif "digest" in block and not validators.hashes.sha256(block["digest"]):
187                 logger.warning("block[domain]='%s' has invalid block[digest]='%s' - SKIPPED!", block["domain"], block["digest"])
188                 continue
189
190             reason = tidyup.reason(block["comment"]) if "comment" in block and block["comment"] is not None and block["comment"] != "" else None
191
192             logger.debug("Appending blocker='%s',blocked='%s',reason='%s',block_level='%s'", domain, block["domain"], reason, block["severity"])
193             blocklist.append({
194                 "blocker"    : domain,
195                 "blocked"    : block["domain"],
196                 "digest"     : block["digest"] if "digest" in block else None,
197                 "reason"     : reason,
198                 "block_level": blocks.alias_block_level(block["severity"]),
199             })
200     else:
201         logger.debug("domain='%s' has no block list", domain)
202
203     logger.debug("blocklist()=%d - EXIT!", len(blocklist))
204     return blocklist