]> git.mxchange.org Git - fba.git/blob - api.py
a
[fba.git] / api.py
1 import uvicorn
2 from fastapi import FastAPI, Request, HTTPException, responses
3 import sqlite3
4 from hashlib import sha256
5 from fastapi.templating import Jinja2Templates
6 from requests import get
7 from json import loads
8
9 with open("config.json") as f:
10     config = loads(f.read())
11     base_url = config["base_url"]
12     port = config["port"]
13 app = FastAPI(docs_url=base_url+"/docs", redoc_url=base_url+"/redoc")
14 templates = Jinja2Templates(directory=".")
15
16 def get_hash(domain: str) -> str:
17     return sha256(domain.encode("utf-8")).hexdigest()
18
19 @app.get(base_url+"/info")
20 def info():
21     conn = sqlite3.connect("blocks.db")
22     c = conn.cursor()
23     c.execute("select (select count(domain) from instances), (select count(domain) from instances where software in ('pleroma', 'mastodon')), (select count(blocker) from blocks)")
24     known, indexed, blocks = c.fetchone()
25     c.close()
26     return {
27         "known_instances": known,
28         "indexed_instances": indexed,
29         "blocks_recorded": blocks,
30         "source_code": "https://git.kiwifarms.net/mint/fedi-block-api",
31     }
32
33 @app.get(base_url+"/api")
34 def blocked(domain: str = None, reason: str = None):
35     if domain == None and reason == None:
36         raise HTTPException(status_code=400, detail="No filter specified")
37     conn = sqlite3.connect("blocks.db")
38     c = conn.cursor()
39     if domain != None:
40         wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
41         punycode = domain.encode('idna').decode('utf-8')
42         c.execute("select blocker, blocked, block_level, reason from blocks where blocked = ? or blocked = ? or blocked = ? or blocked = ? or blocked = ? or blocked = ?",
43                   (domain, "*." + domain, wildchar, get_hash(domain), punycode, "*." + punycode))
44     else:
45         c.execute("select * from blocks where reason like ? and reason != ''", ("%"+reason+"%",))
46     blocks = c.fetchall()
47     conn.close()
48
49     result = {}
50     reasons = {}
51     wildcards = []
52     if domain != None:
53         for domain, blocked, block_level, reason in blocks:
54             if block_level in result:
55                 result[block_level].append(domain)
56             else:
57                 result[block_level] = [domain]
58             if blocked == "*." + ".".join(blocked.split(".")[-blocked.count("."):]):
59                 wildcards.append(domain)
60             if reason != "":
61                 if block_level in reasons:
62                     reasons[block_level][domain] = reason
63                 else:
64                     reasons[block_level] = {domain: reason}
65         return {"blocks": result, "reasons": reasons, "wildcards": wildcards}
66
67     for blocker, blocked, reason, block_level in blocks:
68         if block_level in result:
69             result[block_level].append({"blocker": blocker, "blocked": blocked, "reason": reason})
70         else:
71             result[block_level] = [{"blocker": blocker, "blocked": blocked, "reason": reason}]
72     return {"blocks": result}
73
74 @app.get(base_url+"/")
75 def index(request: Request, domain: str = None, reason: str = None):
76     if domain == "" or reason == "":
77         return responses.RedirectResponse("/")
78     info = None
79     blocks = None
80     if domain == None and reason == None:
81         info = get(f"http://127.0.0.1:{port}{base_url}/info")
82         if not info.ok:
83             raise HTTPException(status_code=info.status_code, detail=info.text)
84         info = info.json()
85     elif domain != None:
86         blocks = get(f"http://127.0.0.1:{port}{base_url}/api?domain={domain}")
87     elif reason != None:
88         blocks = get(f"http://127.0.0.1:{port}{base_url}/api?reason={reason}")
89     if blocks != None:
90         if not blocks.ok:
91             raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
92         blocks = blocks.json()
93     return templates.TemplateResponse("index.html", {"request": request, "domain": domain, "blocks": blocks, "wildcards": wildcards, "reason": reason, "info": info})
94
95 if __name__ == "__main__":
96     uvicorn.run("api:app", host="127.0.0.1", port=port, log_level="info")