]> git.mxchange.org Git - fba.git/blobdiff - fba/networks/misskey.py
Notation applied:
[fba.git] / fba / networks / misskey.py
index bf5892488cc53d3534f886e477bb32afe5bc2954..e47c7dd9d04548c5d63171fec5dfb7665a83e69a 100644 (file)
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 
 import json
+import logging
 
-from fba import blacklist
-from fba import config
 from fba import csrf
-from fba import network
+from fba import utils
 
-from fba.helpers import dicts
+from fba.helpers import config
+from fba.helpers import domain as domain_helper
 from fba.helpers import tidyup
 
+from fba.http import network
+
 from fba.models import instances
 
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
 def fetch_peers(domain: str) -> list:
-    # DEBUG: print(f"DEBUG: domain({len(domain)})={domain} - CALLED!")
-    if not isinstance(domain, str):
-        raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
-    elif domain == "":
-        raise ValueError("Parameter 'domain' is empty")
-
-    # DEBUG: print(f"DEBUG: domain='{domain}' is misskey, sending API POST request ...")
-    peers   = list()
-    offset  = 0
-    step    = config.get("misskey_limit")
+    logger.debug("domain='%s' - CALLED!", domain)
+    domain_helper.raise_on(domain)
+
+    logger.debug("domain='%s' is misskey, sending API POST request ...", domain)
+    peers  = list()
+    offset = 0
+    step   = config.get("misskey_limit")
 
     # No CSRF by default, you don't have to add network.api_headers by yourself here
     headers = tuple()
 
     try:
-        # DEBUG: print(f"DEBUG: Checking CSRF for domain='{domain}'")
+        logger.debug("Checking CSRF for domain='%s'", domain)
         headers = csrf.determine(domain, dict())
     except network.exceptions as exception:
-        print(f"WARNING: Exception '{type(exception)}' during checking CSRF (fetch_peers,{__name__}) - EXIT!")
+        logger.warning("Exception '%s' during checking CSRF (fetch_peers,%s) - EXIT!", type(exception), __name__)
         instances.set_last_error(domain, exception)
-        return peers
+        return list()
 
     # iterating through all "suspended" (follow-only in its terminology)
     # instances page-by-page, since that troonware doesn't support
     # sending them all at once
     while True:
-        # DEBUG: print(f"DEBUG: Fetching offset='{offset}' from '{domain}' ...")
+        logger.debug("Fetching offset=%d from domain='%s' ...", offset, domain)
         if offset == 0:
             fetched = network.post_json_api(domain, "/api/federation/instances", json.dumps({
                 "sort" : "+pubAt",
@@ -69,72 +71,63 @@ def fetch_peers(domain: str) -> list:
             }), headers)
 
         # Check records
-        # DEBUG: print(f"DEBUG: fetched[]='{type(fetched)}'")
+        logger.debug("fetched[]='%s'", type(fetched))
         if "error_message" in fetched:
-            print(f"WARNING: post_json_api() for domain='{domain}' returned error message: {fetched['error_message']}")
+            logger.warning("post_json_api() for domain='%s' returned error message: '%s'", domain, fetched['error_message'])
             instances.set_last_error(domain, fetched)
             break
         elif isinstance(fetched["json"], dict) and "error" in fetched["json"] and "message" in fetched["json"]["error"]:
-            print(f"WARNING: post_json_api() returned error: {fetched['error']['message']}")
+            logger.warning("post_json_api() returned error: '%s'", fetched['error']['message'])
             instances.set_last_error(domain, fetched["json"]["error"]["message"])
             break
 
         rows = fetched["json"]
 
-        # DEBUG: print(f"DEBUG: rows()={len(rows)}")
+        logger.debug("rows(%d)[]='%s'", len(rows), type(rows))
         if len(rows) == 0:
-            # DEBUG: print(f"DEBUG: Returned zero bytes, exiting loop, domain='{domain}'")
+            logger.debug("Returned zero bytes, domain='%s' - BREAK!", domain)
             break
         elif len(rows) != config.get("misskey_limit"):
-            # DEBUG: print(f"DEBUG: Fetched '{len(rows)}' row(s) but expected: '{config.get('misskey_limit')}'")
+            logger.debug("Fetched %d row(s) but expected: %d", len(rows), config.get('misskey_limit'))
             offset = offset + (config.get("misskey_limit") - len(rows))
         else:
