code style cleanup

This commit is contained in:
Mouse Reeve 2020-05-09 14:26:27 -07:00
parent 2a98093ebe
commit ee7c04cc7e
8 changed files with 65 additions and 57 deletions

View file

@ -12,7 +12,7 @@ def get_remove(*args):
def get_add_remove(user, book, shelf, action='Add'): def get_add_remove(user, book, shelf, action='Add'):
''' format an Add or Remove json blob ''' ''' format a shelve book json blob '''
uuid = uuid4() uuid = uuid4()
return { return {
'@context': 'https://www.w3.org/ns/activitystreams', '@context': 'https://www.w3.org/ns/activitystreams',

View file

@ -19,10 +19,13 @@ def get_public_recipients(user, software=None):
# TODO: eventually we may want to handle particular software differently # TODO: eventually we may want to handle particular software differently
followers = followers.filter(fedireads_user=(software == 'fedireads')) followers = followers.filter(fedireads_user=(software == 'fedireads'))
# we want shared inboxes when available
shared = followers.filter( shared = followers.filter(
shared_inbox__isnull=False shared_inbox__isnull=False
).values_list('shared_inbox', flat=True).distinct() ).values_list('shared_inbox', flat=True).distinct()
# if a user doesn't have a shared inbox, we need their personal inbox
# iirc pixelfed doesn't have shared inboxes
inboxes = followers.filter( inboxes = followers.filter(
shared_inbox__isnull=True shared_inbox__isnull=True
).values_list('inbox', flat=True) ).values_list('inbox', flat=True)
@ -33,7 +36,9 @@ def get_public_recipients(user, software=None):
def broadcast(sender, activity, software=None, \ def broadcast(sender, activity, software=None, \
privacy='public', direct_recipients=None): privacy='public', direct_recipients=None):
''' send out an event ''' ''' send out an event '''
# start with parsing the direct recipients
recipients = [u.inbox for u in direct_recipients or []] recipients = [u.inbox for u in direct_recipients or []]
# and then add any other recipients
# TODO: other kinds of privacy # TODO: other kinds of privacy
if privacy == 'public': if privacy == 'public':
recipients += get_public_recipients(sender, software=software) recipients += get_public_recipients(sender, software=software)
@ -69,7 +74,9 @@ def sign_and_send(sender, activity, destination):
] ]
message_to_sign = '\n'.join(signature_headers) message_to_sign = '\n'.join(signature_headers)
# TODO: raise an error if the user doesn't have a private key if not sender.private_key:
# this shouldn't happen. it would be bad if it happened.
raise ValueError('No private key found for sender')
signer = pkcs1_15.new(RSA.import_key(sender.private_key)) signer = pkcs1_15.new(RSA.import_key(sender.private_key))
signed_message = signer.sign(SHA256.new(message_to_sign.encode('utf8'))) signed_message = signer.sign(SHA256.new(message_to_sign.encode('utf8')))

View file

@ -101,7 +101,7 @@ class EditionForm(ModelForm):
'updated_date', 'updated_date',
'last_sync_date', 'last_sync_date',
'authors', 'authors',# TODO
'parent_work', 'parent_work',
'shelves', 'shelves',
'misc_identifiers', 'misc_identifiers',

View file

@ -12,6 +12,7 @@ MAX_ENTRIES = 500
def create_job(user, csv_file): def create_job(user, csv_file):
''' check over a csv and creates a database entry for the job'''
job = ImportJob.objects.create(user=user) job = ImportJob.objects.create(user=user)
for index, entry in enumerate(list(csv.DictReader(csv_file))[:MAX_ENTRIES]): for index, entry in enumerate(list(csv.DictReader(csv_file))[:MAX_ENTRIES]):
if not all(x in entry for x in ('ISBN13', 'Title', 'Author')): if not all(x in entry for x in ('ISBN13', 'Title', 'Author')):
@ -19,13 +20,17 @@ def create_job(user, csv_file):
ImportItem(job=job, index=index, data=entry).save() ImportItem(job=job, index=index, data=entry).save()
return job return job
def start_import(job): def start_import(job):
''' initalizes a csv import job '''
result = import_data.delay(job.id) result = import_data.delay(job.id)
job.task_id = result.id job.task_id = result.id
job.save() job.save()
@app.task @app.task
def import_data(job_id): def import_data(job_id):
''' does the actual lookup work in a celery task '''
job = ImportJob.objects.get(id=job_id) job = ImportJob.objects.get(id=job_id)
try: try:
results = [] results = []

