remote_actor.py 968 Bytes
Newer Older
1
import logging
kaniini's avatar
kaniini committed
2
import aiohttp
3
from . import CONFIG
kaniini's avatar
kaniini committed
4
from .http_debug import http_debug
kaniini's avatar
kaniini committed
5

6
7
8
9
10
11
12
13
from cachetools import TTLCache


CACHE_SIZE = CONFIG.get('cache-size', 16384)
CACHE_TTL = CONFIG.get('cache-ttl', 3600)

ACTORS = TTLCache(CACHE_SIZE, CACHE_TTL)

kaniini's avatar
kaniini committed
14

Izalia Mae's avatar
Izalia Mae committed
15
async def fetch_actor(uri, headers={}, force=False):
kaniini's avatar
kaniini committed
16
17
18
    if uri in ACTORS and not force:
        return ACTORS[uri]

Izalia Mae's avatar
Izalia Mae committed
19
20
21
22
23
    new_headers = {'Accept': 'application/activity+json'}

    for k,v in headers.items():
        new_headers[k.capitalize()] = v

24
25
    try:
        async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
Izalia Mae's avatar
Izalia Mae committed
26
            async with session.get(uri, headers=new_headers) as resp:
kaniini's avatar
kaniini committed
27
                if resp.status != 200:
28
29
30
31
32
33
                    return None
                ACTORS[uri] = (await resp.json(encoding='utf-8', content_type=None))
                return ACTORS[uri]
    except Exception as e:
        logging.info('Caught %r while fetching actor %r.', e, uri)
        return None