]> 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 csrf
18 from fba import network
19
20 from fba.helpers import config
21
22 from fba.models import instances
23
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'")
28     elif domain == "":
29         raise ValueError("Parameter 'domain' is empty")
30
31     # DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
32     peers   = list()
33     start   = 0
34
35     # No CSRF by default, you don't have to add network.api_headers by yourself here
36     headers = tuple()
37
38     try:
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)
44         return peers
45
46     for mode in ["followers", "following"]:
47         # DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
48         while True:
49             data = network.get_json_api(
50                 domain,
51                 f"/api/v1/server/{mode}?start={start}&count=100",
52                 headers,
53                 (config.get("connection_timeout"), config.get("read_timeout"))
54             )
55
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"]
61
62                     # DEBUG: print(f"DEBUG: Found {len(rows)} record(s).")
63                     for record in rows:
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"])
70                             else:
71                                 print(f"WARNING: record from '{domain}' has no '{mode2}' or 'host' record: {record}")
72
73                     if len(rows) < 100:
74                         # DEBUG: print(f"DEBUG: Reached end of JSON response, domain='{domain}'")
75                         break
76
77                 # Continue with next row
78                 start = start + 100
79             else:
80                 print(f"WARNING: domain='{domain}' causes error during API query: '{data['error_message']}' - SKIPPED!")
81                 break
82
83     # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
84     instances.set_total_peers(domain, peers)
85
86     # DEBUG: print(f"DEBUG: Returning peers[]='{type(peers)}'")
87     return peers