-            # DEBUG: print(f"DEBUG: Raising offset by step={step}")
+            logger.debug("Raising offset by step=%d", step)
             offset = offset + step
 
         already = 0
-        # DEBUG: print(f"DEBUG: rows({len(rows)})[]='{type(rows)}'")
+        logger.debug("rows(%d))[]='%s'", len(rows), type(rows))
         for row in rows:
-            # DEBUG: print(f"DEBUG: row()={len(row)}")
-            if not "host" in row:
-                print(f"WARNING: row()={len(row)} does not contain key 'host': {row},domain='{domain}'")
+            logger.debug("row()=%d", len(row))
+            if "host" not in row:
+                logger.warning("row()=%d does not contain key 'host': row='%s',domain='%s' - SKIPPED!", len(row), row, domain)
                 continue
             elif not isinstance(row["host"], str):
-                print(f"WARNING: row[host][]='{type(row['host'])}' is not 'str'")
+                logger.warning("row[host][]='%s' is not 'str' - SKIPPED!", type(row['host']))
                 continue
-            elif blacklist.is_blacklisted(row["host"]):
-                # DEBUG: print(f"DEBUG: row[host]='{row['host']}' is blacklisted. domain='{domain}'")
+            elif not utils.is_domain_wanted(row["host"]):
+                logger.debug("row[host]='%s' is not wanted, domain='%s' - SKIPPED!", row['host'], domain)
                 continue
             elif row["host"] in peers:
-                # DEBUG: print(f"DEBUG: Not adding row[host]='{row['host']}', already found.")
+                logger.debug("Not adding row[host]='%s', already found - SKIPPED!", row['host'])
                 already = already + 1
                 continue
 
-            # DEBUG: print(f"DEBUG: Adding peer: '{row['host']}'")
+            logger.debug("Adding peer: row[host]='%s'", row['host'])
             peers.append(row["host"])
 
         if already == len(rows):
-            # DEBUG: print(f"DEBUG: Host returned same set of '{already}' instances, aborting loop!")
+            logger.debug("Host returned same set of %d instance(s) - BREAK!", already)
             break
 
-    # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
-    instances.set_total_peers(domain, peers)
-
-    # DEBUG: print(f"DEBUG: Returning peers[]='{type(peers)}'")
+    logger.debug("peers()=%d - EXIT!", len(peers))
     return peers
 
-def fetch_blocks(domain: str) -> dict:
-    # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
-    if not isinstance(domain, str):
-        raise ValueError(f"Parameter domain[]='{type(domain)}' is not 'str'")
-    elif domain == "":
-        raise ValueError("Parameter 'domain' is empty")
+def fetch_blocks(domain: str) -> list:
+    logger.debug("domain='%s' - CALLED!", domain)
+    domain_helper.raise_on(domain)
 
-    # DEBUG: print(f"DEBUG: Fetching misskey blocks from domain={domain}")
-    blocklist = {
-        "suspended": [],
-        "blocked"  : []
-    }
+    logger.debug("Fetching misskey blocks from domain='%s'", domain)
+    blocklist = list()
 
     offset  = 0
     step    = config.get("misskey_limit")
@@ -143,10 +136,10 @@ def fetch_blocks(domain: str) -> dict:
     headers = tuple()
 
     try:
-        # DEBUG: print(f"DEBUG: Checking CSRF for domain='{domain}'")
+        logger.debug("Checking CSRF for domain='%s'", domain)
         headers = csrf.determine(domain, dict())
     except network.exceptions as exception:
-        print(f"WARNING: Exception '{type(exception)}' during checking CSRF (fetch_blocks,{__name__}) - EXIT!")
+        logger.warning("Exception '%s' during checking CSRF (fetch_blocks,%s) - EXIT!", type(exception), __name__)
         instances.set_last_error(domain, exception)
         return blocklist
 
@@ -154,9 +147,9 @@ def fetch_blocks(domain: str) -> dict:
     # instances page-by-page since it doesn't support sending them all at once
     while True:
         try:
-            # DEBUG: print(f"DEBUG: Fetching offset='{offset}' from '{domain}' ...")
+            logger.debug("Fetching offset=%d from domain='%s' ...", offset, domain)
             if offset == 0:
