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