]> git.mxchange.org Git - fba.git/commitdiff
Continued:
authorRoland Häder <roland@mxchange.org>
Fri, 19 May 2023 17:30:27 +0000 (19:30 +0200)
committerRoland Häder <roland@mxchange.org>
Fri, 19 May 2023 17:30:27 +0000 (19:30 +0200)
- added auto-discoverable RSS feed
- introduced post_json_api()
- some debug lines added

api.py
fba.py
index.html

diff --git a/api.py b/api.py
index f9605e3811d554e848b7c31b5f7771afbcb1432d..df4c1f8d26ca06fe17194756a4f92d187f5384bc 100644 (file)
--- a/api.py
+++ b/api.py
@@ -88,22 +88,36 @@ def index(request: Request, blockers: int = None, blocked: int = None):
         scores = get(f"http://127.0.0.1:{fba.config['base_url']}{fba.config['base_url']}/top?blockers={blockers}")
     elif blocked != None:
         scores = get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/top?blocked={blocked}")
+
     if scores != None:
         if not scores.ok:
             raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
+
         scores = scores.json()
-    return templates.TemplateResponse("index.html", {"request": request, "scoreboard": True, "blockers": blockers, "blocked": blocked, "scores": scores})
+
+    return templates.TemplateResponse("index.html", {
+        "base_url": fba.config["base_url"],
+        "request": request,
+        "scoreboard": True,
+        "blockers": blockers,
+        "blocked": blocked,
+        "scores": scores
+    })
 
 @app.get(fba.config["base_url"] + "/")
 def index(request: Request, domain: str = None, reason: str = None, reverse: str = None):
     if domain == "" or reason == "" or reverse == "":
         return responses.RedirectResponse("/")
+
     info = None
     blocks = None
+
     if domain == None and reason == None and reverse == None:
         info = get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/info")
+
         if not info.ok:
             raise HTTPException(status_code=info.status_code, detail=info.text)
+
         info = info.json()
     elif domain != None:
         blocks = get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?domain={domain}")
@@ -111,6 +125,7 @@ def index(request: Request, domain: str = None, reason: str = None, reverse: str
         blocks = get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?reason={reason}")
     elif reverse != None:
         blocks = get(f"http://127.0.0.1:{fba.config['port']}{fba.config['base_url']}/api?reverse={reverse}")
+
     if blocks != None:
         if not blocks.ok:
             raise HTTPException(status_code=blocks.status_code, detail=blocks.text)
diff --git a/fba.py b/fba.py
index c18c623802d088eb45cf25ae76a2faada6c6465b..4f2e05de7ab5daf9ba4960afc247ad1e090b4a00 100644 (file)
--- a/fba.py
+++ b/fba.py
@@ -26,40 +26,62 @@ conn = sqlite3.connect("blocks.db")
 c = conn.cursor()
 
 def get_hash(domain: str) -> str:
+    # NOISY-DEBUG: print("DEBUG: Calculating hash for domain:", domain)
     return sha256(domain.encode("utf-8")).hexdigest()
 
 def get_peers(domain: str) -> str:
+    # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
+    peers = None
+
     try:
         res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=5)
-        return res.json()
+        peers = res.json()
     except:
         print("WARNING: Cannot fetch peers:", domain, res.status_code)
-        return None
 
-def get_type(instdomain: str) -> str:
+    # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
+    return peers
+
+def post_json_api(domain: str, path: str, data: str) -> str:
+    # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data():", domain, path, len(data))
+    doc = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=5).json()
+
+    if doc == []:
+        print("WARNING: Cannot query JSON API:", domain, path)
+        raise
+
+    # NOISY-DEBUG: print("DEBUG: Returning doc():", len(doc))
+    return doc
+
+def determine_software(domain: str) -> str:
+    # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
+    software = None
     try:
-        res = reqto.get(f"https://{instdomain}/nodeinfo/2.1.json", headers=headers, timeout=5)
+        res = reqto.get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5)
         if res.status_code == 404:
-            res = reqto.get(f"https://{instdomain}/nodeinfo/2.0", headers=headers, timeout=5)
+            res = reqto.get(f"https://{domain}/nodeinfo/2.0", headers=headers, timeout=5)
         if res.status_code == 404:
-            res = reqto.get(f"https://{instdomain}/nodeinfo/2.0.json", headers=headers, timeout=5)
+            res = reqto.get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5)
         if res.ok and "text/html" in res.headers["content-type"]:
-            res = reqto.get(f"https://{instdomain}/nodeinfo/2.1", headers=headers, timeout=5)
+            res = reqto.get(f"https://{domain}/nodeinfo/2.1", headers=headers, timeout=5)
         if res.ok:
             if res.json()["software"]["name"] in ["akkoma", "rebased"]:
-                return "pleroma"
+                software = "pleroma"
             elif res.json()["software"]["name"] in ["hometown", "ecko"]:
