2019-03-14 20:06:39 +00:00
|
|
|
import json
|
2018-10-28 21:31:33 +00:00
|
|
|
import logging
|
|
|
|
from typing import Optional, Any
|
|
|
|
|
|
|
|
from federation.entities.activitypub.entities import ActivitypubProfile
|
|
|
|
from federation.entities.activitypub.mappers import message_to_objects
|
|
|
|
from federation.utils.network import fetch_document
|
2019-03-14 20:06:39 +00:00
|
|
|
from federation.utils.text import decode_if_bytes
|
2018-10-28 21:31:33 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger('federation')
|
|
|
|
|
|
|
|
|
2019-08-05 20:58:08 +00:00
|
|
|
def retrieve_and_parse_content(**kwargs) -> Optional[Any]:
|
|
|
|
return retrieve_and_parse_document(kwargs.get("id"))
|
|
|
|
|
|
|
|
|
2019-03-14 20:06:39 +00:00
|
|
|
def retrieve_and_parse_document(fid: str) -> Optional[Any]:
|
2018-10-28 21:31:33 +00:00
|
|
|
"""
|
|
|
|
Retrieve remote document by ID and return the entity.
|
|
|
|
"""
|
2019-03-14 20:06:39 +00:00
|
|
|
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'})
|
2018-10-28 21:31:33 +00:00
|
|
|
if document:
|
2019-03-14 20:06:39 +00:00
|
|
|
document = json.loads(decode_if_bytes(document))
|
|
|
|
entities = message_to_objects(document, fid)
|
2019-08-05 20:58:08 +00:00
|
|
|
logger.info("retrieve_and_parse_document - found %s entities", len(entities))
|
2018-10-28 21:31:33 +00:00
|
|
|
if entities:
|
2019-08-05 20:58:08 +00:00
|
|
|
logger.info("retrieve_and_parse_document - using first entity: %s", entities[0])
|
2018-10-28 21:31:33 +00:00
|
|
|
return entities[0]
|
|
|
|
|
|
|
|
|
2019-03-14 20:06:39 +00:00
|
|
|
def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]:
|
2018-10-28 21:31:33 +00:00
|
|
|
"""
|
2019-03-14 20:06:39 +00:00
|
|
|
Retrieve the remote fid and return a Profile object.
|
2018-10-28 21:31:33 +00:00
|
|
|
"""
|
2019-03-14 20:06:39 +00:00
|
|
|
profile = retrieve_and_parse_document(fid)
|
2018-10-28 21:31:33 +00:00
|
|
|
if not profile:
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
profile.validate()
|
|
|
|
except ValueError as ex:
|
|
|
|
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
|
|
|
|
profile, ex)
|
|
|
|
return
|
|
|
|
return profile
|