pleroma-relay/relay/remote_actor.py

57 lines
1.5 KiB
Python
Raw Permalink Normal View History

import logging
2018-08-10 21:14:22 +00:00
import aiohttp
from cachetools import TTLCache
2021-09-15 02:17:27 +00:00
from datetime import datetime
from urllib.parse import urlsplit
from . import CONFIG
from .http_debug import http_debug
CACHE_SIZE = CONFIG.get('cache-size', 16384)
CACHE_TTL = CONFIG.get('cache-ttl', 3600)
ACTORS = TTLCache(CACHE_SIZE, CACHE_TTL)
2018-08-10 21:14:22 +00:00
2021-09-15 02:17:27 +00:00
async def fetch_actor(uri, headers={}, force=False, sign_headers=True):
2018-08-10 21:14:22 +00:00
if uri in ACTORS and not force:
return ACTORS[uri]
2021-09-15 02:17:27 +00:00
from .actor import PRIVKEY
from .http_signatures import sign_headers
url = urlsplit(uri)
key_id = 'https://{}/actor#main-key'.format(CONFIG['ap']['host'])
2020-12-04 06:43:49 +00:00
2021-09-15 02:17:27 +00:00
headers.update({
'Accept': 'application/activity+json',
'User-Agent': 'ActivityRelay'
})
if sign_headers:
headers.update({
'(request-target)': 'get {}'.format(url.path),
'Date': datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
'Host': url.netloc
})
headers['signature'] = sign_headers(headers, PRIVKEY, key_id)
headers.pop('(request-target)')
headers.pop('Host')
2020-12-04 06:43:49 +00:00
try:
async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
2021-09-15 02:17:27 +00:00
async with session.get(uri, headers=headers) as resp:
2018-11-18 22:09:08 +00:00
if resp.status != 200:
return None
2021-09-15 02:17:27 +00:00
ACTORS[uri] = (await resp.json(encoding='utf-8', content_type=None))
return ACTORS[uri]
2021-09-15 02:17:27 +00:00
except Exception as e:
logging.info('Caught %r while fetching actor %r.', e, uri)
return None