]> git.mxchange.org Git - fba.git/blob - fba/networks/peertube.py
Continued:
[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 from fba import config
18 from fba import csrf
19 from fba import network
20
21 from fba.models import instances
22
23 def fetch_peers(domain: str) -> list:
24     # DEBUG: print(f"DEBUG: domain({len(domain)})={domain},software='peertube' - CALLED!")
25     if not isinstance(domain, str):
26         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
27     elif domain == "":
28         raise ValueError("Parameter 'domain' is empty")
29
30     # DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
31     peers   = list()
32     start   = 0
33
34     # No CSRF by default, you don't have to add network.api_headers by yourself here
35     headers = tuple()
36
37     try:
38         # DEBUG: print(f"DEBUG: Checking CSRF for domain='{domain}'")
39         headers = csrf.determine(domain, dict())
40     except network.exceptions as exception:
41         print(f"WARNING: Exception '{type(exception)}' during checking CSRF (fetch_peers,{__name__}) - EXIT!")
42         instances.set_last_error(domain, exception)
43         return peers
44
45     for mode in ["followers", "following"]:
46         # DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
47         while True:
48             data = network.get_json_api(
49                 domain,
50                 f"/api/v1/server/{mode}?start={start}&count=100",
51                 headers,
52                 (config.get("connection_timeout"), config.get("read_timeout"))
53             )
54
55             # DEBUG: print(f"DEBUG: data[]='{type(data)}'")
56             if "error_message" not in data:
57                 # DEBUG: print(f"DEBUG: Success, data[json]()={len(data['json'])}")
58                 if "data" in data["json"]:
59                     rows = data["json"]["data"]
60
61                     # DEBUG: print(f"DEBUG: Found {len(rows)} record(s).")
62                     for record in rows:
63                         # DEBUG: print(f"DEBUG: record()={len(record)}")
64                         for mode2 in ["follower", "following" ]:
65                             # DEBUG: print(f"DEBUG: mode2='{mode2}'")
66                             if mode2 in record and "host" in record[mode2]:
67                                 # DEBUG: print(f"DEBUG: Found host='{record[mode2]['host']}', adding ...")
68                                 peers.append(record[mode2]["host"])
69                             else:
70                                 print(f"WARNING: record from '{domain}' has no '{mode2}' or 'host' record: {record}")
71
72                     if len(rows) < 100:
73                         # DEBUG: print(f"DEBUG: Reached end of JSON response, domain='{domain}'")
74                         break
75
76                 # Continue with next row
77                 start = start + 100
78             else:
79                 print(f"WARNING: domain='{domain}' causes error during API query: '{data['error_message']}' - SKIPPED!")
80                 break
81
82     # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
83     instances.set_total_peers(domain, peers)
84
85     # DEBUG: print(f"DEBUG: Returning peers[]='{type(peers)}'")
86     return peers