bookwyrm/fedireads/federation.py

354 lines
10 KiB
Python
Raw Normal View History

2020-01-25 21:46:30 +00:00
''' activitystream api '''
2020-01-27 01:55:02 +00:00
from base64 import b64encode
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from datetime import datetime
2020-01-26 20:14:27 +00:00
from django.http import HttpResponse, HttpResponseBadRequest, \
HttpResponseNotFound, JsonResponse
2020-01-27 01:55:02 +00:00
from django.views.decorators.csrf import csrf_exempt
2020-01-26 00:24:22 +00:00
from fedireads.settings import DOMAIN
2020-01-27 01:55:02 +00:00
from fedireads import models
2020-01-27 02:49:57 +00:00
import json
2020-01-27 01:55:02 +00:00
import requests
import re
2020-01-28 02:47:54 +00:00
from uuid import uuid4
2020-01-26 20:14:27 +00:00
2020-01-25 21:46:30 +00:00
def webfinger(request):
2020-01-26 00:24:22 +00:00
''' allow other servers to ask about a user '''
resource = request.GET.get('resource')
if not resource and not resource.startswith('acct:'):
return HttpResponseBadRequest()
2020-01-27 01:55:02 +00:00
ap_id = resource.replace('acct:', '')
2020-01-28 03:57:17 +00:00
user = models.User.objects.filter(username=ap_id).first()
2020-01-26 00:24:22 +00:00
if not user:
return HttpResponseNotFound('No account found')
2020-01-28 02:47:54 +00:00
return JsonResponse({
2020-01-28 03:57:17 +00:00
'subject': 'acct:%s' % (user.username),
2020-01-26 00:24:22 +00:00
'links': [
{
'rel': 'self',
'type': 'application/activity+json',
2020-01-27 03:50:22 +00:00
'href': user.actor
2020-01-26 00:24:22 +00:00
}
]
2020-01-28 02:47:54 +00:00
})
2020-01-26 20:14:27 +00:00
2020-01-27 01:55:02 +00:00
@csrf_exempt
2020-01-27 04:57:48 +00:00
def get_actor(request, username):
2020-01-27 01:55:02 +00:00
''' return an activitypub actor object '''
2020-01-28 02:47:54 +00:00
if request.method != 'GET':
return HttpResponseBadRequest()
2020-01-28 04:56:45 +00:00
user = models.User.objects.get(localname=username)
2020-01-28 02:47:54 +00:00
return JsonResponse({
'@context': [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1'
],
'id': user.actor,
'type': 'Person',
2020-01-28 04:56:45 +00:00
'preferredUsername': user.localname,
2020-01-28 02:47:54 +00:00
'inbox': format_inbox(user),
'followers': '%s/followers' % user.actor,
'publicKey': {
'id': '%s/#main-key' % user.actor,
'owner': user.actor,
'publicKeyPem': user.public_key,
}
})
2020-01-27 01:55:02 +00:00
@csrf_exempt
2020-01-26 20:14:27 +00:00
def inbox(request, username):
''' incoming activitypub events '''
2020-01-27 01:55:02 +00:00
if request.method == 'GET':
2020-01-28 02:47:54 +00:00
# TODO: return a collection of something?
2020-01-27 04:57:48 +00:00
return JsonResponse({})
2020-01-27 01:55:02 +00:00
2020-01-27 04:57:48 +00:00
# TODO: RSA key verification
try:
activity = json.loads(request.body)
except json.decoder.JSONDecodeError:
return HttpResponseBadRequest
2020-01-28 02:47:54 +00:00
# TODO: should do some kind of checking if the user accepts
# this action from the sender
# but this will just throw an error if the user doesn't exist I guess
#models.User.objects.get(username=username)
2020-01-28 02:47:54 +00:00
2020-01-27 01:55:02 +00:00
if activity['type'] == 'Add':
2020-01-28 02:47:54 +00:00
return handle_add(activity)
2020-01-26 20:14:27 +00:00
2020-01-27 02:49:57 +00:00
if activity['type'] == 'Follow':
2020-01-28 02:47:54 +00:00
return handle_incoming_follow(activity)
2020-01-27 01:55:02 +00:00
return HttpResponse()
2020-01-27 04:57:48 +00:00
2020-01-28 03:57:17 +00:00
def handle_account_search(query):
''' webfingerin' other servers '''
domain = query.split('@')[1]
try:
user = models.User.objects.get(username=query)
except models.User.DoesNotExist:
2020-01-28 04:56:45 +00:00
url = 'https://%s/.well-known/webfinger?resource=acct:%s' % \
(domain, query)
response = requests.get(url)
if not response.ok:
response.raise_for_status()
2020-01-28 03:57:17 +00:00
data = response.json()
for link in data['links']:
if link['rel'] == 'self':
user = get_or_create_remote_user(link['href'])
return user
2020-01-27 01:55:02 +00:00
def handle_add(activity):
2020-01-28 02:47:54 +00:00
''' receiving an Add activity (to shelve a book) '''
# TODO what happens here? If it's a remote over, then I think
# I should save both the activity and the ShelfBook entry. But
# I'll do that later.
uuid = activity['id']
models.ShelveActivity.objects.get(uuid=uuid)
'''
2020-01-27 01:55:02 +00:00
book_id = activity['object']['url']
book = openlibrary.get_or_create_book(book_id)
user_ap_id = activity['actor'].replace('https//:', '')
2020-01-27 03:50:22 +00:00
user = models.User.objects.get(actor=user_ap_id)
2020-01-28 02:47:54 +00:00
if not user or not user.local:
return HttpResponseBadRequest()
2020-01-27 01:55:02 +00:00
shelf = models.Shelf.objects.get(activitypub_id=activity['target']['id'])
models.ShelfBook(
shelf=shelf,
book=book,
added_by=user,
).save()
2020-01-28 02:47:54 +00:00
'''
return HttpResponse()
2020-01-26 20:14:27 +00:00
2020-01-27 02:49:57 +00:00
2020-01-28 02:47:54 +00:00
def handle_incoming_follow(activity):
2020-01-27 02:49:57 +00:00
'''
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://friend.camp/768222ce-a1c7-479c-a544-c93b8b67fb54",
"type": "Follow",
"actor": "https://friend.camp/users/tripofmice",
"object": "https://ff2cb3e9.ngrok.io/api/u/mouse"
}
'''
# figure out who they want to follow
to_follow = re.sub(
r'https?://([\w\.]+)/api/u/(\w+)',
r'\2@\1',
activity['object']
)
to_follow = models.User.objects.get(username=to_follow)
2020-01-27 02:49:57 +00:00
# figure out who they are
2020-01-28 04:56:45 +00:00
user = get_or_create_remote_user(activity['actor'])
to_follow.followers.add(user)
2020-01-28 02:47:54 +00:00
# verify uuid and accept the request
models.FollowActivity(
uuid=activity['id'],
user=user,
followed=to_follow,
2020-01-28 02:47:54 +00:00
content=activity,
activity_type='Follow',
)
uuid = uuid4()
return JsonResponse({
'@context': 'https://www.w3.org/ns/activitystreams',
'id': 'https://%s/%s' % (DOMAIN, uuid),
'type': 'Accept',
'actor': user.actor,
'object': activity,
})
def handle_outgoing_follow(user, to_follow):
''' someone local wants to follow someone '''
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': '',
'type': 'Follow',
'actor': user.actor,
2020-01-28 03:57:17 +00:00
'object': to_follow.actor,
2020-01-28 02:47:54 +00:00
}
broadcast(user, activity, [format_inbox(to_follow)])
models.FollowActivity(
uuid=uuid,
user=user,
2020-01-28 04:56:45 +00:00
followed=to_follow,
2020-01-28 02:47:54 +00:00
content=activity,
).save()
def handle_shelve(user, book, shelf):
''' gettin organized '''
# update the database
models.ShelfBook(book=book, shelf=shelf, added_by=user).save()
# send out the activitypub action
summary = '%s marked %s as %s' % (
user.username,
book.data['title'],
shelf.name
)
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': summary,
'type': 'Add',
'actor': user.actor,
'object': {
'type': 'Document',
'name': book.data['title'],
'url': book.openlibrary_key
},
'target': {
'type': 'Collection',
'name': shelf.name,
'id': shelf.activitypub_id
}
}
recipients = [format_inbox(u) for u in user.followers.all()]
models.ShelveActivity(
uuid=uuid,
user=user,
content=activity,
activity_type='Add',
shelf=shelf,
book=book,
).save()
broadcast(user, activity, recipients)
def handle_review(user, book, name, content, rating):
''' post a review '''
review_uuid = uuid4()
obj = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(review_uuid),
'type': 'Article',
'published': datetime.utcnow().isoformat(),
'attributedTo': user.actor,
'content': content,
'inReplyTo': book.activitypub_id,
'rating': rating, # fedireads-only custom field
'to': 'https://www.w3.org/ns/activitystreams#Public'
}
recipients = [format_inbox(u) for u in user.followers.all()]
create_uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(create_uuid),
'type': 'Create',
'actor': user.actor,
'to': ['%s/followers' % user.actor],
'cc': ['https://www.w3.org/ns/activitystreams#Public'],
'object': obj,
}
models.Review(
uuid=create_uuid,
user=user,
content=activity,
activity_type='Article',
book=book,
work=book.works.first(),
name=name,
rating=rating,
review_content=content,
).save()
broadcast(user, activity, recipients)
2020-01-27 02:49:57 +00:00
2020-01-27 01:55:02 +00:00
@csrf_exempt
2020-01-26 20:14:27 +00:00
def outbox(request, username):
2020-01-27 04:57:48 +00:00
''' outbox for the requested user '''
2020-01-28 04:56:45 +00:00
user = models.User.objects.get(localname=username)
2020-01-28 02:47:54 +00:00
size = models.Review.objects.filter(user=user).count()
2020-01-26 20:14:27 +00:00
if request.method == 'GET':
# list of activities
2020-01-28 02:47:54 +00:00
return JsonResponse({
'@context': 'https://www.w3.org/ns/activitystreams',
'id': '%s/outbox' % user.actor,
'type': 'OrderedCollection',
'totalItems': size,
'first': '%s/outbox?page=true' % user.actor,
'last': '%s/outbox?min_id=0&page=true' % user.actor
})
# TODO: paginated list of messages
2020-01-26 20:14:27 +00:00
2020-01-28 02:47:54 +00:00
#data = request.body.decode('utf-8')
2020-01-26 20:14:27 +00:00
return HttpResponse()
2020-01-27 01:55:02 +00:00
2020-01-28 02:47:54 +00:00
def broadcast(sender, action, recipients):
''' send out an event to all followers '''
2020-01-27 01:55:02 +00:00
for recipient in recipients:
2020-01-28 02:47:54 +00:00
sign_and_send(sender, action, recipient)
2020-01-27 01:55:02 +00:00
2020-01-28 03:57:17 +00:00
2020-01-28 02:47:54 +00:00
def sign_and_send(sender, action, destination):
''' crpyto whatever and http junk '''
2020-01-28 04:56:45 +00:00
inbox_fragment = '/api/u/%s/inbox' % (sender.localname)
2020-01-27 03:50:22 +00:00
now = datetime.utcnow().isoformat()
message_to_sign = '''(request-target): post %s
host: https://%s
date: %s''' % (inbox_fragment, DOMAIN, now)
signer = pkcs1_15.new(RSA.import_key(sender.private_key))
signed_message = signer.sign(SHA256.new(message_to_sign.encode('utf8')))
2020-01-28 04:56:45 +00:00
signature = 'keyId="%s",' % sender.localname
2020-01-27 03:50:22 +00:00
signature += 'headers="(request-target) host date",'
signature += 'signature="%s"' % b64encode(signed_message)
response = requests.post(
destination,
data=json.dumps(action),
headers={
'Date': now,
'Signature': signature,
'Host': DOMAIN,
},
)
if not response.ok:
2020-01-27 04:57:48 +00:00
response.raise_for_status()
2020-01-26 20:14:27 +00:00
2020-01-28 03:57:17 +00:00
def get_or_create_remote_user(actor):
2020-01-27 04:57:48 +00:00
''' wow, a foreigner '''
2020-01-27 03:50:22 +00:00
try:
user = models.User.objects.get(actor=actor)
except models.User.DoesNotExist:
# TODO: how do you actually correctly learn this?
username = '%s@%s' % (actor.split('/')[-1], actor.split('/')[2])
2020-01-27 04:57:48 +00:00
user = models.User.objects.create_user(
username,
'', '',
actor=actor,
local=False
)
2020-01-27 03:50:22 +00:00
return user
2020-01-26 20:14:27 +00:00
2020-01-28 02:47:54 +00:00
def format_inbox(user):
''' describe an inbox '''
return '%s/inbox' % (user.actor)