moviewyrm/fedireads/api.py

134 lines
4.3 KiB
Python
Raw Normal View History

2020-01-28 19:45:27 +00:00
''' api utilties '''
from base64 import b64encode
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from datetime import datetime
import json
import requests
from fedireads import models
from fedireads import incoming
from fedireads.settings import DOMAIN
def get_or_create_remote_user(actor):
2020-01-28 19:45:27 +00:00
''' look up a remote user or add them '''
try:
2020-01-29 20:07:20 +00:00
return models.User.objects.get(actor=actor)
except models.User.DoesNotExist:
2020-01-29 20:07:20 +00:00
pass
2020-02-07 23:29:11 +00:00
# TODO: also bring in the user's prevous reviews and books
2020-02-07 23:11:53 +00:00
# load the user's info from the actor url
2020-01-29 20:07:20 +00:00
response = requests.get(
actor,
headers={'Accept': 'application/activity+json'}
)
2020-02-07 23:29:11 +00:00
if not response.ok:
response.raise_for_status()
2020-01-29 20:07:20 +00:00
data = response.json()
2020-02-07 23:11:53 +00:00
# the webfinger format for the username.
# TODO: get the user's domain in a better way
2020-01-29 20:07:20 +00:00
username = '%s@%s' % (actor.split('/')[-1], actor.split('/')[2])
2020-02-07 21:39:48 +00:00
shared_inbox = data.get('endpoints').get('sharedInbox') if \
data.get('endpoints') else None
2020-02-07 23:11:53 +00:00
try:
user = models.User.objects.create_user(
username,
'', '', # email and passwords are left blank
actor=actor,
name=data.get('name'),
summary=data.get('summary'),
inbox=data['inbox'], #fail if there's no inbox
outbox=data['outbox'], # fail if there's no outbox
shared_inbox=shared_inbox,
# TODO: probably shouldn't bother to store this for remote users
public_key=data.get('publicKey').get('publicKeyPem'),
local=False
)
except KeyError:
return False
return user
2020-01-28 19:45:27 +00:00
def get_recipients(user, post_privacy, direct_recipients=None):
2020-02-07 23:11:53 +00:00
''' deduplicated list of recipient inboxes '''
2020-01-28 19:45:27 +00:00
recipients = direct_recipients or []
2020-02-07 23:11:53 +00:00
if post_privacy == 'direct':
# all we care about is direct_recipients, not followers
return recipients
2020-01-28 19:45:27 +00:00
2020-02-07 23:11:53 +00:00
# load all the followers of the user who is sending the message
2020-01-28 19:45:27 +00:00
followers = user.followers.all()
if post_privacy == 'public':
# post to public shared inboxes
shared_inboxes = set(u.shared_inbox for u in followers)
recipients += list(shared_inboxes)
2020-02-07 21:39:48 +00:00
# TODO: not every user has a shared inbox
2020-01-28 19:45:27 +00:00
# TODO: direct to anyone who's mentioned
if post_privacy == 'followers':
# don't send it to the shared inboxes
inboxes = set(u.inbox for u in followers)
recipients += list(inboxes)
return recipients
2020-02-07 23:11:53 +00:00
def broadcast(sender, activity, recipients):
2020-01-28 19:45:27 +00:00
''' send out an event '''
2020-01-29 23:55:48 +00:00
errors = []
2020-01-28 19:45:27 +00:00
for recipient in recipients:
2020-01-29 23:55:48 +00:00
try:
2020-02-07 23:11:53 +00:00
sign_and_send(sender, activity, recipient)
2020-01-29 23:55:48 +00:00
except requests.exceptions.HTTPError as e:
2020-02-07 23:11:53 +00:00
# TODO: maybe keep track of users who cause errors
2020-01-29 23:55:48 +00:00
errors.append({
'error': e,
'recipient': recipient,
2020-02-07 23:11:53 +00:00
'activity': activity,
2020-01-29 23:55:48 +00:00
})
return errors
2020-01-28 19:45:27 +00:00
2020-02-07 23:11:53 +00:00
def sign_and_send(sender, activity, destination):
2020-01-28 19:45:27 +00:00
''' crpyto whatever and http junk '''
2020-02-07 23:11:53 +00:00
# TODO: handle http[s] with regex
2020-01-28 19:45:27 +00:00
inbox_fragment = sender.inbox.replace('https://%s' % DOMAIN, '')
now = datetime.utcnow().isoformat()
2020-01-30 04:56:18 +00:00
signature_headers = [
'(request-target): post %s' % inbox_fragment,
'host: https://%s' % DOMAIN,
'date: %s' % now
]
message_to_sign = '\n'.join(signature_headers)
2020-02-07 23:11:53 +00:00
# TODO: raise an error if the user doesn't have a private key
2020-01-28 19:45:27 +00:00
signer = pkcs1_15.new(RSA.import_key(sender.private_key))
signed_message = signer.sign(SHA256.new(message_to_sign.encode('utf8')))
2020-01-29 23:55:48 +00:00
signature = {
'keyId': '%s#main-key' % sender.actor,
'algorithm': 'rsa-sha256',
'headers': '(request-target) host date',
2020-01-30 04:56:18 +00:00
'signature': b64encode(signed_message).decode('utf8'),
2020-01-29 23:55:48 +00:00
}
signature = ','.join('%s="%s"' % (k, v) for (k, v) in signature.items())
2020-01-28 19:45:27 +00:00
response = requests.post(
destination,
2020-02-07 23:11:53 +00:00
data=json.dumps(activity),
2020-01-28 19:45:27 +00:00
headers={
'Date': now,
'Signature': signature,
2020-01-30 04:56:18 +00:00
'Host': 'https://%s' % DOMAIN,
2020-02-07 21:39:48 +00:00
'Content-Type': 'application/activity+json; charset=utf-8',
2020-01-28 19:45:27 +00:00
},
)
if not response.ok:
response.raise_for_status()
incoming.handle_response(response)