-                # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
+                logger.debug("Sending JSON API request to domain='%s',step=%d,offset=%d", domain, step, offset)
                 fetched = network.post_json_api(domain, "/api/federation/instances", json.dumps({
                     "sort"     : "+pubAt",
                     "host"     : None,
@@ -164,7 +157,7 @@ def fetch_blocks(domain: str) -> dict:
                     "limit"    : step
                 }), headers)
             else:
-                # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
+                logger.debug("Sending JSON API request to domain='%s',step=%d,offset=%d", domain, step, offset)
                 fetched = network.post_json_api(domain, "/api/federation/instances", json.dumps({
                     "sort"     : "+pubAt",
                     "host"     : None,
@@ -173,48 +166,49 @@ def fetch_blocks(domain: str) -> dict:
                     "offset"   : offset - 1
                 }), headers)
 
-            # DEBUG: print(f"DEBUG: fetched[]='{type(fetched)}'")
+            logger.debug("fetched[]='%s'", type(fetched))
             if "error_message" in fetched:
-                print(f"WARNING: post_json_api() for domain='{domain}' returned error message: {fetched['error_message']}")
+                logger.warning("post_json_api() for domain='%s' returned error message: '%s'", domain, fetched['error_message'])
                 instances.set_last_error(domain, fetched)
                 break
             elif isinstance(fetched["json"], dict) and "error" in fetched["json"] and "message" in fetched["json"]["error"]:
-                print(f"WARNING: post_json_api() returned error: {fetched['error']['message']}")
+                logger.warning("post_json_api() returned error: '%s'", fetched['error']['message'])
                 instances.set_last_error(domain, fetched["json"]["error"]["message"])
                 break
 
             rows = fetched["json"]
 
-            # DEBUG: print(f"DEBUG: rows({len(rows)})={rows} - suspend")
+            logger.debug("rows(%d)[]='%s'", len(rows), type(rows))
             if len(rows) == 0:
-                # DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
+                logger.debug("Returned zero bytes, domain='%s' - BREAK!", domain)
                 break
             elif len(rows) != config.get("misskey_limit"):
-                # DEBUG: print(f"DEBUG: Fetched '{len(rows)}' row(s) but expected: '{config.get('misskey_limit')}'")
+                logger.debug("Fetched %d row(s) but expected: %d", len(rows), config.get('misskey_limit'))
                 offset = offset + (config.get("misskey_limit") - len(rows))
             else:
-                # DEBUG: print("DEBUG: Raising offset by step:", step)
+                logger.debug("Raising offset by step=%d", step)
                 offset = offset + step
 
             count = 0
             for instance in rows:
                 # Is it there?
-                # DEBUG: print(f"DEBUG: instance[{type(instance)}]='{instance}' - suspend")
-                if "isSuspended" in instance and instance["isSuspended"] and not dicts.has_key(blocklist["suspended"], "domain", instance["host"]):
+                logger.debug("instance[%s]='%s'", type(instance), instance)
+                if "isSuspended" in instance and instance["isSuspended"]:
                     count = count + 1
