api.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import uvicorn
  2. from fastapi import FastAPI, Request, HTTPException, responses, Query
  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. from re import sub
  9. from datetime import datetime
  10. from email import utils
  11. with open("config.json") as f:
  12. config = loads(f.read())
  13. base_url = config["base_url"]
  14. port = config["port"]
  15. app = FastAPI(docs_url=base_url+"/docs", redoc_url=base_url+"/redoc")
  16. templates = Jinja2Templates(directory=".")
  17. def get_hash(domain: str) -> str:
  18. return sha256(domain.encode("utf-8")).hexdigest()
  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', 'misskey', 'gotosocial', 'friendica', 'lemmy')), (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. }
  31. @app.get(base_url+"/top")
  32. def top(blocked: int = None, blockers: int = None):
  33. conn = sqlite3.connect("blocks.db")
  34. c = conn.cursor()
  35. if blocked == None and blockers == None:
  36. raise HTTPException(status_code=400, detail="No filter specified")
  37. elif blocked != None:
  38. if blocked > 500:
  39. raise HTTPException(status_code=400, detail="Too many results")
  40. c.execute("select blocked, count(blocked) from blocks where block_level = 'reject' group by blocked order by count(blocked) desc limit ?", (blocked,))
  41. elif blockers != None:
  42. if blockers > 500:
  43. raise HTTPException(status_code=400, detail="Too many results")
  44. c.execute("select blocker, count(blocker) from blocks where block_level = 'reject' group by blocker order by count(blocker) desc limit ?", (blockers,))
  45. scores = c.fetchall()
  46. c.close()
  47. scoreboard = []
  48. print(scores)
  49. for domain, highscore in scores:
  50. scoreboard.append({"domain": domain, "highscore": highscore})
  51. return scoreboard
  52. @app.get(base_url+"/top/weighted")
  53. def weighted():
  54. conn = sqlite3.connect("blocks.db")
  55. c = conn.cursor()
  56. # trying to make the limit adjustable makes the app crash with `sqlite3.IntegrityError: datatype mismatch`, so rolling with hardcoded one
  57. c.execute("with weighted as (SELECT blocker, count(*) as instance_weight FROM blocks where block_level = 'reject' GROUP BY blocker) SELECT rank() OVER (order by sum(1 / log(instance_weight)) desc) as rank, b.blocked, count(*) as total_blocks, sum(1 / log(instance_weight + 1)) as weighted_score FROM blocks b JOIN weighted USING (blocker) GROUP BY b.blocked order by weighted_score DESC LIMIT 100")
  58. scores = c.fetchall()
  59. c.close()
  60. scoreboard = []
  61. print(scores)
  62. for rank, domain, blocks, weight in scores:
  63. scoreboard.append({"domain": domain, "blocks": blocks, "weight": round(weight, 4)})
  64. return scoreboard
  65. @app.get(base_url+"/api")
  66. def blocked(domain: str = None, reason: str = None, reverse: str = None):
  67. if domain == None and reason == None and reverse == None:
  68. raise HTTPException(status_code=400, detail="No filter specified")
  69. if reason != None:
  70. reason = sub("(%|_)", "", reason)
  71. if len(reason) < 3:
  72. raise HTTPException(status_code=400, detail="Keyword is shorter than three characters")
  73. conn = sqlite3.connect("blocks.db")
  74. c = conn.cursor()
  75. if domain != None:
  76. wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
  77. punycode = domain.encode('idna').decode('utf-8')
  78. c.execute("select blocker, blocked, block_level, reason, first_added, last_seen from blocks where blocked = ? collate nocase or blocked = ? collate nocase or blocked = ? collate nocase or blocked = ? collate nocase or blocked = ? collate nocase or blocked = ? collate nocase order by first_added asc",
  79. (domain, "*." + domain, wildchar, get_hash(domain), punycode, "*." + punycode))
  80. elif reverse != None:
  81. c.execute("select blocker, blocked, block_level, reason, first_added, last_seen from blocks where blocker = ? collate nocase order by first_added asc", (reverse,))
  82. else:
  83. c.execute("select blocker, blocked, block_level, reason, first_added, last_seen from blocks where reason like ? and reason != '' collate nocase order by first_added asc", ("%"+reason+"%",))
  84. blocks = c.fetchall()
  85. c.close()
  86. result = {}
  87. for blocker, blocked, block_level, reason, first_added, last_seen in blocks:
  88. entry = {"blocker": blocker, "blocked": blocked, "reason": reason, "first_added": first_added, "last_seen": last_seen}
  89. if block_level in result:
  90. result[block_level].append(entry)
  91. else:
  92. result[block_level] = [entry]
  93. return result
  94. @app.get(base_url+"/scoreboard")
  95. def index(request: Request, blockers: int = None, blocked: int = None):
  96. if blockers == None and blocked == None:
  97. raise HTTPException(status_code=400, detail="No filter specified")
  98. elif blockers != None:
  99. scores = get(f"http://127.0.0.1:{port}{base_url}/top?blockers={blockers}")
  100. elif blocked != None:
  101. scores = get(f"http://127.0.0.1:{port}{base_url}/top?blocked={blocked}")
  102. if scores != None:
  103. if not scores.ok:
  104. raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
  105. scores = scores.json()
  106. return templates.TemplateResponse("index.html", {"request": request, "scoreboard": True, "blockers": blockers, "blocked": blocked, "scores": scores})
  107. @app.get(base_url+"/weighted")
  108. def index(request: Request):
  109. scores = get(f"http://127.0.0.1:{port}{base_url}/top/weighted")
  110. if scores != None:
  111. if not scores.ok:
  112. raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
  113. scores = scores.json()
  114. return templates.TemplateResponse("index.html", {"request": request, "weighted": True, "scores": scores})
  115. @app.get(base_url+"/")
  116. def index(request: Request, domain: str = None, reason: str = None, reverse: str = None):
  117. if domain == "" or reason == "" or reverse == "":
  118. return responses.RedirectResponse("/")
  119. info = None
  120. blocks = None
  121. if domain == None and reason == None and reverse == None:
  122. info = get(f"http://127.0.0.1:{port}{base_url}/info")
  123. if not info.ok:
  124. raise HTTPException(status_code=info.status_code, detail=info.text)
  125. info = info.json()
  126. elif domain != None:
  127. blocks = get(f"http://127.0.0.1:{port}{base_url}/api?domain={domain}")
  128. elif reason != None:
  129. blocks = get(f"http://127.0.0.1:{port}{base_url}/api?reason={reason}")
  130. elif reverse != None:
  131. blocks = get(f"http://127.0.0.1:{port}{base_url}/api?reverse={reverse}")
  132. if blocks != None:
  133. if not blocks.ok:
  134. raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
  135. blocks = blocks.json()
  136. for block_level in blocks:
  137. for block in blocks[block_level]:
  138. block["first_added"] = datetime.utcfromtimestamp(block["first_added"]).strftime('%Y-%m-%d %H:%M')
  139. block["last_seen"] = datetime.utcfromtimestamp(block["last_seen"]).strftime('%Y-%m-%d %H:%M')
  140. return templates.TemplateResponse("index.html", {"request": request, "domain": domain, "blocks": blocks, "reason": reason, "reverse": reverse, "info": info})
  141. @app.get(base_url+"/api/mutual")
  142. def mutual(domains: list[str] = Query()):
  143. """Return 200 if federation is open between the two, 4xx otherwise"""
  144. conn = sqlite3.connect('blocks.db')
  145. c = conn.cursor()
  146. c.execute(
  147. "SELECT block_level FROM blocks " \
  148. "WHERE ((blocker = :a OR blocker = :b) AND (blocked = :b OR blocked = :a OR blocked = :aw OR blocked = :bw)) " \
  149. "AND block_level = 'reject' " \
  150. "LIMIT 1",
  151. {
  152. "a": domains[0],
  153. "b": domains[1],
  154. "aw": "*." + domains[0],
  155. "bw": "*." + domains[1],
  156. },
  157. )
  158. res = c.fetchone()
  159. c.close()
  160. if res is not None:
  161. # Blocks found
  162. return responses.JSONResponse(status_code=418, content={})
  163. # No known blocks
  164. return responses.JSONResponse(status_code=200, content={})
  165. @app.get(base_url+"/rss")
  166. def rss(request: Request, domain: str = None):
  167. conn = sqlite3.connect("blocks.db")
  168. c = conn.cursor()
  169. if domain != None:
  170. wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
  171. punycode = domain.encode('idna').decode('utf-8')
  172. 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",
  173. (domain, "*." + domain, wildchar, get_hash(domain), punycode, "*." + punycode))
  174. else:
  175. c.execute("select blocker, blocked, block_level, reason, first_added, last_seen from blocks order by first_added desc limit 50")
  176. blocks = c.fetchall()
  177. c.close()
  178. result = []
  179. for blocker, blocked, block_level, reason, first_added, last_seen in blocks:
  180. first_added = utils.format_datetime(datetime.fromtimestamp(first_added))
  181. if reason == None or reason == '':
  182. reason = "No reason provided."
  183. else:
  184. reason = "Provided reason: '" + reason + "'"
  185. result.append({"blocker": blocker, "blocked": blocked, "block_level": block_level, "reason": reason, "first_added": first_added})
  186. timestamp = utils.format_datetime(datetime.now())
  187. return templates.TemplateResponse("rss.xml", {"request": request, "timestamp": timestamp, "domain": domain, "blocks": result}, headers={"Content-Type": "application/rss+xml"})
  188. if __name__ == "__main__":
  189. uvicorn.run("api:app", host="127.0.0.1", port=port, log_level="info")