View file

@ -42,6 +42,9 @@ def shared_inbox(request):
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
return HttpResponseBadRequest() return HttpResponseBadRequest()
if not activity.get('object'):
return HttpResponseBadRequest()
try: try:
verify_signature(request) verify_signature(request)
except ValueError: except ValueError:
@ -128,9 +131,13 @@ def verify_signature(request):
@app.task @app.task
def handle_follow(activity): def handle_follow(activity):
''' someone wants to follow a local user ''' ''' someone wants to follow a local user '''
# figure out who they want to follow # figure out who they want to follow -- not using get_or_create because
# we only allow you to follow local users
try:
to_follow = models.User.objects.get(actor=activity['object']) to_follow = models.User.objects.get(actor=activity['object'])
# figure out who they are except models.User.DoesNotExist:
return False
# figure out who the actor is
user = get_or_create_remote_user(activity['actor']) user = get_or_create_remote_user(activity['actor'])
try: try:
request = models.UserFollowRequest.objects.create( request = models.UserFollowRequest.objects.create(
@ -165,14 +172,11 @@ def handle_follow(activity):
def handle_unfollow(activity): def handle_unfollow(activity):
''' unfollow a local user ''' ''' unfollow a local user '''
obj = activity['object'] obj = activity['object']
if not obj['type'] == 'Follow':
#idk how to undo other things
return HttpResponseNotFound()
try: try:
requester = get_or_create_remote_user(obj['actor']) requester = get_or_create_remote_user(obj['actor'])
to_unfollow = models.User.objects.get(actor=obj['object']) to_unfollow = models.User.objects.get(actor=obj['object'])
except models.User.DoesNotExist: except models.User.DoesNotExist:
return HttpResponseNotFound() return False
to_unfollow.followers.remove(requester) to_unfollow.followers.remove(requester)
@ -209,7 +213,7 @@ def handle_follow_reject(activity):
) )
request.delete() request.delete()
except models.UserFollowRequest.DoesNotExist: except models.UserFollowRequest.DoesNotExist:
pass return False
@app.task @app.task
@ -217,16 +221,12 @@ def handle_create(activity):
''' someone did something, good on them ''' ''' someone did something, good on them '''
user = get_or_create_remote_user(activity['actor']) user = get_or_create_remote_user(activity['actor'])
if not 'object' in activity:
return False
if user.local: if user.local:
# we really oughtn't even be sending in this case # we really oughtn't even be sending in this case
return True return True
if activity['object'].get('fedireadsType') and \ if activity['object'].get('fedireadsType') and \
'inReplyToBook' in activity['object']: 'inReplyToBook' in activity['object']:
try:
if activity['object']['fedireadsType'] == 'Review': if activity['object']['fedireadsType'] == 'Review':
builder = status_builder.create_review_from_activity builder = status_builder.create_review_from_activity
elif activity['object']['fedireadsType'] == 'Quotation': elif activity['object']['fedireadsType'] == 'Quotation':
@ -234,16 +234,13 @@ def handle_create(activity):
else: else:
builder = status_builder.create_comment_from_activity builder = status_builder.create_comment_from_activity
# create the status, it'll throw a valueerror if anything is missing # create the status, it'll throw a ValueError if anything is missing
builder(user, activity['object']) builder(user, activity['object'])
except ValueError:
return False
elif activity['object'].get('inReplyTo'): elif activity['object'].get('inReplyTo'):
# only create the status if it's in reply to a status we already know # only create the status if it's in reply to a status we already know
if not status_builder.get_status(activity['object']['inReplyTo']): if not status_builder.get_status(activity['object']['inReplyTo']):
return True return True
try:
status = status_builder.create_status_from_activity( status = status_builder.create_status_from_activity(
user, user,
activity['object'] activity['object']
@ -255,8 +252,6 @@ def handle_create(activity):
related_user=status.user, related_user=status.user,
related_status=status, related_status=status,
) )
except ValueError:
return False
return True return True
@ -268,7 +263,7 @@ def handle_favorite(activity):
status = models.Status.objects.get(id=status_id) status = models.Status.objects.get(id=status_id)
liker = get_or_create_remote_user(activity['actor']) liker = get_or_create_remote_user(activity['actor'])
except (models.Status.DoesNotExist, models.User.DoesNotExist): except (models.Status.DoesNotExist, models.User.DoesNotExist):
return return False
if not liker.local: if not liker.local:
status_builder.create_favorite_from_activity(liker, activity) status_builder.create_favorite_from_activity(liker, activity)
@ -287,7 +282,7 @@ def handle_unfavorite(activity):
favorite_id = activity['object']['id'] favorite_id = activity['object']['id']
fav = status_builder.get_favorite(favorite_id) fav = status_builder.get_favorite(favorite_id)
if not fav: if not fav:
return HttpResponseNotFound() return False
fav.delete() fav.delete()
@ -300,7 +295,7 @@ def handle_boost(activity):
status = models.Status.objects.get(id=status_id) status = models.Status.objects.get(id=status_id)
booster = get_or_create_remote_user(activity['actor']) booster = get_or_create_remote_user(activity['actor'])
except (models.Status.DoesNotExist, models.User.DoesNotExist): except (models.Status.DoesNotExist, models.User.DoesNotExist):
return HttpResponseNotFound() return False
if not booster.local: if not booster.local:
status_builder.create_boost_from_activity(booster, activity) status_builder.create_boost_from_activity(booster, activity)
@ -318,7 +313,7 @@ def handle_tag(activity):
''' someone is tagging or shelving a book ''' ''' someone is tagging or shelving a book '''
user = get_or_create_remote_user(activity['actor']) user = get_or_create_remote_user(activity['actor'])
if not user.local: if not user.local:
book = activity['target']['id'].split('/')[-1] book = activity['target']['id']
status_builder.create_tag(user, book, activity['object']['name']) status_builder.create_tag(user, book, activity['object']['name'])

