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/>.
18 from fba import network
20 from fba.helpers import config
22 from fba.models import instances
24 def fetch_peers(domain: str) -> list:
25 # DEBUG: print(f"DEBUG: domain({len(domain)})='{domain}',software='peertube' - CALLED!")
26 if not isinstance(domain, str):
27 raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
29 raise ValueError("Parameter 'domain' is empty")
31 # DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
35 # No CSRF by default, you don't have to add network.api_headers by yourself here
39 # DEBUG: print(f"DEBUG: Checking CSRF for domain='{domain}'")
40 headers = csrf.determine(domain, dict())
41 except network.exceptions as exception:
42 print(f"WARNING: Exception '{type(exception)}' during checking CSRF (fetch_peers,{__name__}) - EXIT!")
43 instances.set_last_error(domain, exception)
46 for mode in ["followers", "following"]:
47 # DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
49 data = network.get_json_api(
51 f"/api/v1/server/{mode}?start={start}&count=100",
53 (config.get("connection_timeout"), config.get("read_timeout"))
56 # DEBUG: print(f"DEBUG: data[]='{type(data)}'")
57 if "error_message" not in data:
58 # DEBUG: print(f"DEBUG: Success, data[json]()={len(data['json'])}")
59 if "data" in data["json"]:
60 rows = data["json"]["data"]
62 # DEBUG: print(f"DEBUG: Found {len(rows)} record(s).")
64 # DEBUG: print(f"DEBUG: record()={len(record)}")
65 for mode2 in ["follower", "following" ]:
66 # DEBUG: print(f"DEBUG: mode2='{mode2}'")
67 if mode2 in record and "host" in record[mode2]:
68 # DEBUG: print(f"DEBUG: Found host='{record[mode2]['host']}', adding ...")
69 peers.append(record[mode2]["host"])
71 print(f"WARNING: record from '{domain}' has no '{mode2}' or 'host' record: {record}")
74 # DEBUG: print(f"DEBUG: Reached end of JSON response, domain='{domain}'")
77 # Continue with next row
80 print(f"WARNING: domain='{domain}' causes error during API query: '{data['error_message']}' - SKIPPED!")
83 # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
84 instances.set_total_peers(domain, peers)
86 # DEBUG: print(f"DEBUG: Returning peers[]='{type(peers)}'")