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