-def update_last_instance_fetch(domain: str):
- # DEBUG: print(f"DEBUG: domain={domain} - CALLED!")
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
-
- # DEBUG: print("DEBUG: Updating last_instance_fetch for domain:", domain)
- instances.set("last_instance_fetch", domain, time.time())
-
- # Running pending updated
- # DEBUG: print(f"DEBUG: Invoking instances.update_instance_data({domain}) ...")
- instances.update_instance_data(domain)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def update_last_nodeinfo(domain: str):
- # DEBUG: print(f"DEBUG: domain={domain} - CALLED!")
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
-
- # DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
- instances.set("last_nodeinfo", domain, time.time())
- instances.set("last_updated" , domain, time.time())
-
- # Running pending updated
- # DEBUG: print(f"DEBUG: Invoking instances.update_instance_data({domain}) ...")
- instances.update_instance_data(domain)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def get_peers(domain: str, software: str) -> list:
- # DEBUG: print(f"DEBUG: domain({len(domain)})={domain},software={software} - CALLED!")
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
- elif type(software) != str and software != None:
- raise ValueError(f"software[]={type(software)} is not 'str'")
-
- peers = list()
-
- if software == "misskey":
- # DEBUG: print(f"DEBUG: domain='{domain}' is misskey, sending API POST request ...")
- offset = 0
- step = config.get("misskey_limit")
-
- # 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}' ...")
- if offset == 0:
- fetched = post_json_api(domain, "/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "limit": step
- }), {
- "Origin": domain
- })
- else:
- fetched = post_json_api(domain, "/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "limit" : step,
- "offset": offset - 1
- }), {
- "Origin": domain
- })
-
- # DEBUG: print(f"DEBUG: fetched()={len(fetched))}")
- if len(fetched) == 0:
- # DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
- break
- elif len(fetched) != config.get("misskey_limit"):
- # DEBUG: print(f"DEBUG: Fetched '{len(fetched)}' row(s) but expected: '{config.get('misskey_limit')}'")
- offset = offset + (config.get("misskey_limit") - len(fetched))
- else:
- # DEBUG: print("DEBUG: Raising offset by step:", step)
- offset = offset + step
-
- # Check records
- # DEBUG: print(f"DEBUG: fetched({len(fetched)})[]={type(fetched)}")
- if isinstance(fetched, dict) and "error" in fetched and "message" in fetched["error"]:
- print(f"WARNING: post_json_api() returned error: {fetched['error']['message']}")
- update_last_error(domain, fetched["error"]["message"])
- break
-
- already = 0
- for row in fetched:
- # DEBUG: print(f"DEBUG: row():{len(row)}")
- if not "host" in row:
- print(f"WARNING: row()={len(row)} does not contain element 'host': {row},domain='{domain}'")
- continue
- elif type(row["host"]) != str:
- print(f"WARNING: row[host][]={type(row['host'])} is not 'str'")
- continue
- elif is_blacklisted(row["host"]):
- # DEBUG: print(f"DEBUG: row[host]='{row['host']}' is blacklisted. domain='{domain}'")
- continue
- elif row["host"] in peers:
- # DEBUG: print(f"DEBUG: Not adding row[host]='{row['host']}', already found.")
- already = already + 1
- continue
-
- # DEBUG: print(f"DEBUG: Adding peer: '{row['host']}'")
- peers.append(row["host"])
-
- if already == len(fetched):
- print(f"WARNING: Host returned same set of '{already}' instances, aborting loop!")
- break
-
- # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
- instances.set("total_peers", domain, len(peers))
-
- # DEBUG: print(f"DEBUG: Updating last_instance_fetch for domain='{domain}' ...")
- update_last_instance_fetch(domain)
-
- # DEBUG: print("DEBUG: Returning peers[]:", type(peers))
- return peers
- elif software == "lemmy":
- # DEBUG: print(f"DEBUG: domain='{domain}' is Lemmy, fetching JSON ...")
- try:
- response = get_response(domain, "/api/v3/site", api_headers, (config.get("connection_timeout"), config.get("read_timeout")))
-
- data = json_from_response(response)
-
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code='{response.status_code}',data[]='{type(data)}'")
- if not response.ok or response.status_code >= 400:
- print("WARNING: Could not reach any JSON API:", domain)
- update_last_error(domain, response)
- elif response.ok and isinstance(data, list):
- # DEBUG: print(f"DEBUG: domain='{domain}' returned a list: '{data}'")
- sys.exit(255)
- elif "federated_instances" in data:
- # DEBUG: print(f"DEBUG: Found federated_instances for domain='{domain}'")
- peers = peers + add_peers(data["federated_instances"])
- # DEBUG: print("DEBUG: Added instance(s) to peers")
- else:
- print("WARNING: JSON response does not contain 'federated_instances':", domain)
- update_last_error(domain, response)
-
- except BaseException as e:
- print(f"WARNING: Exception during fetching JSON: domain='{domain}',exception[{type(e)}]:'{str(e)}'")
-
- # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
- instances.set("total_peers", domain, len(peers))
-
- # DEBUG: print(f"DEBUG: Updating last_instance_fetch for domain='{domain}' ...")
- update_last_instance_fetch(domain)
-
- # DEBUG: print("DEBUG: Returning peers[]:", type(peers))
- return peers
- elif software == "peertube":
- # DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
-
- start = 0
- for mode in ["followers", "following"]:
- # DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
- while True:
- try:
- response = get_response(domain, "/api/v1/server/{mode}?start={start}&count=100", headers, (config.get("connection_timeout"), config.get("read_timeout")))
-
- data = json_from_response(response)
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code='{response.status_code}',data[]='{type(data)}'")
- if response.ok and isinstance(data, dict):
- # DEBUG: print("DEBUG: Success, data:", len(data))
- if "data" in data:
- # DEBUG: print(f"DEBUG: Found {len(data['data'])} record(s).")
- for record in data["data"]:
- # DEBUG: print(f"DEBUG: record()={len(record)}")
- if mode in record and "host" in record[mode]:
- # DEBUG: print(f"DEBUG: Found host={record[mode]['host']}, adding ...")
- peers.append(record[mode]["host"])
- else:
- print(f"WARNING: record from '{domain}' has no '{mode}' or 'host' record: {record}")
-
- if len(data["data"]) < 100:
- # DEBUG: print("DEBUG: Reached end of JSON response:", domain)
- break
-
- # Continue with next row
- start = start + 100
-
- except BaseException as e:
- print(f"WARNING: Exception during fetching JSON: domain='{domain}',exception[{type(e)}]:'{str(e)}'")
-
- # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
- instances.set("total_peers", domain, len(peers))
-
- # DEBUG: print(f"DEBUG: Updating last_instance_fetch for domain='{domain}' ...")
- update_last_instance_fetch(domain)
-
- # DEBUG: print("DEBUG: Returning peers[]:", type(peers))
- return peers
-
- # DEBUG: print(f"DEBUG: Fetching get_peers_url='{get_peers_url}' from '{domain}' ...")
- try:
- response = get_response(domain, get_peers_url, api_headers, (config.get("connection_timeout"), config.get("read_timeout")))
-
- data = json_from_response(response)
-
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},data[]='{type(data)}'")
- if not response.ok or response.status_code >= 400:
- # DEBUG: print(f"DEBUG: Was not able to fetch '{get_peers_url}', trying alternative ...")
- response = get_response(domain, "/api/v3/site", api_headers, (config.get("connection_timeout"), config.get("read_timeout")))
-
- data = json_from_response(response)
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},data[]='{type(data)}'")
- if not response.ok or response.status_code >= 400:
- print("WARNING: Could not reach any JSON API:", domain)
- update_last_error(domain, response)
- elif response.ok and isinstance(data, list):
- # DEBUG: print(f"DEBUG: domain='{domain}' returned a list: '{data}'")
- sys.exit(255)
- elif "federated_instances" in data:
- # DEBUG: print(f"DEBUG: Found federated_instances for domain='{domain}'")
- peers = peers + add_peers(data["federated_instances"])
- # DEBUG: print("DEBUG: Added instance(s) to peers")
- else:
- print("WARNING: JSON response does not contain 'federated_instances':", domain)
- update_last_error(domain, response)
- else:
- # DEBUG: print("DEBUG: Querying API was successful:", domain, len(data))
- peers = data
-
- except BaseException as e:
- print("WARNING: Some error during get():", domain, e)
- update_last_error(domain, e)
-
- # DEBUG: print(f"DEBUG: Adding '{len(peers)}' for domain='{domain}'")
- instances.set("total_peers", domain, len(peers))
-
- # DEBUG: print(f"DEBUG: Updating last_instance_fetch for domain='{domain}' ...")
- update_last_instance_fetch(domain)
-
- # DEBUG: print("DEBUG: Returning peers[]:", type(peers))
- return peers
-
-def post_json_api(domain: str, path: str, parameter: str, extra_headers: dict = {}) -> dict:
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
- elif type(path) != str:
- raise ValueError(f"path[]={type(path)} is not 'str'")
- elif path == "":
- raise ValueError("Parameter 'path' cannot be empty")
- elif type(parameter) != str:
- raise ValueError(f"parameter[]={type(parameter)} is not 'str'")
-
- # DEBUG: print("DEBUG: Sending POST to domain,path,parameter:", domain, path, parameter, extra_headers)
- data = {}
- try:
- response = reqto.post(f"https://{domain}{path}", data=parameter, headers={**api_headers, **extra_headers}, timeout=(config.get("connection_timeout"), config.get("read_timeout")))
-
- data = json_from_response(response)
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},data[]='{type(data)}'")
- if not response.ok or response.status_code >= 400:
- print(f"WARNING: Cannot query JSON API: domain='{domain}',path='{path}',parameter()={len(parameter)},response.status_code='{response.status_code}',data[]='{type(data)}'")
- update_last_error(domain, response)
-
- except BaseException as e:
- print(f"WARNING: Some error during post(): domain='{domain}',path='{path}',parameter()={len(parameter)},exception[{type(e)}]:'{str(e)}'")
-
- # DEBUG: print(f"DEBUG: Returning data({len(data)})=[]:{type(data)}")
- return data
-
-def fetch_nodeinfo(domain: str, path: str = None) -> list:
- # DEBUG: print(f"DEBUG: domain='{domain}',path={path} - CALLED!")
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
- elif type(path) != str and path != None:
- raise ValueError(f"Parameter path[]={type(path)} is not 'str'")
-
- # DEBUG: print("DEBUG: Fetching nodeinfo from domain,path:", domain, path)
- nodeinfo = fetch_wellknown_nodeinfo(domain)
-
- # DEBUG: print(f"DEBUG: nodeinfo({len(nodeinfo)})={nodeinfo}")
- if len(nodeinfo) > 0:
- # DEBUG: print("DEBUG: nodeinfo()={len(nodeinfo))} - EXIT!")
- return nodeinfo
-
- requests = [
- f"https://{domain}/nodeinfo/2.1.json",
- f"https://{domain}/nodeinfo/2.1",
- f"https://{domain}/nodeinfo/2.0.json",
- f"https://{domain}/nodeinfo/2.0",
- f"https://{domain}/nodeinfo/1.0",
- f"https://{domain}/api/v1/instance"
- ]
-
- data = {}
- for request in requests:
- if path != None and path != "" and request != path:
- # DEBUG: print(f"DEBUG: path='{path}' does not match request='{request}' - SKIPPED!")
- continue
-
- try:
- # DEBUG: print("DEBUG: Fetching request:", request)
- response = reqto.get(request, headers=api_headers, timeout=(config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout")))
-
- data = json_from_response(response)
- # DEBUG: print(f"DEBUG: response.ok={response.ok},response.status_code={response.status_code},data[]='{type(data)}'")
- if response.ok and isinstance(data, dict):
- # DEBUG: print("DEBUG: Success:", request)
- instances.set("detection_mode", domain, "STATIC_CHECK")
- instances.set("nodeinfo_url" , domain, request)
- break
- elif response.ok and isinstance(data, list):
- # DEBUG: print(f"DEBUG: domain='{domain}' returned a list: '{data}'")
- sys.exit(255)
- elif not response.ok or response.status_code >= 400:
- print("WARNING: Failed fetching nodeinfo from domain:", domain)
- update_last_error(domain, response)
- continue
-
- except BaseException as e:
- # DEBUG: print("DEBUG: Cannot fetch API request:", request)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print(f"DEBUG: data()={len(data)} - EXIT!")
- return data
-
-def fetch_wellknown_nodeinfo(domain: str) -> list:
- # DEBUG: print(f"DEBUG: domain={domain} - CALLED!")
- if type(domain) != str:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
-
- # DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
- data = {}
-
- try:
- response = get_response(domain, "/.well-known/nodeinfo", api_headers, (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout")))
-
- data = json_from_response(response)
- # DEBUG: print("DEBUG: domain,response.ok,data[]:", domain, response.ok, type(data))
- if response.ok and isinstance(data, dict):
- nodeinfo = data
- # DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
- if "links" in nodeinfo:
- # DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
- for link in nodeinfo["links"]:
- # DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
- if link["rel"] in nodeinfo_identifier:
- # DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
- response = reqto.get(link["href"])
-
- data = json_from_response(response)
- # DEBUG: print("DEBUG: href,response.ok,response.status_code:", link["href"], response.ok, response.status_code)
- if response.ok and isinstance(data, dict):
- # DEBUG: print("DEBUG: Found JSON nodeinfo():", len(data))
- instances.set("detection_mode", domain, "AUTO_DISCOVERY")
- instances.set("nodeinfo_url" , domain, link["href"])
- break
- else:
- print("WARNING: Unknown 'rel' value:", domain, link["rel"])
- else:
- print("WARNING: nodeinfo does not contain 'links':", domain)
-
- except BaseException as e:
- print("WARNING: Failed fetching .well-known info:", domain)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print("DEBUG: Returning data[]:", type(data))
- return data
-
-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:
- raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
- elif domain == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
- elif type(path) != str:
- raise ValueError(f"path[]={type(path)} is not 'str'")
- elif path == "":
- raise ValueError(f"Parameter 'domain' cannot be empty")
-
- # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}' - CALLED!")
- software = None
-
- try:
- # DEBUG: print(f"DEBUG: Fetching path='{path}' from '{domain}' ...")
- response = get_response(domain, path, headers, (config.get("connection_timeout"), config.get("read_timeout")))
-
- # DEBUG: print("DEBUG: domain,response.ok,response.status_code,response.text[]:", domain, response.ok, response.status_code, type(response.text))
- if response.ok and response.status_code < 300 and len(response.text) > 0:
- # DEBUG: print("DEBUG: Search for <meta name='generator'>:", domain)
- doc = bs4.BeautifulSoup(response.text, "html.parser")
-
- # DEBUG: print("DEBUG: doc[]:", type(doc))
- generator = doc.find("meta", {"name": "generator"})
- site_name = doc.find("meta", {"property": "og:site_name"})
-
- # DEBUG: print(f"DEBUG: generator='{generator}',site_name='{site_name}'")
- if isinstance(generator, bs4.element.Tag):
- # DEBUG: print("DEBUG: Found generator meta tag:", domain)
- software = tidyup_domain(generator.get("content"))
- print(f"INFO: domain='{domain}' is generated by '{software}'")
- instances.set("detection_mode", domain, "GENERATOR")
- remove_pending_error(domain)
- elif isinstance(site_name, bs4.element.Tag):
- # DEBUG: print("DEBUG: Found property=og:site_name:", domain)
- sofware = tidyup_domain(site_name.get("content"))
- print(f"INFO: domain='{domain}' has og:site_name='{software}'")
- instances.set("detection_mode", domain, "SITE_NAME")
- remove_pending_error(domain)
-
- except BaseException as e:
- # DEBUG: print(f"DEBUG: Cannot fetch / from '{domain}':", e)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if type(software) is 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):
- # 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:
- # 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:
- # 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:
- # DEBUG: print(f"DEBUG: software='{software}' has ' by ' in it")
- software = strip_until(software, " by ")
- elif type(software) is str and " see " in software:
- # DEBUG: print(f"DEBUG: software='{software}' has ' see ' in it")
- software = strip_until(software, " see ")