fetch well-known url for nodeinfo
[relay.git/.git] / relay / remote_actor.py
1 import logging
2 import aiohttp
3 from . import CONFIG
4 from .http_debug import http_debug
5
6 from cachetools import TTLCache
7
8
9 CACHE_SIZE = CONFIG.get('cache-size', 16384)
10 CACHE_TTL = CONFIG.get('cache-ttl', 3600)
11
12 ACTORS = TTLCache(CACHE_SIZE, CACHE_TTL)
13
14
15 async def fetch_actor(uri, headers={}, force=False):
16     if uri in ACTORS and not force:
17         return ACTORS[uri]
18
19     new_headers = {'Accept': 'application/activity+json'}
20
21     for k,v in headers.items():
22         new_headers[k.capitalize()] = v
23
24     try:
25         async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
26             async with session.get(uri, headers=new_headers) as resp:
27                 if resp.status != 200:
28                     return None
29                 ACTORS[uri] = (await resp.json(encoding='utf-8', content_type=None))
30                 return ACTORS[uri]
31     except Exception as e:
32         logging.info('Caught %r while fetching actor %r.', e, uri)
33         return None