1 from fastapi import FastAPI, Request, HTTPException, responses, Query
2 from fastapi.templating import Jinja2Templates
3 from datetime import datetime
4 from email import utils
12 app = FastAPI(docs_url=fba.config["base_url"] + "/docs", redoc_url=fba.config["base_url"] + "/redoc")
13 templates = Jinja2Templates(directory=".")
15 @app.get(fba.config["base_url"] + "/info")
17 fba.c.execute("SELECT (SELECT COUNT(domain) FROM instances), (SELECT COUNT(domain) FROM instances WHERE software IN ('pleroma', 'mastodon', 'misskey', 'gotosocial', 'friendica')), (SELECT COUNT(blocker) FROM blocks)")
18 known, indexed, blocks = fba.c.fetchone()
21 "known_instances" : known,
22 "indexed_instances": indexed,
23 "blocks_recorded" : blocks,
24 "slogan" : fba.config["slogan"]
27 @app.get(fba.config["base_url"] + "/top")
28 def top(blocked: int = None, blockers: int = None, reference: int = None, software: int = None):
31 raise HTTPException(status_code=400, detail="Too many results")
32 fba.c.execute("SELECT blocked, COUNT(blocked) FROM blocks WHERE block_level = 'reject' GROUP BY blocked ORDER BY COUNT(blocked) DESC LIMIT ?", [blocked])
33 elif blockers != None:
35 raise HTTPException(status_code=400, detail="Too many results")
36 fba.c.execute("SELECT blocker, COUNT(blocker) FROM blocks WHERE block_level = 'reject' GROUP BY blocker ORDER BY COUNT(blocker) DESC LIMIT ?", [blockers])
37 elif reference != None:
39 raise HTTPException(status_code=400, detail="Too many results")
40 fba.c.execute("SELECT origin, COUNT(domain) FROM instances GROUP BY origin ORDER BY COUNT(domain) DESC LIMIT ?", [reference])
41 elif software != None:
43 raise HTTPException(status_code=400, detail="Too many results")
44 fba.c.execute("SELECT software, COUNT(domain) FROM instances GROUP BY software ORDER BY COUNT(domain) DESC LIMIT ?", [software])
46 raise HTTPException(status_code=400, detail="No filter specified")
48 scores = fba.c.fetchall()
52 for domain, highscore in scores:
53 scoreboard.append({"domain": domain, "highscore": highscore})
57 @app.get(fba.config["base_url"] + "/api")
58 def blocked(domain: str = None, reason: str = None, reverse: str = None):
59 if domain == None and reason == None and reverse == None:
60 raise HTTPException(status_code=400, detail="No filter specified")
62 reason = re.sub("(%|_)", "", reason)
64 raise HTTPException(status_code=400, detail="Keyword is shorter than three characters")
66 wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
67 punycode = domain.encode('idna').decode('utf-8')
68 fba.c.execute("SELECT blocker, blocked, block_level, reason, first_added, last_seen FROM blocks WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? ORDER BY first_added ASC",
69 (domain, "*." + domain, wildchar, fba.get_hash(domain), punycode, "*." + punycode))
71 fba.c.execute("SELECT blocker, blocked, block_level, reason, first_added, last_seen FROM blocks WHERE blocker = ? ORDER BY first_added ASC", [reverse])
73 fba.c.execute("SELECT blocker, blocked, block_level, reason, first_added, last_seen FROM blocks WHERE reason like ? AND reason != '' ORDER BY first_added ASC", ["%" + reason + "%"])
74 blocks = fba.c.fetchall()
77 for blocker, blocked, block_level, reason, first_added, last_seen in blocks:
82 "first_added": first_added,
83 "last_seen" : last_seen
85 if block_level in result:
86 result[block_level].append(entry)
88 result[block_level] = [entry]
92 @app.get(fba.config["base_url"] + "/scoreboard")
93 def index(request: Request, blockers: int = None, blocked: int = None, reference: int = None, software: int = None):
96 if blockers != None and blockers > 0:
97 res = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/top?blockers={blockers}")
98 elif blocked != None and blocked > 0:
99 res = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/top?blocked={blocked}")
100 elif reference != None and reference > 0:
101 res = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/top?reference={reference}")
102 elif software != None and software > 0:
103 res = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/top?software={software}")
105 raise HTTPException(status_code=400, detail="No filter specified")
108 raise HTTPException(status_code=500, detail="Could not determine scores")
110 raise HTTPException(status_code=res.status_code, detail=res.text)
112 return templates.TemplateResponse("index.html", {
113 "base_url" : fba.config["base_url"],
116 "blockers" : blockers,
118 "reference" : reference,
119 "software" : software,
120 "scores" : res.json()
123 @app.get(fba.config["base_url"] + "/")
124 def index(request: Request, domain: str = None, reason: str = None, reverse: str = None):
125 if domain == "" or reason == "" or reverse == "":
126 return responses.RedirectResponse("/")
131 if domain == None and reason == None and reverse == None:
132 info = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/info")
135 raise HTTPException(status_code=info.status_code, detail=info.text)
139 blocks = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?domain={domain}")
141 blocks = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?reason={reason}")
142 elif reverse != None:
143 blocks = requests.get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?reverse={reverse}")
147 raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
148 blocks = blocks.json()
149 for block_level in blocks:
150 for block in blocks[block_level]:
151 block["first_added"] = datetime.utcfromtimestamp(block["first_added"]).strftime('%Y-%m-%d %H:%M')
152 block["last_seen"] = datetime.utcfromtimestamp(block["last_seen"]).strftime('%Y-%m-%d %H:%M')
154 return templates.TemplateResponse("index.html", {"request": request, "domain": domain, "blocks": blocks, "reason": reason, "reverse": reverse, "info": info})
156 @app.get(fba.config["base_url"] + "/api/mutual")
157 def mutual(domains: list[str] = Query()):
158 """Return 200 if federation is open between the two, 4xx otherwise"""
160 "SELECT block_level FROM blocks " \
161 "WHERE ((blocker = :a OR blocker = :b) AND (blocked = :b OR blocked = :a OR blocked = :aw OR blocked = :bw)) " \
162 "AND block_level = 'reject' " \
167 "aw": "*." + domains[0],
168 "bw": "*." + domains[1],
171 res = fba.c.fetchone()
175 return responses.JSONResponse(status_code=418, content={})
178 return responses.JSONResponse(status_code=200, content={})
180 @app.get(fba.config["base_url"] + "/rss")
181 def rss(request: Request, domain: str = None):
183 wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
184 punycode = domain.encode('idna').decode('utf-8')
185 fba.c.execute("SELECT blocker, blocked, block_level, reason, first_added, last_seen FROM blocks WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? ORDER BY first_added DESC LIMIT 50",
186 (domain, "*." + domain, wildchar, fba.get_hash(domain), punycode, "*." + punycode))
188 fba.c.execute("SELECT blocker, blocked, block_level, reason, first_added, last_seen FROM blocks ORDER BY first_added DESC LIMIT 50")
190 blocks = fba.c.fetchall()
193 for blocker, blocked, block_level, reason, first_added, last_seen in blocks:
194 first_added = utils.format_datetime(datetime.fromtimestamp(first_added))
195 if reason == None or reason == '':
196 reason = "No reason provided."
198 reason = "Provided reason: '" + reason + "'"
203 "block_level": block_level,
205 "first_added": first_added
208 timestamp = utils.format_datetime(datetime.now())
210 return templates.TemplateResponse("rss.xml", {
212 "timestamp": timestamp,
216 "Content-Type": "application/rss+xml"
219 if __name__ == "__main__":
220 uvicorn.run("api:app", host="127.0.0.1", port=fba.config["port"], log_level=fba.config["log_level"])