]> git.mxchange.org Git - fba.git/blob - api.py
94fdc3895368e7a6ad2bf77b97fa4cec9dfa15ca
[fba.git] / api.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 fastapi import Request, HTTPException, Query
18 from fastapi.responses import JSONResponse
19 from fastapi.responses import PlainTextResponse
20 from fastapi.templating import Jinja2Templates
21 from datetime import datetime
22 from email import utils
23
24 import fastapi
25 import uvicorn
26 import requests
27 import re
28 from fba import *
29
30 router = fastapi.FastAPI(docs_url=config.get("base_url") + "/docs", redoc_url=config.get("base_url") + "/redoc")
31 templates = Jinja2Templates(directory="templates")
32
33 @router.get(config.get("base_url") + "/api/info.json", response_class=JSONResponse)
34 def info():
35     fba.cursor.execute("SELECT (SELECT COUNT(domain) FROM instances), (SELECT COUNT(domain) FROM instances WHERE software IN ('pleroma', 'mastodon', 'misskey', 'gotosocial', 'friendica', 'bookwyrm', 'takahe', 'peertube')), (SELECT COUNT(blocker) FROM blocks), (SELECT COUNT(domain) FROM instances WHERE last_status_code IS NOT NULL)")
36     known, indexed, blocks, errorous = fba.cursor.fetchone()
37
38     return {
39         "known_instances"   : known,
40         "indexed_instances" : indexed,
41         "blocks_recorded"   : blocks,
42         "errorous_instances": errorous,
43         "slogan"            : config.get("slogan")
44     }
45
46 @router.get(config.get("base_url") + "/api/top.json", response_class=JSONResponse)
47 def top(blocked: int = None, blockers: int = None, reference: int = None, software: int = None, originator: int = None):
48     if blocked != None:
49         if blocked > 500:
50             raise HTTPException(status_code=400, detail="Too many results")
51         fba.cursor.execute("SELECT blocked, COUNT(blocked) FROM blocks WHERE block_level = 'reject' GROUP BY blocked ORDER BY COUNT(blocked) DESC LIMIT ?", [blocked])
52     elif blockers != None:
53         if blockers > 500:
54             raise HTTPException(status_code=400, detail="Too many results")
55         fba.cursor.execute("SELECT blocker, COUNT(blocker) FROM blocks WHERE block_level = 'reject' GROUP BY blocker ORDER BY COUNT(blocker) DESC LIMIT ?", [blockers])
56     elif reference != None:
57         if reference > 500:
58             raise HTTPException(status_code=400, detail="Too many results")
59         fba.cursor.execute("SELECT origin, COUNT(domain) FROM instances WHERE software IS NOT NULL GROUP BY origin ORDER BY COUNT(domain) DESC LIMIT ?", [reference])
60     elif software != None:
61         if software > 500:
62             raise HTTPException(status_code=400, detail="Too many results")
63         fba.cursor.execute("SELECT software, COUNT(domain) FROM instances WHERE software IS NOT NULL GROUP BY software ORDER BY COUNT(domain) DESC, software ASC LIMIT ?", [software])
64     elif originator != None:
65         if originator > 500:
66             raise HTTPException(status_code=400, detail="Too many results")
67         fba.cursor.execute("SELECT originator, COUNT(domain) FROM instances WHERE originator IS NOT NULL GROUP BY originator ORDER BY COUNT(domain) DESC, originator ASC LIMIT ?", [originator])
68     else:
69         raise HTTPException(status_code=400, detail="No filter specified")
70
71     scores = fba.cursor.fetchall()
72
73     scoreboard = []
74
75     for domain, highscore in scores:
76         scoreboard.append({
77             "domain"   : domain,
78             "highscore": highscore
79         })
80
81     return scoreboard
82
83 @router.get(config.get("base_url") + "/api/index.json", response_class=JSONResponse)
84 def blocked(domain: str = None, reason: str = None, reverse: str = None):
85     if domain == None and reason == None and reverse == None:
86         raise HTTPException(status_code=400, detail="No filter specified")
87
88     if reason != None:
89         reason = re.sub("(%|_)", "", reason)
90         if len(reason) < 3:
91             raise HTTPException(status_code=400, detail="Keyword is shorter than three characters")
92
93     if domain != None:
94         wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
95         punycode = domain.encode('idna').decode('utf-8')
96         fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? ORDER BY first_seen ASC",
97                   (domain, "*." + domain, wildchar, fba.get_hash(domain), punycode, "*." + punycode))
98     elif reverse != None:
99         fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE blocker = ? ORDER BY first_seen ASC", [reverse])
100     else:
101         fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE reason like ? AND reason != '' ORDER BY first_seen ASC", ["%" + reason + "%"])
102
103     blocks = fba.cursor.fetchall()
104
105     result = {}
106     for blocker, blocked, block_level, reason, first_seen, last_seen in blocks:
107         entry = {
108             "blocker"   : blocker,
109             "blocked"   : blocked,
110             "reason"    : reason,
111             "first_seen": first_seen,
112             "last_seen" : last_seen
113         }
114         if block_level in result:
115             result[block_level].append(entry)
116         else:
117             result[block_level] = [entry]
118
119     return result
120
121 @router.get(config.get("base_url") + "/api/mutual.json", response_class=JSONResponse)
122 def mutual(domains: list[str] = Query()):
123     """Return 200 if federation is open between the two, 4xx otherwise"""
124     fba.cursor.execute(
125         "SELECT block_level FROM blocks " \
126         "WHERE ((blocker = :a OR blocker = :b) AND (blocked = :b OR blocked = :a OR blocked = :aw OR blocked = :bw)) " \
127         "AND block_level = 'reject' " \
128         "LIMIT 1",
129         {
130             "a" : domains[0],
131             "b" : domains[1],
132             "aw": "*." + domains[0],
133             "bw": "*." + domains[1],
134         },
135     )
136     response = fba.cursor.fetchone()
137
138     if response is not None:
139         # Blocks found
140         return JSONResponse(status_code=418, content={})
141
142     # No known blocks
143     return JSONResponse(status_code=200, content={})
144
145 @router.get(config.get("base_url") + "/scoreboard")
146 def index(request: Request, blockers: int = None, blocked: int = None, reference: int = None, software: int = None, originator: int = None):
147     scores = None
148
149     if blockers != None and blockers > 0:
150         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?blockers={blockers}")
151     elif blocked != None and blocked > 0:
152         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?blocked={blocked}")
153     elif reference != None and reference > 0:
154         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?reference={reference}")
155     elif software != None and software > 0:
156         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?software={software}")
157     elif originator != None and originator > 0:
158         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?originator={originator}")
159     else:
160         raise HTTPException(status_code=400, detail="No filter specified")
161
162     if response == None:
163         raise HTTPException(status_code=500, detail="Could not determine scores")
164     elif not response.ok:
165         raise HTTPException(status_code=response.status_code, detail=response.text)
166
167     return templates.TemplateResponse("scoreboard.html", {
168         "base_url"  : config.get("base_url"),
169         "slogan"    : config.get("slogan"),
170         "request"   : request,
171         "scoreboard": True,
172         "blockers"  : blockers,
173         "blocked"   : blocked,
174         "reference" : reference,
175         "software"  : software,
176         "originator": originator,
177         "scores"    : fba.json_from_response(response)
178     })
179
180 @router.get(config.get("base_url") + "/")
181 def index(request: Request, domain: str = None, reason: str = None, reverse: str = None):
182     if domain == "" or reason == "" or reverse == "":
183         return fastapi.responses.RedirectResponse("/")
184
185     info = None
186     blocks = None
187
188     if domain == None and reason == None and reverse == None:
189         info = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/info.json")
190
191         if not info.ok:
192             raise HTTPException(status_code=info.status_code, detail=info.text)
193
194         info = info.json()
195     elif domain != None:
196         blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?domain={domain}")
197     elif reason != None:
198         blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?reason={reason}")
199     elif reverse != None:
200         blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?reverse={reverse}")
201
202     if blocks != None:
203         if not blocks.ok:
204             raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
205         blocks = blocks.json()
206         for block_level in blocks:
207             for block in blocks[block_level]:
208                 block["first_seen"] = datetime.utcfromtimestamp(block["first_seen"]).strftime('%Y-%m-%d %H:%M')
209                 block["last_seen"] = datetime.utcfromtimestamp(block["last_seen"]).strftime('%Y-%m-%d %H:%M')
210
211     return templates.TemplateResponse("index.html", {
212         "request": request,
213         "domain" : domain,
214         "blocks" : blocks,
215         "reason" : reason,
216         "reverse": reverse,
217         "info"   : info
218     })
219
220 @router.get(config.get("base_url") + "/rss")
221 def rss(request: Request, domain: str = None):
222     if domain != None:
223         wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
224         punycode = domain.encode('idna').decode('utf-8')
225         fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? ORDER BY first_seen DESC LIMIT 50",
226                   (domain, "*." + domain, wildchar, fba.get_hash(domain), punycode, "*." + punycode))
227     else:
228         fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks ORDER BY first_seen DESC LIMIT 50")
229
230     blocks = fba.cursor.fetchall()
231
232     result = []
233     for blocker, blocked, block_level, reason, first_seen, last_seen in blocks:
234         first_seen = utils.format_datetime(datetime.fromtimestamp(first_seen))
235         if reason == None or reason == '':
236             reason = "No reason provided."
237         else:
238             reason = "Provided reason: '" + reason + "'"
239
240         result.append({
241             "blocker"    : blocker,
242             "blocked"    : blocked,
243             "block_level": block_level,
244             "reason"     : reason,
245             "first_seen" : first_seen
246         })
247
248     timestamp = utils.format_datetime(datetime.now())
249
250     return templates.TemplateResponse("rss.xml", {
251         "request"  : request,
252         "timestamp": timestamp,
253         "domain"   : domain,
254         "blocks"   : result
255     }, headers={
256         "Content-Type": "routerlication/rss+xml"
257     })
258
259 @router.get(config.get("base_url") + "/robots.txt", response_class=PlainTextResponse)
260 def robots(request: Request):
261     return templates.TemplateResponse("robots.txt", {
262         "request" : request,
263         "base_url": config.get("base_url")
264     })
265
266 if __name__ == "__main__":
267     uvicorn.run("api:router", host=config.get("host"), port=config.get("port"), log_level=config.get("log_level"))