X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=fba%2Fnetworks%2Fmisskey.py;h=045b5061c807fa4547802e26edcef8243e4b31b5;hb=f9d221393d508c052c56cbc8abf04aa411776454;hp=e1e7360433e9ca11cf3922eae4b9d90b6575691c;hpb=65e7ded0da2d597d118450be6730458327c0c7ea;p=fba.git diff --git a/fba/networks/misskey.py b/fba/networks/misskey.py index e1e7360..045b506 100644 --- a/fba/networks/misskey.py +++ b/fba/networks/misskey.py @@ -15,44 +15,48 @@ # along with this program. If not, see . import json +import logging -from fba import blacklist -from fba import config -from fba import csrf -from fba import network - -from fba.helpers import dicts +from fba.helpers import config +from fba.helpers import dicts as dict_helper +from fba.helpers import domain as domain_helper from fba.helpers import tidyup +from fba.http import csrf +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") + logger.debug("domain='%s' - CALLED!", domain) + domain_helper.raise_on(domain) - # 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' 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!") - return peers + logger.warning("Exception '%s' during checking CSRF (fetch_peers,%s)", type(exception), __name__) + instances.set_last_error(domain, exception) + + logger.debug("Returning empty list ... - EXIT!") + 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", @@ -68,93 +72,90 @@ 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']}") - instances.update_last_error(domain, fetched) + 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']}") - instances.update_last_error(domain, fetched["json"]["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',step=%d", len(rows), type(rows), step) 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)}'") + added = 0 + 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'") - continue - elif blacklist.is_blacklisted(row["host"]): - # DEBUG: print(f"DEBUG: row[host]='{row['host']}' is blacklisted. domain='{domain}'") + logger.warning("row[host][]='%s' is not of type 'str' - SKIPPED!", type(row['host'])) continue elif row["host"] in peers: - # DEBUG: print(f"DEBUG: Not adding row[host]='{row['host']}', already found.") - already = already + 1 + logger.debug("Not adding row[host]='%s', already found - SKIPPED!", row['host']) + continue + elif not domain_helper.is_wanted(row["host"]): + logger.debug("row[host]='%s' is not wanted - SKIPPED!", row["host"]) continue - # DEBUG: print(f"DEBUG: Adding peer: '{row['host']}'") + logger.debug("Adding peer: row[host]='%s'", row['host']) + added = added + 1 peers.append(row["host"]) - if already == len(rows): - # DEBUG: print(f"DEBUG: Host returned same set of '{already}' instances, aborting loop!") + logger.debug("added=%d,rows()=%d", added, len(rows)) + if added == 0: + logger.debug("Host returned already added (%d) peers - BREAK!", len(rows)) break - # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'") - instances.set_data("total_peers", domain, len(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") - - # DEBUG: print(f"DEBUG: Fetching misskey blocks from domain={domain}") - blocklist = { - "suspended": [], - "blocked" : [] - } +def fetch_blocks(domain: str) -> list: + logger.debug("domain='%s' - CALLED!", domain) + domain_helper.raise_on(domain) - offset = 0 - step = config.get("misskey_limit") + if not instances.is_registered(domain): + raise Exception(f"domain='{domain}' is not registered but function is invoked.") # 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_blocks,{__name__}) - EXIT!") - return blocklist + logger.warning("Exception '%s' during checking CSRF (fetch_blocks,%s)", type(exception), __name__) + instances.set_last_error(domain, exception) + + logger.debug("Returning empty list ... - EXIT!") + return list() + + blocklist = list() + offset = 0 + step = config.get("misskey_limit") # iterating through all "suspended" (follow-only in its terminology) # instances page-by-page since it doesn't support sending them all at once + logger.debug("Fetching misskey blocks from domain='%s'", domain) 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, @@ -162,7 +163,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, @@ -171,49 +172,68 @@ 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']}") - instances.update_last_error(domain, fetched) + 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']}") - instances.update_last_error(domain, fetched["json"]["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'", type(instance)) + if "host" not in instance: + logger.warning("instance(%d)='%s' has no key 'host' - SKIPPED!", len(instance), instance) + continue + elif instance["host"] is None or instance["host"] == "": + logger.debug("instance[host]='%s' is None or empty - SKIPPED!", instance["host"]) + continue + + logger.debug("instance[host]='%s' - BEFORE!", instance["host"]) + blocked = tidyup.domain(instance["host"]) + + logger.debug("blocked[%s]='%s' - AFTER!", type(blocked), blocked) + if blocked is None or blocked == "": + logger.warning("instance[host]='%s' is None or empty after tidyup.domain() - SKIPPED!", instance["host"]) + continue + elif not domain_helper.is_wanted(blocked): + logger.debug("blocked='%s' is not wanted - SKIPPED!", blocked) + continue + elif "isSuspended" in instance and instance["isSuspended"] and not dict_helper.has_key(blocklist, "blocked", blocked): count = count + 1 - blocklist["suspended"].append({ - "domain": tidyup.domain(instance["host"]), - # no reason field, nothing - "reason": None + logger.debug("Appending blocker='%s',blocked='%s',block_level='suspended'", domain, blocked) + blocklist.append({ + "blocker" : domain, + "blocked" : blocked, + "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)}'") - instances.update_last_error(domain, 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 @@ -221,7 +241,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, @@ -229,7 +249,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, @@ -238,53 +258,62 @@ 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']}") - instances.update_last_error(domain, fetched) + 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']}") - instances.update_last_error(domain, fetched["json"]["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'", type(instance)) + blocked = tidyup.domain(instance["host"]) + + logger.debug("blocked='%s'", blocked) + if blocked is None or blocked == "": + logger.warning("instance[host]='%s' is None or empty after tidyup.domain() - SKIPPED!", instance["host"]) + continue + elif not domain_helper.is_wanted(blocked): + logger.debug("blocked='%s' is not wanted - SKIPPED!", blocked) + continue + elif "isBlocked" in instance and instance["isBlocked"] and not dict_helper.has_key(blocklist, "blocked", blocked): count = count + 1 - blocklist["blocked"].append({ - "domain": tidyup.domain(instance["host"]), - "reason": None + 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)}'") - instances.update_last_error(domain, 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