-                return "mastodon"
+                software = "mastodon"
             elif res.json()["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
-                return "misskey"
+                software = "misskey"
             else:
-                return res.json()["software"]["name"]
+                software = res.json()["software"]["name"]
         elif res.status_code == 404:
-            res = reqto.get(f"https://{instdomain}/api/v1/instance", headers=headers, timeout=5)
+            res = reqto.get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5)
         if res.ok:
-            return "mastodon"
+            software = "mastodon"
     except:
-        return None
+        print("WARNING: Failed fetching instance meta data")
+
+    # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
+    return software
 
 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
     # NOISY: print("--- Updating block reason:", reason, blocker, blocked, block_level)
@@ -73,6 +95,7 @@ def update_block_reason(reason: str, blocker: str, blocked: str, block_level: st
                 block_level
             ),
         )
+
     except:
         print("ERROR: failed SQL query")
         sys.exit(255)
@@ -89,6 +112,7 @@ def update_last_seen(last_seen: int, blocker: str, blocked: str, block_level: st
                 block_level
             )
         )
+
     except:
         print("ERROR: failed SQL query")
         sys.exit(255)
@@ -107,6 +131,7 @@ def block_instance(blocker: str, blocked: str, reason: str, block_level: str, fi
                  last_seen
              ),
         )
+
     except:
         print("ERROR: failed SQL query")
         sys.exit(255)
@@ -119,9 +144,10 @@ def add_instance(domain: str):
             (
                domain,
                get_hash(domain),
-               get_type(domain)
+               determine_software(domain)
             ),
         )
+
     except:
         print("ERROR: failed SQL query")
         sys.exit(255)
@@ -140,17 +166,22 @@ def send_bot_post(instance: str, blocks: dict):
         else:
             if len(block["reason"]) > 420:
                 block["reason"] = block["reason"][0:419] + "[…]"
+
             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
+
     if truncated:
         message = message + "(the list has been truncated to the first 20 entries)"
 
     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
+
     req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
         data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
         headers=botheaders, timeout=10).json()
+
     return True
 
 def get_mastodon_blocks(domain: str) -> dict:
+    # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
     blocks = {
         "Suspended servers": [],
         "Filtered media": [],
@@ -186,8 +217,10 @@ def get_mastodon_blocks(domain: str) -> dict:
 
     for header in doc.find_all("h3"):
         header_text = header.text
+
         if header_text in translations:
             header_text = translations[header_text]
+
         if header_text in blocks:
             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
@@ -198,14 +231,16 @@ def get_mastodon_blocks(domain: str) -> dict:
                         "reason": line.find_all("td")[1].text.strip(),
                     }
                 )
+
+    # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
     return {
         "reject": blocks["Suspended servers"],
         "media_removal": blocks["Filtered media"],
-        "followers_only": blocks["Limited servers"]
-        + blocks["Silenced servers"],
+        "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
     }
 
 def get_friendica_blocks(domain: str) -> dict:
+    # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
     blocks = []
 
     try:
@@ -214,6 +249,7 @@ def get_friendica_blocks(domain: str) -> dict:
             "html.parser",
         )
     except:
+        print("WARNING: Failed to fetch /friendica from domain:", domain)
         return {}
 
     blocklist = doc.find(id="about_blocklist")
@@ -224,18 +260,18 @@ def get_friendica_blocks(domain: str) -> dict:
         return {}
 
     for line in blocklist.find("table").find_all("tr")[1:]:
-        blocks.append(
-            {
-                "domain": line.find_all("td")[0].text.strip(),
-                "reason": line.find_all("td")[1].text.strip()
-            }
-        )
+        blocks.append({
+            "domain": line.find_all("td")[0].text.strip(),
+            "reason": line.find_all("td")[1].text.strip()
+        })
 
+    # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
     return {
         "reject": blocks
     }
 
 def get_misskey_blocks(domain: str) -> dict:
+    # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
     blocks = {
         "suspended": [],
         "blocked": []
@@ -245,14 +281,26 @@ def get_misskey_blocks(domain: str) -> dict:
         counter = 0
         step = 99
         while True:
-            # iterating through all "suspended" (follow-only in its terminology) instances page-by-page, since that troonware doesn't support sending them all at once
+            # iterating through all "suspended" (follow-only in its terminology)
+            # instances page-by-page, since that troonware doesn't support
+            # sending them all at once
             try:
                 if counter == 0:
-                    doc = reqto.post(f"https://{domain}/api/federation/instances", data=json.dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step}), headers=headers, timeout=5).json()
-                    if doc == []: raise
+                    doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
+                        "sort": "+caughtAt",
+                        "host": None,
+                        "suspended": True,
+                        "limit": step
+                    }))
                 else:
