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/>.
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
30 router = fastapi.FastAPI(docs_url=config.get("base_url") + "/docs", redoc_url=config.get("base_url") + "/redoc")
31 templates = Jinja2Templates(directory="templates")
33 @router.get(config.get("base_url") + "/api/info.json", response_class=JSONResponse)
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()
39 "known_instances" : known,
40 "indexed_instances" : indexed,
41 "blocks_recorded" : blocks,
42 "errorous_instances": errorous,
43 "slogan" : config.get("slogan")
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):
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:
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:
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:
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:
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])
69 raise HTTPException(status_code=400, detail="No filter specified")
71 scores = fba.cursor.fetchall()
75 for domain, highscore in scores:
78 "highscore": highscore
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")
89 reason = re.sub("(%|_)", "", reason)
91 raise HTTPException(status_code=400, detail="Keyword is shorter than three characters")
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))
99 fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE blocker = ? ORDER BY first_seen ASC", [reverse])
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 + "%"])
103 blocks = fba.cursor.fetchall()
106 for blocker, blocked, block_level, reason, first_seen, last_seen in blocks:
111 "first_seen": first_seen,
112 "last_seen" : last_seen
114 if block_level in result:
115 result[block_level].append(entry)
117 result[block_level] = [entry]
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"""
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' " \
132 "aw": "*." + domains[0],
133 "bw": "*." + domains[1],
136 response = fba.cursor.fetchone()
138 if response is not None:
140 return JSONResponse(status_code=418, content={})
143 return JSONResponse(status_code=200, content={})
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):
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}")
160 raise HTTPException(status_code=400, detail="No filter specified")
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)
167 return templates.TemplateResponse("scoreboard.html", {
168 "base_url" : config.get("base_url"),
169 "slogan" : config.get("slogan"),
172 "blockers" : blockers,
174 "reference" : reference,
175 "software" : software,
176 "originator": originator,
177 "scores" : fba.json_from_response(response)
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("/")
185 response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/info.json")
188 raise HTTPException(status_code=response.status_code, detail=response.text)
190 info = response.json()
194 blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?domain={domain}")
196 blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?reason={reason}")
197 elif reverse != None:
198 blocks = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/index.json?reverse={reverse}")
202 raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
203 blocks = blocks.json()
204 for block_level in blocks:
205 for block in blocks[block_level]:
206 block["first_seen"] = datetime.utcfromtimestamp(block["first_seen"]).strftime(config.get("timestamp_format"))
207 block["last_seen"] = datetime.utcfromtimestamp(block["last_seen"]).strftime(config.get("timestamp_format"))
209 return templates.TemplateResponse("index.html", {
218 @router.get(config.get("base_url") + "/rss")
219 def rss(request: Request, domain: str = None):
221 wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
222 punycode = domain.encode('idna').decode('utf-8')
223 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",
224 (domain, "*." + domain, wildchar, fba.get_hash(domain), punycode, "*." + punycode))
226 fba.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks ORDER BY first_seen DESC LIMIT 50")
228 result = fba.cursor.fetchall()
231 for blocker, blocked, block_level, reason, first_seen, last_seen in result:
232 first_seen = utils.format_datetime(datetime.fromtimestamp(first_seen))
233 if reason == None or reason == '':
234 reason = "No reason provided."
236 reason = "Provided reason: '" + reason + "'"
241 "block_level": block_level,
243 "first_seen" : first_seen
246 return templates.TemplateResponse("rss.xml", {
248 "timestamp": utils.format_datetime(datetime.now()),
250 "hostname" : config.get("hostname"),
253 "Content-Type": "routerlication/rss+xml"
256 @router.get(config.get("base_url") + "/robots.txt", response_class=PlainTextResponse)
257 def robots(request: Request):
258 return templates.TemplateResponse("robots.txt", {
260 "base_url": config.get("base_url")
263 if __name__ == "__main__":
264 uvicorn.run("api:router", host=config.get("host"), port=config.get("port"), log_level=config.get("log_level"))