]> git.mxchange.org Git - fba.git/blob - fba/network.py
WIP:
[fba.git] / fba / network.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 import json
18 import reqto
19 import requests
20
21 from fba import config
22 from fba import csrf
23 from fba import instances
24
25 # HTTP headers for non-API requests
26 web_headers = {
27     "User-Agent": config.get("useragent"),
28 }
29
30 # HTTP headers for API requests
31 api_headers = {
32     "User-Agent"  : config.get("useragent"),
33     "Content-Type": "application/json",
34 }
35
36 def post_json_api(domain: str, path: str, data: str, headers: dict = {}) -> dict:
37     # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',data='{data}',headers()={len(headers)} - CALLED!")
38     if not isinstance(domain, str):
39         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
40     elif domain == "":
41         raise ValueError("Parameter 'domain' is empty")
42     elif not isinstance(path, str):
43         raise ValueError(f"path[]={type(path)} is not 'str'")
44     elif path == "":
45         raise ValueError("Parameter 'path' cannot be empty")
46     elif not isinstance(data, str):
47         raise ValueError(f"data[]={type(data)} is not 'str'")
48     elif not isinstance(headers, dict):
49         raise ValueError(f"headers[]={type(headers)} is not 'list'")
50
51     # DEBUG: print(f"DEBUG: Determining if CSRF header needs to be sent for domain='{domain}' ...")
52     headers = csrf.determine(domain, {**api_headers, **headers})
53
54     json_reply = {
55         "status_code": 200,
56     }
57
58     try:
59         # DEBUG: print(f"DEBUG: Sending POST to domain='{domain}',path='{path}',data='{data}',headers({len(headers)})={headers}")
60         response = reqto.post(
61             f"https://{domain}{path}",
62             data=data,
63             headers=headers,
64             timeout=(config.get("connection_timeout"), config.get("read_timeout"))
65         )
66
67         json_reply["json"] = json_from_response(response)
68
69         # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},json_reply[]='{type(json_reply)}'")
70         if not response.ok or response.status_code >= 400:
71             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)}'")
72             json_reply["status_code"]   = response.status_code
73             json_reply["error_message"] = response.text
74             instances.update_last_error(domain, response)
75
76     except requests.exceptions.ConnectionError as exception:
77         # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
78         json_reply["status_code"]   = 999
79         json_reply["error_message"] = f"exception['{type(exception)}']='{str(exception)}'"
80         instances.update_last_error(domain, exception)
81         raise exception
82
83     # DEBUG: print(f"DEBUG: Returning json_reply({len(json_reply)})=[]:{type(json_reply)}")
84     return json_reply
85
86 def get_json_api(domain: str, path: str, timeout: tuple) -> dict:
87     # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',data='{data}',timeout()={len(timeout)} - CALLED!")
88     if not isinstance(domain, str):
89         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
90     elif domain == "":
91         raise ValueError("Parameter 'domain' is empty")
92     elif not isinstance(path, str):
93         raise ValueError(f"path[]={type(path)} is not 'str'")
94     elif path == "":
95         raise ValueError("Parameter 'path' cannot be empty")
96     elif not isinstance(timeout, tuple):
97         raise ValueError(f"timeout[]={type(timeout)} is not 'tuple'")
98
99     # DEBUG: print(f"DEBUG: Determining if CSRF header needs to be sent for domain='{domain}' ...")
100     headers = csrf.determine(domain, api_headers)
101
102     json_reply = {
103         "status_code": 200,
104     }
105
106     try:
107         # DEBUG: print(f"DEBUG: Sending GET to domain='{domain}',path='{path}',timeout({len(timeout)})={timeout}")
108         response = reqto.get(
109             f"https://{domain}{path}",
110             headers=headers,
111             timeout=timeout
112         )
113
114     except requests.exceptions.ConnectionError as exception:
115         # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
116         json_reply["status_code"]   = 999
117         json_reply["error_message"] = f"exception['{type(exception)}']='{str(exception)}'"
118         instances.update_last_error(domain, exception)
119         raise exception
120
121     json_reply["json"] = json_from_response(response)
122
123     # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},json_reply[]='{type(json_reply)}'")
124     if not response.ok or response.status_code >= 400:
125         print(f"WARNING: Cannot query JSON API: domain='{domain}',path='{path}',response.status_code='{response.status_code}',json_reply[]='{type(json_reply)}'")
126         json_reply["status_code"]   = response.status_code
127         json_reply["error_message"] = response.text
128         instances.update_last_error(domain, response)
129
130     # DEBUG: print(f"DEBUG: Returning json_reply({len(json_reply)})=[]:{type(json_reply)}")
131     return json_reply
132
133 def send_bot_post(domain: str, blocklist: dict):
134     # DEBUG: print(f"DEBUG: domain={domain},blocklist()={len(blocklist)} - CALLED!")
135     if not isinstance(domain, str):
136         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
137     elif domain == "":
138         raise ValueError("Parameter 'domain' is empty")
139     elif not isinstance(blocklist, dict):
140         raise ValueError(f"Parameter blocklist[]='{type(blocklist)}' is not 'dict'")
141
142     message = f"{domain} has blocked the following instances:\n\n"
143     truncated = False
144
145     if len(blocklist) > 20:
146         truncated = True
147         blocklist = blocklist[0 : 19]
148
149     # DEBUG: print(f"DEBUG: blocklist()={len(blocklist)}")
150     for block in blocklist:
151         # DEBUG: print(f"DEBUG: block['{type(block)}']={block}")
152         if block["reason"] is None or block["reason"] == '':
153             message = message + block["blocked"] + " with unspecified reason\n"
154         else:
155             if len(block["reason"]) > 420:
156                 block["reason"] = block["reason"][0:419] + "[…]"
157
158             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
159
160     if truncated:
161         message = message + "(the list has been truncated to the first 20 entries)"
162
163     botheaders = {**api_headers, **{"Authorization": "Bearer " + config.get("bot_token")}}
164
165     req = reqto.post(
166         f"{config.get('bot_instance')}/api/v1/statuses",
167         data={
168             "status"      : message,
169             "visibility"  : config.get('bot_visibility'),
170             "content_type": "text/plain"
171         },
172         headers=botheaders,
173         timeout=10
174     ).json()
175
176     return True
177
178 def fetch_response(domain: str, path: str, headers: dict, timeout: tuple) -> requests.models.Response:
179     # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}',headers()={len(headers)},timeout={timeout} - CALLED!")
180     if not isinstance(domain, str):
181         raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
182     elif domain == "":
183         raise ValueError("Parameter 'domain' is empty")
184     elif not isinstance(path, str):
185         raise ValueError(f"Parameter path[]='{type(path)}' is not 'str'")
186     elif path == "":
187         raise ValueError("Parameter 'path' is empty")
188     elif not isinstance(headers, dict):
189         raise ValueError(f"headers[]={type(headers)} is not 'dict'")
190     elif not isinstance(timeout, tuple):
191         raise ValueError(f"timeout[]={type(timeout)} is not 'tuple'")
192
193     try:
194         # DEBUG: print(f"DEBUG: Sending GET request to '{domain}{path}' ...")
195         response = reqto.get(
196             f"https://{domain}{path}",
197             headers=headers,
198             timeout=timeout
199         )
200
201     except requests.exceptions.ConnectionError as exception:
202         # DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' failed. exception[{type(exception)}]='{str(exception)}'")
203         instances.update_last_error(domain, exception)
204         raise exception
205
206     # DEBUG: print(f"DEBUG: response[]='{type(response)}' - EXXIT!")
207     return response
208
209 def json_from_response(response: requests.models.Response) -> list:
210     # DEBUG: print(f"DEBUG: response[]={type(response)} - CALLED!")
211     if not isinstance(response, requests.models.Response):
212         raise ValueError(f"Parameter response[]='{type(response)}' is not type of 'Response'")
213
214     data = dict()
215     if response.text.strip() != "":
216         # DEBUG: print(f"DEBUG: response.text()={len(response.text)} is not empty, invoking response.json() ...")
217         try:
218             data = response.json()
219         except json.decoder.JSONDecodeError:
220             pass
221
222     # DEBUG: print(f"DEBUG: data[]={type(data)} - EXIT!")
223     return data