remote_actor.py 1.53 KB
Newer Older
1
import logging
kaniini's avatar
kaniini committed
2
3
import aiohttp

4
from cachetools import TTLCache
Izalia Mae's avatar
Izalia Mae committed
5
6
7
8
9
from datetime import datetime
from urllib.parse import urlsplit

from . import CONFIG
from .http_debug import http_debug
10
11
12
13
14
15
16


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
17

Izalia Mae's avatar
Izalia Mae committed
18
async def fetch_actor(uri, headers={}, force=False, sign_headers=True):
kaniini's avatar
kaniini committed
19
20
21
    if uri in ACTORS and not force:
        return ACTORS[uri]

Izalia Mae's avatar
Izalia Mae committed
22
23
24
25
26
    from .actor import PRIVKEY
    from .http_signatures import sign_headers

    url = urlsplit(uri)
    key_id = 'https://{}/actor#main-key'.format(CONFIG['ap']['host'])
Izalia Mae's avatar
Izalia Mae committed
27

Izalia Mae's avatar
Izalia Mae committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    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')
Izalia Mae's avatar
Izalia Mae committed
43

44
45
    try:
        async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
Izalia Mae's avatar
Izalia Mae committed
46
47
            async with session.get(uri, headers=headers) as resp:

kaniini's avatar
kaniini committed
48
                if resp.status != 200:
49
                    return None
Izalia Mae's avatar
Izalia Mae committed
50

51
52
                ACTORS[uri] = (await resp.json(encoding='utf-8', content_type=None))
                return ACTORS[uri]
Izalia Mae's avatar
Izalia Mae committed
53

54
55
56
    except Exception as e:
        logging.info('Caught %r while fetching actor %r.', e, uri)
        return None