1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
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.
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.
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/>.
17 from fba import config
19 from fba import network
21 from fba.models import instances
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'")
28 raise ValueError("Parameter 'domain' is empty")
30 # DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
34 # No CSRF by default, you don't have to add network.api_headers by yourself here
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)
45 for mode in ["followers", "following"]:
46 # DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
48 data = network.get_json_api(
50 f"/api/v1/server/{mode}?start={start}&count=100",
52 (config.get("connection_timeout"), config.get("read_timeout"))
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"]
61 # DEBUG: print(f"DEBUG: Found {len(rows)} record(s).")
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"])
70 print(f"WARNING: record from '{domain}' has no '{mode2}' or 'host' record: {record}")
73 # DEBUG: print(f"DEBUG: Reached end of JSON response, domain='{domain}'")
76 # Continue with next row
79 print(f"WARNING: domain='{domain}' causes error during API query: '{data['error_message']}' - SKIPPED!")
82 # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
83 instances.set_total_peers(domain, peers)
85 # DEBUG: print(f"DEBUG: Returning peers[]='{type(peers)}'")