fedi-block-api/api.py

68 lines
2.4 KiB
Python
Raw Normal View History

2022-04-22 17:49:23 +00:00
from fastapi import FastAPI, Request, HTTPException
2022-03-31 21:09:13 +00:00
import sqlite3
2022-04-22 12:58:23 +00:00
from hashlib import sha256
2022-04-22 17:49:23 +00:00
from fastapi.templating import Jinja2Templates
from requests import get
2022-03-31 21:09:13 +00:00
base_url = ""
app = FastAPI(docs_url=base_url+"/docs", redoc_url=base_url+"/redoc")
2022-04-22 17:49:23 +00:00
templates = Jinja2Templates(directory=".")
2022-03-31 21:09:13 +00:00
2022-04-22 12:58:23 +00:00
def get_hash(domain: str) -> str:
return sha256(domain.encode("utf-8")).hexdigest()
2022-03-31 21:09:13 +00:00
@app.get(base_url+"/info")
def info():
conn = sqlite3.connect("blocks.db")
c = conn.cursor()
c.execute("select (select count(domain) from instances), (select count(domain) from instances where software in ('pleroma', 'mastodon')), (select count(blocker) from blocks)")
known, indexed, blocks = c.fetchone()
c.close()
return {
"known_instances": known,
"indexed_instances": indexed,
"blocks_recorded": blocks,
"source_code": "https://gitlab.com/EnjuAihara/fedi-block-api",
}
2022-04-22 17:49:23 +00:00
@app.get(base_url+"/api")
def blocked(domain: str = None):
if domain == None:
raise HTTPException(status_code=400, detail="No domain specified")
2022-03-31 21:09:13 +00:00
conn = sqlite3.connect("blocks.db")
c = conn.cursor()
2022-04-22 02:25:29 +00:00
wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
2022-04-22 12:58:23 +00:00
c.execute("select blocker, block_level, reason from blocks where blocked = ? or blocked = ? or blocked = ?", (domain, wildchar, get_hash(domain)))
2022-03-31 21:09:13 +00:00
blocks = c.fetchall()
conn.close()
result = {}
reasons = {}
2022-04-14 12:04:53 +00:00
for domain, block_level, reason in blocks:
if block_level in result:
result[block_level].append(domain)
else:
result[block_level] = [domain]
if reason != "":
if block_level in reasons:
reasons[block_level][domain] = reason
else:
reasons[block_level] = {domain: reason}
return {"blocks": result, "reasons": reasons}
2022-03-31 21:09:13 +00:00
2022-04-22 17:49:23 +00:00
@app.get(base_url+"/")
def index(request: Request, domain: str = None):
2022-04-22 17:58:43 +00:00
blocks = get(f"http://127.0.0.1:8069{base_url}/api?domain={domain}")
2022-04-22 17:49:23 +00:00
info = None
if domain == None:
2022-04-22 17:58:43 +00:00
info = get(f"http://127.0.0.1:8069{base_url}/info")
2022-04-22 17:49:23 +00:00
if not info.ok:
raise HTTPException(status_code=info.status_code, detail=info.text)
info = info.json()
if not blocks.ok:
raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
return templates.TemplateResponse("index.html", {"request": request, "domain": domain, "blocks": blocks.json(), "info": info})