]> git.mxchange.org Git - fba.git/blob - api.py
Fix (?) for yet more duplicate uppercase entries
[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         c.execute("select blocker, block_level, reason from blocks where blocked = ? or blocked = ? or blocked = ? or blocked = ?", (domain, "*." + domain, wildchar, get_hash(domain)))
42     else:
43         c.execute("select * from blocks where reason like ? and reason != ''", ("%"+reason+"%",))
44     blocks = c.fetchall()
45     conn.close()
46
47     result = {}
48     reasons = {}
49     if domain != None:
50         for domain, block_level, reason in blocks:
51             if block_level in result:
52                 result[block_level].append(domain)
53             else:
54                 result[block_level] = [domain]
55                 
56             if reason != "":
57                 if block_level in reasons:
58                     reasons[block_level][domain] = reason
59                 else:
60                     reasons[block_level] = {domain: reason}
61         return {"blocks": result, "reasons": reasons}
62
63     for blocker, blocked, reason, block_level in blocks:
64         if block_level in result:
65             result[block_level].append({"blocker": blocker, "blocked": blocked, "reason": reason})
66         else:
67             result[block_level] = [{"blocker": blocker, "blocked": blocked, "reason": reason}]
68     return {"blocks": result}
69
70 @app.get(base_url+"/")
71 def index(request: Request, domain: str = None, reason: str = None):
72     if domain == "" or reason == "":
73         return responses.RedirectResponse("/")
74     info = None
75     blocks = None
76     if domain == None and reason == None:
77         info = get(f"http://127.0.0.1:{port}{base_url}/info")
78         if not info.ok:
79             raise HTTPException(status_code=info.status_code, detail=info.text)
80         info = info.json()
81     elif domain != None:
82         blocks = get(f"http://127.0.0.1:{port}{base_url}/api?domain={domain}")
83     elif reason != None:
84         blocks = get(f"http://127.0.0.1:{port}{base_url}/api?reason={reason}")
85     if blocks != None:
86         if not blocks.ok:
87             raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
88         blocks = blocks.json()
89     return templates.TemplateResponse("index.html", {"request": request, "domain": domain, "blocks": blocks, "reason": reason, "info": info})
90
91 if __name__ == "__main__":
92     uvicorn.run("api:app", host="127.0.0.1", port=port, log_level="info")