-                    doc = reqto.post(f"https://{domain}/api/federation/instances", data=json.dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step,"offset":counter-1}), headers=headers, timeout=5).json()
-                    if doc == []: raise
+                    doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
+                        "sort": "+caughtAt",
+                        "host": None,
+                        "suspended": True,
+                        "limit": step,
+                        "offset": counter-1
+                    }))
+
                 for instance in doc:
                     # just in case
                     if instance["isSuspended"]:
@@ -272,30 +320,41 @@ def get_misskey_blocks(domain: str) -> dict:
             # same shit, different asshole ("blocked" aka full suspend)
             try:
                 if counter == 0:
-                    doc = reqto.post(f"https://{domain}/api/federation/instances", data=json.dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step}), headers=headers, timeout=5).json()
-                    if doc == []: raise
+                    doc = post_json_api(domain,"/api/federation/instances", json.dumps({
+                        "sort": "+caughtAt",
+                        "host": None,
+                        "blocked": True,
+                        "limit": step
+                    }))
                 else:
-                    doc = reqto.post(f"https://{domain}/api/federation/instances", data=json.dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step,"offset":counter-1}), headers=headers, timeout=5).json()
-                    if doc == []: raise
+                    doc = post_json_api(domain,"/api/federation/instances", json.dumps({
+                        "sort": "+caughtAt",
+                        "host": None,
+                        "blocked": True,
+                        "limit": step,
+                        "offset": counter-1
+                    }))
+
                 for instance in doc:
                     if instance["isBlocked"]:
-                        blocks["blocked"].append(
-                            {
+                        blocks["blocked"].append({
                                 "domain": instance["host"],
                                 "reason": ""
-                            }
-                        )
+                        })
                 counter = counter + step
+
             except:
                 counter = 0
                 break
 
+        # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
         return {
             "reject": blocks["blocked"],
             "followers_only": blocks["suspended"]
         }
 
     except:
+        print("WARNING: API request failed for domain:", domain)
         return {}
 
 def tidyup(domain: str) -> str:
index b15952fce558dea9ca785f3b275e6a7c5562751b..efdc6e9fafce3dcbad633254505696ea7aac4d74 100644 (file)
@@ -1,6 +1,7 @@
 <!DOCTYPE html>
 <head>
     <title>fedi-block-api{% if domain %} {{domain}}{% endif %}</title>
+    <link rel="alternate" type="application/rss+xml" title="RSS Feed for {{base_url}}" href="{base_url}/rss" />
     <style>
         body {
             background-color: #000022;
@@ -93,9 +94,9 @@
                     <tr>
                         <td>{{loop.index}}</td>
                         <td>
-                            <img src="https://proxy.duckduckgo.com/ip3/{{entry['domain']}}.ico" width=16/>
+                            <img src="https://proxy.duckduckgo.com/ip3/{{entry['domain']}}.ico" width="16" />
                             <b><a href="../?{% if blockers %}reverse{% elif blocked %}domain{% endif %}={{entry['domain']}}" rel="nofollow noopener noreferrer">{{entry['domain']}}</a></b>&nbsp;
-                            <a class="listlink" href="https://{{entry['domain']}}">↗</a>
+                            <a class="listlink" href="https://{{entry['domain']}}" rel="external" target="_blank">↗</a>
                         </td>
                         <td>{{entry['highscore']}}</td>
                     </tr>
                     {% for block in blocks[block_level] %}
                         <tr>
                             <td>
-                                <img src="https://proxy.duckduckgo.com/ip3/{{block['blocker']}}.ico" width=16/>
                                 <b><a href="https://{{block['blocker']}}" rel="nofollow noopener noreferrer">{{block['blocker']}}</a></b>
                                 {% if reason or domain %}<a class="listlink" href="./?reverse={{block['blocker']}}">↘</a>{% endif %}
                             </td>
                             <td>
-                                <img src="https://proxy.duckduckgo.com/ip3/{{domain or block['blocked']}}.ico" width=16/>
                                 <b><a href="https://{{domain or block['blocked']}}" rel="nofollow noopener noreferrer">{{block['blocked']}}</a></b>
                                 {% if reason or reverse %}<a class="listlink" href="./?domain={{domain or block['blocked']}}">↘</a>{% endif %}
                             </td>
     {% else %}
         <h1>Enter a Domain</h1>
         <form>
-            <input type="text" name="domain" placeholder="example.com" />
+            <input type="text" name="domain" placeholder="example.com" required="required" />
             <input type="submit" value="Submit" />
         </form>
         <h1>Enter a Reason</h1>
         <form>
-            <input type="text" name="reason" placeholder="free speech" />
+            <input type="text" name="reason" placeholder="free speech" required="required" />
             <input type="submit" value="Submit" />
         </form>
         <h1>Reverse search</h1>
         <form>
-            <input type="text" name="reverse" placeholder="example.com" />
+            <input type="text" name="reverse" placeholder="example.com" required="required" />
             <input type="submit" value="Submit" />
         </form>
         <p>