]> git.mxchange.org Git - fba.git/blob - fba/networks/friendica.py
Continued:
[fba.git] / fba / networks / friendica.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
19 import bs4
20 import validators
21
22 from fba.helpers import blacklist
23 from fba.helpers import config
24 from fba.helpers import tidyup
25
26 from fba.http import network
27
28 from fba.models import instances
29
30 logging.basicConfig(level=logging.INFO)
31 logger = logging.getLogger(__name__)
32
33 def fetch_blocks(domain: str) -> dict:
34     logger.debug(f"domain='{domain}' - CALLED!")
35     if not isinstance(domain, str):
36         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
37     elif domain == "":
38         raise ValueError("Parameter 'domain' is empty")
39     elif domain.lower() != domain:
40         raise ValueError(f"Parameter domain='{domain}' must be all lower-case")
41     elif not validators.domain(domain.split("/")[0]):
42         raise ValueError(f"domain='{domain}' is not a valid domain")
43     elif domain.endswith(".arpa"):
44         raise ValueError(f"domain='{domain}' is a domain for reversed IP addresses, please don't crawl them!")
45     elif domain.endswith(".tld"):
46         raise ValueError(f"domain='{domain}' is a fake domain, please don't crawl them!")
47
48     blocklist = list()
49     block_tag = None
50
51     try:
52         logger.debug("Fetching friendica blocks from domain:", domain)
53         doc = bs4.BeautifulSoup(
54             network.fetch_response(
55                 domain,
56                 "/friendica",
57                 network.web_headers,
58                 (config.get("connection_timeout"), config.get("read_timeout"))
59             ).text,
60             "html.parser",
61         )
62         logger.debug(f"doc[]='{type(doc)}'")
63
64         block_tag = doc.find(id="about_blocklist")
65     except network.exceptions as exception:
66         logger.warning(f"Exception '{type(exception)}' during fetching instances (friendica) from domain='{domain}'")
67         instances.set_last_error(domain, exception)
68         return dict()
69
70     # Prevents exceptions:
71     if block_tag is None:
72         logger.debug("Instance has no block list:", domain)
73         return dict()
74
75     table = block_tag.find("table")
76
77     logger.debug(f"table[]='{type(table)}'")
78     if table.find("tbody"):
79         rows = table.find("tbody").find_all("tr")
80     else:
81         rows = table.find_all("tr")
82
83     logger.debug(f"Found rows()={len(rows)}")
84     for line in rows:
85         logger.debug(f"line='{line}'")
86         blocked = tidyup.domain(line.find_all("td")[0].text)
87         reason  = tidyup.reason(line.find_all("td")[1].text)
88         logger.debug(f"blocked='{blocked}',reason='{reason}'")
89
90         if not validators.domain(blocked):
91             logger.warning(f"blocked='{blocked}' is not a valid domain - SKIPPED!")
92             continue
93         elif blocked.endswith(".arpa"):
94             logger.warning(f"blocked='{blocked}' is a reversed .arpa domain and should not be used generally.")
95             continue
96         elif blocked.endswith(".tld"):
97             logger.warning(f"blocked='{blocked}' is a fake domain, please don't crawl them!")
98             continue
99         elif blacklist.is_blacklisted(blocked):
100             logger.debug(f"blocked='{blocked}' is blacklisted - SKIPPED!")
101             continue
102
103         logger.debug(f"Appending blocked='{blocked}',reason='{reason}'")
104         blocklist.append({
105             "domain": tidyup.domain(blocked),
106             "reason": tidyup.reason(reason)
107         })
108         logger.debug("Next!")
109
110     logger.debug("Returning blocklist() for domain:", domain, len(blocklist))
111     return {
112         "reject": blocklist
113     }