View file

@ -1,3 +1,4 @@
''' track progress of goodreads imports '''
import re import re
import dateutil.parser import dateutil.parser
@ -5,7 +6,7 @@ from django.db import models
from django.utils import timezone from django.utils import timezone
from fedireads import books_manager from fedireads import books_manager
from fedireads.models import Edition, ReadThrough, User, Book from fedireads.models import ReadThrough, User, Book
from fedireads.utils.fields import JSONField from fedireads.utils.fields import JSONField
# Mapping goodreads -> fedireads shelf titles. # Mapping goodreads -> fedireads shelf titles.
@ -32,6 +33,7 @@ def construct_search_term(title, author):
return ' '.join([title, author]) return ' '.join([title, author])
class ImportJob(models.Model): class ImportJob(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now)

View file

@ -13,7 +13,6 @@ from fedireads import forms, models, outgoing
from fedireads import goodreads_import from fedireads import goodreads_import
from fedireads.settings import DOMAIN from fedireads.settings import DOMAIN
from fedireads.views import get_user_from_username from fedireads.views import get_user_from_username
from fedireads.books_manager import get_or_create_book
def user_login(request): def user_login(request):

View file

@ -53,23 +53,23 @@ def nodeinfo(request):
status_count = models.Status.objects.filter(user__local=True).count() status_count = models.Status.objects.filter(user__local=True).count()
user_count = models.User.objects.count() user_count = models.User.objects.count()
return JsonResponse({ return JsonResponse({
"version": "2.0", 'version': '2.0',
"software": { 'software': {
"name": "fedireads", 'name': 'fedireads',
"version": "0.0.1" 'version': '0.0.1'
}, },
"protocols": [ 'protocols': [
"activitypub" 'activitypub'
], ],
"usage": { 'usage': {
"users": { 'users': {
"total": user_count, 'total': user_count,
"activeMonth": user_count, # TODO 'activeMonth': user_count, # TODO
"activeHalfyear": user_count, # TODO 'activeHalfyear': user_count, # TODO
}, },
"localPosts": status_count, 'localPosts': status_count,
}, },
"openRegistrations": True, 'openRegistrations': True,
}) })