moviewyrm/fedireads/incoming.py

322 lines
9.8 KiB
Python
Raw Normal View History

2020-01-28 19:45:27 +00:00
''' handles all of the activity coming in to the server '''
2020-01-30 04:56:18 +00:00
from base64 import b64decode
2020-03-29 07:05:09 +00:00
from Crypto.Hash import SHA256
2020-01-30 04:56:18 +00:00
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
import django.db.utils
2020-03-29 07:05:09 +00:00
from django.http import HttpResponse
from django.http import HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
import json
2020-01-30 04:56:18 +00:00
import requests
2020-03-29 07:05:09 +00:00
from fedireads import models, outgoing
2020-03-21 22:21:27 +00:00
from fedireads import status as status_builder
2020-02-15 06:44:07 +00:00
from fedireads.remote_user import get_or_create_remote_user
@csrf_exempt
2020-01-28 19:13:13 +00:00
def shared_inbox(request):
''' incoming activitypub events '''
2020-01-30 04:56:18 +00:00
# TODO: should this be functionally different from the non-shared inbox??
2020-01-28 19:13:13 +00:00
if request.method == 'GET':
return HttpResponseNotFound()
2020-01-28 19:13:13 +00:00
try:
activity = json.loads(request.body)
except json.decoder.JSONDecodeError:
2020-02-15 04:37:02 +00:00
return HttpResponseBadRequest()
try:
verify_signature(request)
except ValueError:
return HttpResponse(status=401)
handlers = {
'Follow': handle_follow,
'Accept': handle_follow_accept,
'Reject': handle_follow_reject,
2020-03-29 07:05:09 +00:00
'Create': handle_create,
'Like': handle_favorite,
'Announce': handle_boost,
2020-03-30 01:42:34 +00:00
'Add': {
'Tag': handle_add,
},
'Undo': {
'Follow': handle_unfollow,
'Like': handle_unfavorite,
},
'Update': {
'Person': None,# TODO: handle_update_user
'Document': None# TODO: handle_update_book
},
}
activity_type = activity['type']
2020-03-30 01:42:34 +00:00
handler = handlers.get(activity_type, None)
if isinstance(handler, dict):
handler = handler.get(activity['object']['type'], None)
2020-03-29 07:05:09 +00:00
if handler:
2020-03-29 07:05:09 +00:00
return handler(activity)
2020-02-19 08:13:06 +00:00
return HttpResponseNotFound()
2020-01-28 19:13:13 +00:00
2020-02-15 04:37:02 +00:00
def verify_signature(request):
''' verify rsa signature '''
2020-01-30 04:56:18 +00:00
signature_dict = {}
2020-02-15 04:37:02 +00:00
for pair in request.headers['Signature'].split(','):
2020-01-30 04:56:18 +00:00
k, v = pair.split('=', 1)
v = v.replace('"', '')
signature_dict[k] = v
2020-02-15 04:37:02 +00:00
try:
key_id = signature_dict['keyId']
headers = signature_dict['headers']
signature = b64decode(signature_dict['signature'])
except KeyError:
raise ValueError('Invalid auth header')
2020-01-30 04:56:18 +00:00
response = requests.get(
key_id,
headers={'Accept': 'application/activity+json'}
)
if not response.ok:
2020-02-15 04:37:02 +00:00
raise ValueError('Could not load public key')
2020-01-30 04:56:18 +00:00
actor = response.json()
key = RSA.import_key(actor['publicKey']['publicKeyPem'])
comparison_string = []
for signed_header_name in headers.split(' '):
if signed_header_name == '(request-target)':
comparison_string.append('(request-target): post %s' % request.path)
else:
comparison_string.append('%s: %s' % (
signed_header_name,
request.headers[signed_header_name]
))
comparison_string = '\n'.join(comparison_string)
signer = pkcs1_15.new(key)
digest = SHA256.new()
digest.update(comparison_string.encode())
2020-02-15 04:37:02 +00:00
# raises a ValueError if it fails
signer.verify(digest, signature)
2020-02-15 04:37:02 +00:00
return True
@csrf_exempt
def inbox(request, username):
''' incoming activitypub events '''
# TODO: should do some kind of checking if the user accepts
2020-01-30 04:56:18 +00:00
# this action from the sender probably? idk
2020-02-22 22:02:03 +00:00
# but this will just throw a 404 if the user doesn't exist
try:
models.User.objects.get(localname=username)
except models.User.DoesNotExist:
return HttpResponseNotFound()
2020-01-30 04:56:18 +00:00
return shared_inbox(request)
def handle_follow(activity):
2020-02-15 21:07:57 +00:00
''' someone wants to follow a local user '''
# figure out who they want to follow
to_follow = models.User.objects.get(actor=activity['object'])
# figure out who they are
user = get_or_create_remote_user(activity['actor'])
try:
request = models.UserFollowRequest.objects.create(
user_subject=user,
user_object=to_follow,
relationship_id=activity['id']
)
except django.db.utils.IntegrityError as err:
if err.__cause__.diag.constraint_name != 'userfollowrequest_unique':
raise
2020-02-23 21:24:23 +00:00
# Duplicate follow request. Not sure what the correct behaviour is, but
# just dropping it works for now. We should perhaps generate the
# Accept, but then do we need to match the activity id?
return HttpResponse()
if not to_follow.manually_approves_followers:
2020-03-21 22:21:27 +00:00
status_builder.create_notification(
to_follow,
'FOLLOW',
related_user=user
)
outgoing.handle_accept(user, to_follow, request)
else:
2020-03-21 22:21:27 +00:00
status_builder.create_notification(
to_follow,
'FOLLOW_REQUEST',
related_user=user
)
2020-02-15 06:44:07 +00:00
return HttpResponse()
2020-03-29 07:05:09 +00:00
def handle_unfollow(activity):
2020-02-19 06:44:13 +00:00
''' unfollow a local user '''
obj = activity['object']
if not obj['type'] == 'Follow':
#idk how to undo other things
return HttpResponseNotFound()
try:
requester = get_or_create_remote_user(obj['actor'])
to_unfollow = models.User.objects.get(actor=obj['object'])
except models.User.DoesNotExist:
return HttpResponseNotFound()
to_unfollow.followers.remove(requester)
return HttpResponse()
def handle_follow_accept(activity):
''' hurray, someone remote accepted a follow request '''
# figure out who they want to follow
requester = models.User.objects.get(actor=activity['object']['actor'])
# figure out who they are
accepter = get_or_create_remote_user(activity['actor'])
try:
2020-03-14 00:57:36 +00:00
request = models.UserFollowRequest.objects.get(
user_subject=requester,
user_object=accepter
)
request.delete()
except models.UserFollowRequest.DoesNotExist:
pass
accepter.followers.add(requester)
return HttpResponse()
def handle_follow_reject(activity):
''' someone is rejecting a follow request '''
requester = models.User.objects.get(actor=activity['object']['actor'])
rejecter = get_or_create_remote_user(activity['actor'])
try:
request = models.UserFollowRequest.objects.get(
user_subject=requester,
user_object=rejecter
)
request.delete()
except models.UserFollowRequest.DoesNotExist:
pass
return HttpResponse()
def handle_create(activity):
''' someone did something, good on them '''
user = get_or_create_remote_user(activity['actor'])
2020-02-15 05:00:11 +00:00
if not 'object' in activity:
return HttpResponseBadRequest()
2020-03-29 07:05:09 +00:00
if user.local:
# we really oughtn't even be sending in this case
return HttpResponse()
if activity['object'].get('fedireadsType') in ['Review', 'Comment'] and \
2020-03-21 23:50:49 +00:00
'inReplyToBook' in activity['object']:
2020-03-29 07:05:09 +00:00
try:
if activity['object']['fedireadsType'] == 'Review':
builder = status_builder.create_review_from_activity
else:
builder = status_builder.create_comment_from_activity
# create the status, it'll throw a valueerror if anything is missing
builder(user, activity['object'])
except ValueError:
return HttpResponseBadRequest()
else:
# TODO: should only create notes if they are relevent to a book,
# so, not every single thing someone posts on mastodon
try:
2020-03-21 22:21:27 +00:00
status = status_builder.create_status_from_activity(
user,
activity['object']
)
2020-03-13 00:16:55 +00:00
if status and status.reply_parent:
2020-03-21 22:21:27 +00:00
status_builder.create_notification(
2020-03-07 22:50:29 +00:00
status.reply_parent.user,
'REPLY',
related_user=status.user,
related_status=status,
)
except ValueError:
return HttpResponseBadRequest()
2020-03-29 07:05:09 +00:00
return HttpResponse()
2020-02-15 05:00:11 +00:00
def handle_favorite(activity):
2020-02-19 08:13:06 +00:00
''' approval of your good good post '''
try:
status_id = activity['object'].split('/')[-1]
status = models.Status.objects.get(id=status_id)
liker = get_or_create_remote_user(activity['actor'])
except (models.Status.DoesNotExist, models.User.DoesNotExist):
return HttpResponseNotFound()
if not liker.local:
2020-03-21 22:21:27 +00:00
status_builder.create_favorite_from_activity(liker, activity)
2020-03-07 22:50:29 +00:00
2020-03-21 22:21:27 +00:00
status_builder.create_notification(
2020-03-07 22:50:29 +00:00
status.user,
'FAVORITE',
related_user=liker,
related_status=status,
)
2020-02-19 08:13:06 +00:00
return HttpResponse()
def handle_unfavorite(activity):
2020-03-21 22:21:27 +00:00
''' approval of your good good post '''
try:
favorite_id = activity['object']['id']
fav = status_builder.get_favorite(favorite_id)
except models.Favorite.DoesNotExist:
return HttpResponseNotFound()
fav.delete()
return HttpResponse()
def handle_boost(activity):
''' someone gave us a boost! '''
try:
status_id = activity['object'].split('/')[-1]
status = models.Status.objects.get(id=status_id)
booster = get_or_create_remote_user(activity['actor'])
except (models.Status.DoesNotExist, models.User.DoesNotExist):
return HttpResponseNotFound()
if not booster.local:
status_builder.create_boost_from_activity(booster, activity)
status_builder.create_notification(
status.user,
'BOOST',
related_user=booster,
related_status=status,
)
return HttpResponse()
def handle_add(activity):
2020-02-21 06:19:19 +00:00
''' someone is tagging or shelving a book '''
if activity['object']['type'] == 'Tag':
user = get_or_create_remote_user(activity['actor'])
if not user.local:
2020-02-21 06:37:50 +00:00
book = activity['target']['id'].split('/')[-1]
2020-03-21 22:21:27 +00:00
status_builder.create_tag(user, book, activity['object']['name'])
2020-02-21 06:19:19 +00:00
return HttpResponse()
return HttpResponse()
return HttpResponseNotFound()
2020-03-21 22:21:27 +00:00