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/>.
21 from fba import config
23 from fba import instances
25 # HTTP headers for non-API requests
27 "User-Agent": config.get("useragent"),
30 # HTTP headers for API requests
32 "User-Agent" : config.get("useragent"),
33 "Content-Type": "application/json",
36 # Exceptions to always catch
38 requests.exceptions.ConnectionError,
39 requests.exceptions.Timeout,
40 requests.exceptions.TooManyRedirects,
44 def post_json_api(domain: str, path: str, data: str, headers: dict = {}) -> dict:
45 # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',data='{data}',headers()={len(headers)} - CALLED!")
46 if not isinstance(domain, str):
47 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
49 raise ValueError("Parameter 'domain' is empty")
50 elif not isinstance(path, str):
51 raise ValueError(f"path[]={type(path)} is not 'str'")
53 raise ValueError("Parameter 'path' cannot be empty")
54 elif not isinstance(data, str):
55 raise ValueError(f"data[]={type(data)} is not 'str'")
56 elif not isinstance(headers, dict):
57 raise ValueError(f"headers[]={type(headers)} is not 'list'")
64 # DEBUG: print(f"DEBUG: Sending POST to domain='{domain}',path='{path}',data='{data}',headers({len(headers)})={headers}")
65 response = reqto.post(
66 f"https://{domain}{path}",
68 headers={**api_headers, **headers},
69 timeout=(config.get("connection_timeout"), config.get("read_timeout"))
72 json_reply["json"] = json_from_response(response)
74 # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},json_reply[]='{type(json_reply)}'")
75 if not response.ok or response.status_code >= 400:
76 print(f"WARNING: Cannot query JSON API: domain='{domain}',path='{path}',data()={len(data)},response.status_code='{response.status_code}',json_reply[]='{type(json_reply)}'")
77 json_reply["status_code"] = response.status_code
78 json_reply["error_message"] = response.reason
79 instances.update_last_error(domain, response)
81 except requests.exceptions.ConnectionError as exception:
82 # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
83 json_reply["status_code"] = 999
84 json_reply["error_message"] = f"exception['{type(exception)}']='{str(exception)}'"
85 instances.update_last_error(domain, exception)
88 # DEBUG: print(f"DEBUG: Returning json_reply({len(json_reply)})=[]:{type(json_reply)}")
91 def fetch_api_url(url: str, timeout: tuple) -> dict:
92 # DEBUG: print(f"DEBUG: url='{url}',timeout()={len(timeout)} - CALLED!")
93 if not isinstance(url, str):
94 raise ValueError(f"Parameter url[]='{type(url)}' is not 'str'")
95 elif not isinstance(timeout, tuple):
96 raise ValueError(f"timeout[]={type(timeout)} is not 'tuple'")
103 # DEBUG: print(f"DEBUG: Fetching url='{url}' ...")
104 response = fba.fetch_url(url, api_headers, timeout)
106 json_reply["json"] = json_from_response(response)
108 # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},json_reply[]='{type(json_reply)}'")
109 if not response.ok or response.status_code >= 400:
110 print(f"WARNING: Cannot query JSON API: url='{url}',response.status_code='{response.status_code}',json_reply[]='{type(json_reply)}'")
111 json_reply["status_code"] = response.status_code
112 json_reply["error_message"] = response.reason
114 except requests.exceptions.ConnectionError as exception:
115 # DEBUG: print(f"DEBUG: Fetching '{url}' failed. exception[{type(exception)}]='{str(exception)}'")
116 json_reply["status_code"] = 999
117 json_reply["error_message"] = f"exception['{type(exception)}']='{str(exception)}'"
120 # DEBUG: print(f"DEBUG: Returning json_reply({len(json_reply)})=[]:{type(json_reply)}")
123 def get_json_api(domain: str, path: str, headers: dict, timeout: tuple) -> dict:
124 # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',timeout()={len(timeout)} - CALLED!")
125 if not isinstance(domain, str):
126 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
128 raise ValueError("Parameter 'domain' is empty")
129 elif not isinstance(path, str):
130 raise ValueError(f"path[]={type(path)} is not 'str'")
132 raise ValueError("Parameter 'path' cannot be empty")
133 elif not isinstance(headers, dict):
134 raise ValueError(f"headers[]={type(headers)} is not 'list'")
135 elif not isinstance(timeout, tuple):
136 raise ValueError(f"timeout[]={type(timeout)} is not 'tuple'")
143 # DEBUG: print(f"DEBUG: Sending GET to domain='{domain}',path='{path}',timeout({len(timeout)})={timeout}")
144 response = reqto.get(
145 f"https://{domain}{path}",
146 headers={**api_headers, **headers},
150 except requests.exceptions.ConnectionError as exception:
151 # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
152 json_reply["status_code"] = 999
153 json_reply["error_message"] = f"exception['{type(exception)}']='{str(exception)}'"
154 instances.update_last_error(domain, exception)
157 json_reply["json"] = json_from_response(response)
159 # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},json_reply[]='{type(json_reply)}'")
160 if not response.ok or response.status_code >= 400:
161 print(f"WARNING: Cannot query JSON API: domain='{domain}',path='{path}',response.status_code='{response.status_code}',json_reply[]='{type(json_reply)}'")
162 json_reply["status_code"] = response.status_code
163 json_reply["error_message"] = response.reason
164 instances.update_last_error(domain, response)
166 # DEBUG: print(f"DEBUG: Returning json_reply({len(json_reply)})=[]:{type(json_reply)}")
169 def send_bot_post(domain: str, blocklist: dict):
170 # DEBUG: print(f"DEBUG: domain={domain},blocklist()={len(blocklist)} - CALLED!")
171 if not isinstance(domain, str):
172 raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
174 raise ValueError("Parameter 'domain' is empty")
175 elif not isinstance(blocklist, dict):
176 raise ValueError(f"Parameter blocklist[]='{type(blocklist)}' is not 'dict'")
178 message = f"{domain} has blocked the following instances:\n\n"
181 if len(blocklist) > 20:
183 blocklist = blocklist[0 : 19]
185 # DEBUG: print(f"DEBUG: blocklist()={len(blocklist)}")
186 for block in blocklist:
187 # DEBUG: print(f"DEBUG: block['{type(block)}']={block}")
188 if block["reason"] is None or block["reason"] == '':
189 message = message + block["blocked"] + " with unspecified reason\n"
191 if len(block["reason"]) > 420:
192 block["reason"] = block["reason"][0:419] + "[…]"
194 message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
197 message = message + "(the list has been truncated to the first 20 entries)"
199 botheaders = {**api_headers, **{"Authorization": "Bearer " + config.get("bot_token")}}
202 f"{config.get('bot_instance')}/api/v1/statuses",
205 "visibility" : config.get('bot_visibility'),
206 "content_type": "text/plain"
214 def fetch_response(domain: str, path: str, headers: dict, timeout: tuple) -> requests.models.Response:
215 # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',headers()={len(headers)},timeout={timeout} - CALLED!")
216 if not isinstance(domain, str):
217 raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
219 raise ValueError("Parameter 'domain' is empty")
220 elif not isinstance(path, str):
221 raise ValueError(f"Parameter path[]='{type(path)}' is not 'str'")
223 raise ValueError("Parameter 'path' is empty")
224 elif not isinstance(headers, dict):
225 raise ValueError(f"headers[]={type(headers)} is not 'dict'")
226 elif not isinstance(timeout, tuple):
227 raise ValueError(f"timeout[]={type(timeout)} is not 'tuple'")
230 # DEBUG: print(f"DEBUG: Sending GET request to '{domain}{path}' ...")
231 response = reqto.get(
232 f"https://{domain}{path}",
237 except requests.exceptions.ConnectionError as exception:
238 # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
239 instances.update_last_error(domain, exception)
242 # DEBUG: print(f"DEBUG: response[]='{type(response)}' - EXXIT!")
245 def json_from_response(response: requests.models.Response) -> list:
246 # DEBUG: print(f"DEBUG: response[]={type(response)} - CALLED!")
247 if not isinstance(response, requests.models.Response):
248 raise ValueError(f"Parameter response[]='{type(response)}' is not type of 'Response'")
251 if response.text.strip() != "":
252 # DEBUG: print(f"DEBUG: response.text()={len(response.text)} is not empty, invoking response.json() ...")
254 data = response.json()
255 except json.decoder.JSONDecodeError:
258 # DEBUG: print(f"DEBUG: data[]={type(data)} - EXIT!")