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