]> git.mxchange.org Git - fba.git/blob - fba/networks/peertube.py
caf38653dc61e2edb4b0f20f0ff2705861086ac7
[fba.git] / fba / networks / peertube.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 from fba.helpers import blacklist
20 from fba.helpers import config
21 from fba.helpers import domain as domain_helper
22
23 from fba.http import csrf
24 from fba.http import network
25
26 from fba.models import instances
27
28 logging.basicConfig(level=logging.INFO)
29 logger = logging.getLogger(__name__)
30
31 def fetch_peers(domain: str) -> list:
32     logger.debug("domain='%s' - CALLED!", domain)
33     domain_helper.raise_on(domain)
34
35     if blacklist.is_blacklisted(domain):
36         raise Exception(f"domain='{domain}' is blacklisted but function is invoked.")
37     elif not instances.is_registered(domain):
38         raise Exception(f"domain='{domain}' is not registered but function is invoked.")
39
40     # Init variables
41     peers   = list()
42     headers = tuple()
43     start   = 0
44
45     try:
46         logger.debug("Checking CSRF for domain='%s'", domain)
47         headers = csrf.determine(domain, dict())
48     except network.exceptions as exception:
49         logger.warning("Exception '%s' during checking CSRF (fetch_peers,%s)", type(exception), __name__)
50         instances.set_last_error(domain, exception)
51
52         logger.debug("Returning empty list ... - EXIT!")
53         return list()
54
55     for mode in ["followers", "following"]:
56         logger.debug("domain='%s',mode='%s'", domain, mode)
57         while True:
58             data = network.get_json_api(
59                 domain,
60                 f"/api/v1/server/{mode}?start={start}&count=100",
61                 headers,
62                 (config.get("connection_timeout"), config.get("read_timeout"))
63             )
64
65             logger.debug("data[]='%s'", type(data))
66             if "error_message" in data:
67                 logger.warning("domain='%s' causes error during API query: '%s' - SKIPPED!", domain, data["error_message"])
68                 break
69             elif "data" not in data["json"]:
70                 logger.warning("domain='%s' has no 'data' element returned - SKIPPED!", domain)
71                 break
72             else:
73                 logger.debug("Success, data[json]()=%d", len(data["json"]))
74                 instances.set_success(domain)
75
76                 rows  = data["json"]["data"]
77
78                 logger.debug("Found %d record(s).", len(rows))
79                 for record in rows:
80                     logger.debug("record()=%d", len(record))
81                     for mode2 in ["follower", "following"]:
82                         logger.debug("mode=%s,mode2='%s'", mode, mode2)
83                         if mode2 not in record:
84                             logger.debug("Array record does not contain element mode2='%s' - SKIPPED", mode2)
85                             continue
86                         elif "host" not in record[mode2]:
87                             logger.debug("record[%s] does not contain element 'host' - SKIPPED", mode2)
88                             continue
89                         elif record[mode2]["host"] == domain:
90                             logger.debug("record[%s]='%s' matches domain='%s' - SKIPPED!", mode2, record[mode2]["host"], domain)
91                             continue
92                         elif not domain_helper.is_wanted(record[mode2]["host"]):
93                             logger.debug("record[%s][host]='%s' is not wanted - SKIPPED!", mode2, record[mode2]["host"])
94                             continue
95
96                         logger.debug("Appending mode2='%s',host='%s' ...", mode2, record[mode2]["host"])
97                         peers.append(record[mode2]["host"])
98
99                 if len(rows) < 100:
100                     logger.debug("Reached end of JSON response, domain='%s'", domain)
101                     break
102
103                 # Continue with next row
104                 start = start + 100
105
106     logger.debug("peers[%s]()=%d - EXIT!", type(peers), len(peers))
107     return peers