-                    blocklist["suspended"].append({
-                        "domain": tidyup.domain(instance["host"]),
-                        # no reason field, nothing
-                        "reason": None
+                    blocklist.append({
+                        "blocker"    : domain,
+                        "blocked"    : tidyup.domain(instance["host"]),
+                        "reason"     : None,
+                        "block_level": "suspended",
                     })
 
-            # DEBUG: print(f"DEBUG: count={count}")
+            logger.debug("count=%d", count)
             if count == 0:
-                # DEBUG: print("DEBUG: API is no more returning new instances, aborting loop!")
+                logger.debug("API is no more returning new instances, aborting loop! domain='%s'", domain)
                 break
 
         except network.exceptions as exception:
-            print(f"WARNING: Caught error, exiting loop: domain='{domain}',exception[{type(exception)}]='{str(exception)}'")
+            logger.warning("Caught error, exiting loop: domain='%s',exception[%s]='%s'", domain, type(exception), str(exception))
             instances.set_last_error(domain, exception)
             offset = 0
             break
@@ -223,7 +217,7 @@ def fetch_blocks(domain: str) -> dict:
         # Fetch blocked (full suspended) instances
         try:
             if offset == 0:
-                # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
+                logger.debug("Sending JSON API request to domain='%s',step=%d,offset=%d", domain, step, offset)
                 fetched = network.post_json_api(domain, "/api/federation/instances", json.dumps({
                     "sort"   : "+pubAt",
                     "host"   : None,
@@ -231,7 +225,7 @@ def fetch_blocks(domain: str) -> dict:
                     "limit"  : step
                 }), headers)
             else:
-                # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
+                logger.debug("Sending JSON API request to domain='%s',step=%d,offset=%d", domain, step, offset)
                 fetched = network.post_json_api(domain, "/api/federation/instances", json.dumps({
                     "sort"   : "+pubAt",
                     "host"   : None,
@@ -240,53 +234,54 @@ def fetch_blocks(domain: str) -> dict:
                     "offset" : offset - 1
                 }), headers)
 
-            # DEBUG: print(f"DEBUG: fetched[]='{type(fetched)}'")
+            logger.debug("fetched[]='%s'", type(fetched))
             if "error_message" in fetched:
-                print(f"WARNING: post_json_api() for domain='{domain}' returned error message: {fetched['error_message']}")
+                logger.warning("post_json_api() for domain='%s' returned error message: '%s'", domain, fetched['error_message'])
                 instances.set_last_error(domain, fetched)
                 break
             elif isinstance(fetched["json"], dict) and "error" in fetched["json"] and "message" in fetched["json"]["error"]:
-                print(f"WARNING: post_json_api() returned error: {fetched['error']['message']}")
+                logger.warning("post_json_api() returned error: '%s'", fetched['error']['message'])
                 instances.set_last_error(domain, fetched["json"]["error"]["message"])
                 break
 
             rows = fetched["json"]
 
-            # DEBUG: print(f"DEBUG: rows({len(rows)})={rows} - blocked")
+            logger.debug("rows(%d)[]='%s'", len(rows), type(rows))
             if len(rows) == 0:
-                # DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
+                logger.debug("Returned zero bytes, domain='%s' - BREAK!", domain)
                 break
             elif len(rows) != config.get("misskey_limit"):
-                # DEBUG: print(f"DEBUG: Fetched '{len(rows)}' row(s) but expected: '{config.get('misskey_limit')}'")
+                logger.debug("Fetched %d row(s) but expected: %d'", len(rows), config.get('misskey_limit'))
                 offset = offset + (config.get("misskey_limit") - len(rows))
             else:
-                # DEBUG: print("DEBUG: Raising offset by step:", step)
+                logger.debug("Raising offset by step=%d", step)
                 offset = offset + step
 
             count = 0
             for instance in rows:
                 # Is it there?
-                # DEBUG: print(f"DEBUG: instance[{type(instance)}]='{instance}' - blocked")
-                if "isBlocked" in instance and instance["isBlocked"] and not dicts.has_key(blocklist["blocked"], "domain", instance["host"]):
+                logger.debug("instance[%s]='%s'", type(instance), instance)
+                if "isBlocked" in instance and instance["isBlocked"]:
                     count = count + 1
-                    blocklist["blocked"].append({
-                        "domain": tidyup.domain(instance["host"]),
-                        "reason": None
+                    blocked = tidyup.domain(instance["host"])
+                    logger.debug("Appending blocker='%s',blocked='%s',block_level='reject'", domain, blocked)
+                    blocklist.append({
+                        "blocker"    : domain,
+                        "blocked"    : blocked,
+                        "reason"     : None,
+                        "block_level": "reject",
                     })
 
-            # DEBUG: print(f"DEBUG: count={count}")
+            logger.debug("count=%d", count)
             if count == 0:
-                # DEBUG: print("DEBUG: API is no more returning new instances, aborting loop!")
+                logger.debug("API is no more returning new instances, aborting loop!")
                 break
 
         except network.exceptions as exception:
-            print(f"WARNING: Caught error, exiting loop: domain='{domain}',exception[{type(exception)}]='{str(exception)}'")
+            logger.warning("Caught error, exiting loop: domain='%s',exception[%s]='%s'", domain, type(exception), str(exception))
             instances.set_last_error(domain, exception)
             offset = 0
             break
 
-    # DEBUG: print(f"DEBUG: Returning for domain='{domain}',blocked()={len(blocklist['blocked'])},suspended()={len(blocklist['suspended'])}")
-    return {
-        "reject"        : blocklist["blocked"],
-        "followers_only": blocklist["suspended"]
-    }
+    logger.debug("blocklist()=%d - EXIT!", len(blocklist))
+    return blocklist