uncia/uncia/functions.py

78 lines
1.4 KiB
Python

from functools import wraps
from izzylib import HttpRequestsClient, LruCache, logging
from . import __version__
from .config import config
from .database import db
client = HttpRequestsClient(appagent=f'UnciaRelay/{__version__}; https://{config.host}')
client.set_global()
cache = LruCache()
def cache_fetch(func):
@wraps(func)
def inner_func(url, *args, **kwargs):
cached = cache.fetch(url)
if cached:
return cached
response = func(url, *args, **kwargs)
if not response:
return
cache.store(url, response)
return response
return inner_func
@cache_fetch
def fetch_actor(url):
return client.json(url, activity=True).json
@cache_fetch
def fetch_auth(url):
with db.session as s:
response = client.signed_request(
s.get.config('privkey'),
f'https://{config.host}/actor#main-key',
url,
headers = {'accept': 'application/activity+json'}
)
return response.json()
def get_inbox(actor):
try:
return actor.endpoints.sharedInbox
except:
return actor.inbox
def push_message(inbox, message):
with db.session as s:
response = client.signed_request(
s.get.config('privkey'),
f'https://{config.host}/actor#main-key',
inbox,
data = message.to_json(),
method = 'post',
headers = {'accept': 'application/json'}
)
if response.status not in [200, 202]:
try:
body = response.json
except:
body = response.text
logging.debug(f'Error from {inbox}: {body}')
return response