]> git.mxchange.org Git - fba.git/blobdiff - fba/fba.py
Fixed some issues found by pylint:
[fba.git] / fba / fba.py
index 122b2f6395186ab648fe40d7c5dfe69e799b2c95..49b1044a091e2a76c78e57fec3b1f22c94f42bd8 100644 (file)
@@ -82,26 +82,26 @@ patterns = [
 
 def is_primitive(var: any) -> bool:
     # DEBUG: print(f"DEBUG: var[]='{type(var)}' - CALLED!")
-    return type(var) in {int, str, float, bool} or var == None
+    return type(var) in {int, str, float, bool} or var is None
 
 def fetch_instances(domain: str, origin: str, software: str, script: str, path: str = None):
     # DEBUG: print(f"DEBUG: domain='{domain}',origin='{origin}',software='{software}',path='{path}' - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
-    elif type(origin) != str and origin != None:
+        raise ValueError("Parameter 'domain' is empty")
+    elif not isinstance(origin, str) and origin is not None:
         raise ValueError(f"Parameter origin[]={type(origin)} is not 'str'")
-    elif software == None:
+    elif software is None:
         print(f"DEBUG: software for domain='{domain}' is not set, determining ...")
         software = determine_software(domain, path)
         print(f"DEBUG: Determined software='{software}' for domain='{domain}'")
-    elif type(software) != str:
+    elif not isinstance(software, str):
         raise ValueError(f"Parameter software[]={type(software)} is not 'str'")
-    elif type(script) != str:
+    elif not isinstance(script, str):
         raise ValueError(f"Parameter script[]={type(script)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'domain' is empty")
 
     if not instances.is_registered(domain):
         # DEBUG: print("DEBUG: Adding new domain:", domain, origin)
@@ -119,7 +119,7 @@ def fetch_instances(domain: str, origin: str, software: str, script: str, path:
 
     print(f"INFO: Checking {len(peerlist)} instances from {domain} ...")
     for instance in peerlist:
-        if instance == None:
+        if instance is None:
             # Skip "None" types as tidup() cannot parse them
             continue
 
@@ -142,8 +142,8 @@ def fetch_instances(domain: str, origin: str, software: str, script: str, path:
             if not instances.is_registered(instance):
                 # DEBUG: print("DEBUG: Adding new instance:", instance, domain)
                 instances.add(instance, domain, script)
-        except BaseException as e:
-            print(f"ERROR: instance='{instance}',exception[{type(e)}]:'{str(e)}'")
+        except BaseException as exception:
+            print(f"ERROR: instance='{instance}',exception[{type(exception)}]:'{str(exception)}'")
             continue
 
     # DEBUG: print("DEBUG: EXIT!")
@@ -153,7 +153,7 @@ def add_peers(rows: dict) -> list:
     peers = list()
     for key in ["linked", "allowed", "blocked"]:
         # DEBUG: print(f"DEBUG: Checking key='{key}'")
-        if key in rows and rows[key] != None:
+        if key in rows and rows[key] is not None:
             # DEBUG: print(f"DEBUG: Adding {len(rows[key])} peer(s) to peers list ...")
             for peer in rows[key]:
                 # DEBUG: print(f"DEBUG: peer='{peer}' - BEFORE!")
@@ -196,7 +196,6 @@ def remove_version(software: str) -> str:
         # DEBUG: print(f"DEBUG: Was not able to find common seperator, returning untouched software='{software}'")
         return software
 
-    matches = None
     match = None
     # DEBUG: print(f"DEBUG: Checking {len(patterns)} patterns ...")
     for pattern in patterns:
@@ -204,11 +203,12 @@ def remove_version(software: str) -> str:
         match = pattern.match(version)
 
         # DEBUG: print(f"DEBUG: match[]={type(match)}")
-        if type(match) is re.Match:
+        if isinstance(match, re.Match):
+            # DEBUG: print(f"DEBUG: version='{version}' is matching pattern='{pattern}'")
             break
 
     # DEBUG: print(f"DEBUG: version[{type(version)}]='{version}',match='{match}'")
-    if type(match) is not re.Match:
+    if not isinstance(match, re.Match):
         print(f"WARNING: version='{version}' does not match regex, leaving software='{software}' untouched.")
         return software
 
@@ -226,11 +226,12 @@ def remove_version(software: str) -> str:
 
 def strip_powered_by(software: str) -> str:
     # DEBUG: print(f"DEBUG: software='{software}' - CALLED!")
-    if software == "":
-        print(f"ERROR: Bad method call, 'software' is empty")
-        raise Exception("Parameter 'software' is empty")
+    if not isinstance(software, str):
+        raise ValueError(f"Parameter software[]='{type(software)}' is not 'str'")
+    elif software == "":
+        raise ValueError("Parameter 'software' is empty")
     elif not "powered by" in software:
-        print(f"WARNING: Cannot find 'powered by' in '{software}'!")
+        print(f"WARNING: Cannot find 'powered by' in software='{software}'!")
         return software
 
     start = software.find("powered by ")
@@ -246,9 +247,10 @@ def strip_powered_by(software: str) -> str:
 
 def strip_hosted_on(software: str) -> str:
     # DEBUG: print(f"DEBUG: software='{software}' - CALLED!")
-    if software == "":
-        print(f"ERROR: Bad method call, 'software' is empty")
-        raise Exception("Parameter 'software' is empty")
+    if not isinstance(software, str):
+        raise ValueError(f"Parameter software[]='{type(software)}' is not 'str'")
+    elif software == "":
+        raise ValueError("Parameter 'software' is empty")
     elif not "hosted on" in software:
         print(f"WARNING: Cannot find 'hosted on' in '{software}'!")
         return software
@@ -256,7 +258,7 @@ def strip_hosted_on(software: str) -> str:
     end = software.find("hosted on ")
     # DEBUG: print(f"DEBUG: end[{type(end)}]='{end}'")
 
-    software = software[0, start].strip()
+    software = software[0, end].strip()
     # DEBUG: print(f"DEBUG: software='{software}'")
 
     software = strip_until(software, " - ")
@@ -266,12 +268,14 @@ def strip_hosted_on(software: str) -> str:
 
 def strip_until(software: str, until: str) -> str:
     # DEBUG: print(f"DEBUG: software='{software}',until='{until}' - CALLED!")
-    if software == "":
-        print(f"ERROR: Bad method call, 'software' is empty")
-        raise Exception("Parameter 'software' is empty")
+    if not isinstance(software, str):
+        raise ValueError(f"Parameter software[]='{type(software)}' is not 'str'")
+    elif software == "":
+        raise ValueError("Parameter 'software' is empty")
+    elif not isinstance(until, str):
+        raise ValueError(f"Parameter until[]='{type(until)}' is not 'str'")
     elif until == "":
-        print(f"ERROR: Bad method call, 'until' is empty")
-        raise Exception("Parameter 'until' is empty")
+        raise ValueError("Parameter 'until' is empty")
     elif not until in software:
         print(f"WARNING: Cannot find '{until}' in '{software}'!")
         return software
@@ -287,10 +291,10 @@ def strip_until(software: str, until: str) -> str:
     return software
 
 def remove_pending_error(domain: str):
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'domain' is empty")
 
     try:
         # Prevent updating any pending errors, nodeinfo was found
@@ -302,19 +306,19 @@ def remove_pending_error(domain: str):
     # DEBUG: print("DEBUG: EXIT!")
 
 def get_hash(domain: str) -> str:
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'domain' is empty")
 
     return hashlib.sha256(domain.encode("utf-8")).hexdigest()
 
 def log_error(domain: str, response: requests.models.Response):
     # DEBUG: print("DEBUG: domain,response[]:", domain, type(response))
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'domain' is empty")
 
     try:
         # DEBUG: print("DEBUG: BEFORE response[]:", type(response))
@@ -322,7 +326,7 @@ def log_error(domain: str, response: requests.models.Response):
             response = str(response)
 
         # DEBUG: print("DEBUG: AFTER response[]:", type(response))
-        if type(response) is str:
+        if isinstance(response, str):
             cursor.execute("INSERT INTO error_log (domain, error_code, error_message, created) VALUES (?, 999, ?, ?)",[
                 domain,
                 response,
@@ -339,19 +343,19 @@ def log_error(domain: str, response: requests.models.Response):
         # Cleanup old entries
         # DEBUG: print(f"DEBUG: Purging old records (distance: {config.get('error_log_cleanup')})")
         cursor.execute("DELETE FROM error_log WHERE created < ?", [time.time() - config.get("error_log_cleanup")])
-    except BaseException as e:
-        print(f"ERROR: failed SQL query: domain='{domain}',exception[{type(e)}]:'{str(e)}'")
+    except BaseException as exception:
+        print(f"ERROR: failed SQL query: domain='{domain}',exception[{type(exception)}]:'{str(exception)}'")
         sys.exit(255)
 
     # DEBUG: print("DEBUG: EXIT!")
 
 def fetch_peers(domain: str, software: str) -> list:
     # DEBUG: print(f"DEBUG: domain({len(domain)})={domain},software={software} - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
-    elif type(software) != str and software != None:
+        raise ValueError("Parameter 'domain' is empty")
+    elif not isinstance(software, str) and software is not None:
         raise ValueError(f"software[]={type(software)} is not 'str'")
 
     if software == "misskey":
@@ -395,9 +399,9 @@ def fetch_peers(domain: str, software: str) -> list:
             # DEBUG: print("DEBUG: Querying API was successful:", domain, len(data))
             peers = data
 
-    except BaseException as e:
-        print("WARNING: Some error during get():", domain, e)
-        instances.update_last_error(domain, e)
+    except BaseException as exception:
+        print("WARNING: Some error during get():", domain, exception)
+        instances.update_last_error(domain, exception)
 
     # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
     instances.set("total_peers", domain, len(peers))
@@ -410,11 +414,11 @@ def fetch_peers(domain: str, software: str) -> list:
 
 def fetch_nodeinfo(domain: str, path: str = None) -> list:
     # DEBUG: print(f"DEBUG: domain='{domain}',path={path} - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
-    elif type(path) != str and path != None:
+        raise ValueError("Parameter 'domain' is empty")
+    elif not isinstance(path, str) and path is not None:
         raise ValueError(f"Parameter path[]={type(path)} is not 'str'")
 
     # DEBUG: print(f"DEBUG: Fetching nodeinfo from domain='{domain}' ...")
@@ -436,7 +440,7 @@ def fetch_nodeinfo(domain: str, path: str = None) -> list:
 
     data = {}
     for request in request_paths:
-        if path != None and path != "" and path != f"https://{domain}{path}":
+        if path is not None and path != "" and path != f"https://{domain}{path}":
             # DEBUG: print(f"DEBUG: path='{path}' does not match request='{request}' - SKIPPED!")
             continue
 
@@ -459,9 +463,9 @@ def fetch_nodeinfo(domain: str, path: str = None) -> list:
                 instances.update_last_error(domain, response)
                 continue
 
-        except BaseException as e:
+        except BaseException as exception:
             # DEBUG: print("DEBUG: Cannot fetch API request:", request)
-            instances.update_last_error(domain, e)
+            instances.update_last_error(domain, exception)
             pass
 
     # DEBUG: print(f"DEBUG: data()={len(data)} - EXIT!")
@@ -469,10 +473,10 @@ def fetch_nodeinfo(domain: str, path: str = None) -> list:
 
 def fetch_wellknown_nodeinfo(domain: str) -> list:
     # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'domain' is empty")
 
     # DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
     data = {}
@@ -505,9 +509,9 @@ def fetch_wellknown_nodeinfo(domain: str) -> list:
             else:
                 print("WARNING: nodeinfo does not contain 'links':", domain)
 
-    except BaseException as e:
+    except BaseException as exception:
         print("WARNING: Failed fetching .well-known info:", domain)
-        instances.update_last_error(domain, e)
+        instances.update_last_error(domain, exception)
         pass
 
     # DEBUG: print("DEBUG: Returning data[]:", type(data))
@@ -515,14 +519,14 @@ def fetch_wellknown_nodeinfo(domain: str) -> list:
 
 def fetch_generator_from_path(domain: str, path: str = "/") -> str:
     # DEBUG: print(f"DEBUG: domain({len(domain)})={domain},path={path} - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
-    elif type(path) != str:
+        raise ValueError("Parameter 'domain' is empty")
+    elif not isinstance(path, str):
         raise ValueError(f"path[]={type(path)} is not 'str'")
     elif path == "":
-        raise ValueError(f"Parameter 'domain' is empty")
+        raise ValueError("Parameter 'path' is empty")
 
     # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}' - CALLED!")
     software = None
@@ -554,30 +558,30 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
                 instances.set("detection_mode", domain, "SITE_NAME")
                 remove_pending_error(domain)
 
-    except BaseException as e:
-        # DEBUG: print(f"DEBUG: Cannot fetch / from '{domain}':", e)
-        instances.update_last_error(domain, e)
+    except BaseException as exception:
+        # DEBUG: print(f"DEBUG: Cannot fetch / from '{domain}':", exception)
+        instances.update_last_error(domain, exception)
         pass
 
     # DEBUG: print(f"DEBUG: software[]={type(software)}")
-    if type(software) is str and software == "":
+    if isinstance(software, str) and software == "":
         # DEBUG: print(f"DEBUG: Corrected empty string to None for software of domain='{domain}'")
         software = None
-    elif type(software) is str and ("." in software or " " in software):
+    elif isinstance(software, str) and ("." in software or " " in software):
         # DEBUG: print(f"DEBUG: software='{software}' may contain a version number, domain='{domain}', removing it ...")
         software = remove_version(software)
 
     # DEBUG: print(f"DEBUG: software[]={type(software)}")
-    if type(software) is str and " powered by " in software:
+    if isinstance(software, str) and " powered by " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
         software = remove_version(strip_powered_by(software))
-    elif type(software) is str and " hosted on " in software:
+    elif isinstance(software, str) and " hosted on " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has 'hosted on' in it")
         software = remove_version(strip_hosted_on(software))
-    elif type(software) is str and " by " in software:
+    elif isinstance(software, str) and " by " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has ' by ' in it")
         software = strip_until(software, " by ")
-    elif type(software) is str and " see " in software:
+    elif isinstance(software, str) and " see " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has ' see ' in it")
         software = strip_until(software, " see ")
 
@@ -586,11 +590,11 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
 
 def determine_software(domain: str, path: str = None) -> str:
     # DEBUG: print(f"DEBUG: domain({len(domain)})={domain},path={path} - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
     elif domain == "":
-        raise ValueError(f"Parameter 'domain' is empty")
-    elif type(path) != str and path != None:
+        raise ValueError("Parameter 'domain' is empty")
+    elif not isinstance(path, str) and path is not None:
         raise ValueError(f"Parameter path[]={type(path)} is not 'str'")
 
     # DEBUG: print("DEBUG: Determining software for domain,path:", domain, path)
@@ -641,10 +645,10 @@ def determine_software(domain: str, path: str = None) -> str:
     elif "powered by" in software:
         # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
         software = strip_powered_by(software)
-    elif type(software) is str and " by " in software:
+    elif isinstance(software, str) and " by " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has ' by ' in it")
         software = strip_until(software, " by ")
-    elif type(software) is str and " see " in software:
+    elif isinstance(software, str) and " see " in software:
         # DEBUG: print(f"DEBUG: software='{software}' has ' see ' in it")
         software = strip_until(software, " see ")
 
@@ -662,7 +666,7 @@ def determine_software(domain: str, path: str = None) -> str:
         software = remove_version(software)
 
     # DEBUG: print(f"DEBUG: software[]={type(software)}")
-    if type(software) is str and "powered by" in software:
+    if isinstance(software, str) and "powered by" in software:
         # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
         software = remove_version(strip_powered_by(software))
 
@@ -671,7 +675,7 @@ def determine_software(domain: str, path: str = None) -> str:
 
 def tidyup_reason(reason: str) -> str:
     # DEBUG: print(f"DEBUG: reason='{reason}' - CALLED!")
-    if type(reason) != str:
+    if not isinstance(reason, str):
         raise ValueError(f"Parameter reason[]={type(reason)} is not 'str'")
 
     # Strip string
@@ -685,7 +689,7 @@ def tidyup_reason(reason: str) -> str:
 
 def tidyup_domain(domain: str) -> str:
     # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
-    if type(domain) != str:
+    if not isinstance(domain, str):
         raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
 
     # All lower-case and strip spaces out + last dot
@@ -729,24 +733,24 @@ def json_from_response(response: requests.models.Response) -> list:
     # DEBUG: print(f"DEBUG: data[]={type(data)} - EXIT!")
     return data
 
-def has_key(keys: list, search: str, value: any) -> bool:
-    # DEBUG: print(f"DEBUG: keys()={len(keys)},search='{search}',value[]='{type(value)}' - CALLED!")
-    if type(keys) != list:
-        raise ValueError(f"Parameter keys[]='{type(keys)}' is not 'list'")
-    elif type(search) != str:
-        raise ValueError(f"Parameter search[]='{type(search)}' is not 'str'")
-    elif search == "":
-        raise ValueError("Parameter 'search' is empty")
+def has_key(lists: list, key: str, value: any) -> bool:
+    # DEBUG: print(f"DEBUG: lists()={len(lists)},key='{key}',value[]='{type(value)}' - CALLED!")
+    if not isinstance(lists, list):
+        raise ValueError(f"Parameter lists[]='{type(lists)}' is not 'list'")
+    elif not isinstance(key, str):
+        raise ValueError(f"Parameter key[]='{type(key)}' is not 'str'")
+    elif key == "":
+        raise ValueError("Parameter 'key' is empty")
 
     has = False
-    # DEBUG: print(f"DEBUG: Checking keys()={len(keys)} ...")
-    for key in keys:
-        # DEBUG: print(f"DEBUG: key['{type(key)}']={key}")
-        if type(key) != dict:
-            raise ValueError(f"key[]='{type(key)}' is not 'dict'")
-        elif not search in key:
-            raise KeyError(f"Cannot find search='{search}'")
-        elif key[search] == value:
+    # DEBUG: print(f"DEBUG: Checking lists()={len(lists)} ...")
+    for row in lists:
+        # DEBUG: print(f"DEBUG: row['{type(row)}']={row}")
+        if not isinstance(row, dict):
+            raise ValueError(f"row[]='{type(row)}' is not 'dict'")
+        elif not key in row:
+            raise KeyError(f"Cannot find key='{key}'")
+        elif row[key] == value:
             has = True
             break
 
@@ -807,10 +811,14 @@ def find_domains(tag: bs4.element.Tag) -> list:
 
 def fetch_url(url: str, headers: dict, timeout: list) -> requests.models.Response:
     # DEBUG: print(f"DEBUG: url='{url}',headers()={len(headers)},timeout={timeout} - CALLED!")
-    if type(url) != str:
+    if not isinstance(url, str):
         raise ValueError(f"Parameter url[]='{type(url)}' is not 'str'")
     elif url == "":
         raise ValueError("Parameter 'url' is empty")
+    elif not isinstance(headers, dict):
+        raise ValueError(f"Parameter headers[]='{type(headers)}' is not 'dict'")
+    elif not isinstance(timeout, list):
+        raise ValueError(f"Parameter timeout[]='{type(timeout)}' is not 'list'")
 
     # DEBUG: print(f"DEBUG: Parsing url='{url}'")
     components = urlparse(url)