diff --git a/README.md b/README.md
index c8b6e92bf..3db6dd926 100644
--- a/README.md
+++ b/README.md
@@ -20,22 +20,22 @@ You can request an invite to https://bookwyrm.social by [email](mailto:mousereev
## Contributing
-There are many ways you can contribute to this project, regardless of your level of technical expertise.
+There are many ways you can contribute to this project, regardless of your level of technical expertise.
### Feedback and feature requests
Please feel encouraged and welcome to point out bugs, suggestions, feature requests, and ideas for how things ought to work using [GitHub issues](https://github.com/mouse-reeve/bookwyrm/issues).
### Code contributions
-Code contributons are gladly welcomed! If you're not sure where to start, take a look at the ["Good first issue"](https://github.com/mouse-reeve/bookwyrm/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) tag. Because BookWyrm is a small project, there isn't a lot of formal structure, but there is a huge capacity for one-on-one support, which can look like asking questions as you go, pair programming, video chats, et cetera, so please feel free to reach out.
+Code contributions are gladly welcomed! If you're not sure where to start, take a look at the ["Good first issue"](https://github.com/mouse-reeve/bookwyrm/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) tag. Because BookWyrm is a small project, there isn't a lot of formal structure, but there is a huge capacity for one-on-one support, which can look like asking questions as you go, pair programming, video chats, et cetera, so please feel free to reach out.
-If you have questions about the project or contributing, you can seet up a video call during BookWyrm ["office hours"](https://calendly.com/mouse-reeve/30min).
+If you have questions about the project or contributing, you can set up a video call during BookWyrm ["office hours"](https://calendly.com/mouse-reeve/30min).
### Financial Support
BookWyrm is an ad-free passion project with no intentions of seeking out venture funding or corporate financial relationships. If you want to help keep the project going, you can donate to the [Patreon](https://www.patreon.com/bookwyrm), or make a one time gift via [PayPal](https://paypal.me/oulipo).
## About BookWyrm
### What it is and isn't
-BookWyrm is a platform for social reading! You can use it to track what you're reading, review books, and follow your friends. It isn't primarily meant for cataloguing or as a datasource for books, but it does do both of those things to some degree.
+BookWyrm is a platform for social reading! You can use it to track what you're reading, review books, and follow your friends. It isn't primarily meant for cataloguing or as a data-source for books, but it does do both of those things to some degree.
### The role of federation
BookWyrm is built on [ActivityPub](http://activitypub.rocks/). With ActivityPub, it inter-operates with different instances of BookWyrm, and other ActivityPub compliant services, like Mastodon. This means you can run an instance for your book club, and still follow your friend who posts on a server devoted to 20th century Russian speculative fiction. It also means that your friend on mastodon can read and comment on a book review that you post on your BookWyrm instance.
@@ -68,7 +68,7 @@ Since the project is still in its early stages, the features are growing every d
- Private, followers-only, and public privacy levels for posting, shelves, and lists
- Option for users to manually approve followers
- Allow blocking and flagging for moderation
-
+
### The Tech Stack
Web backend
- [Django](https://www.djangoproject.com/) web server
@@ -111,17 +111,17 @@ Once the build is complete, you can access the instance at `localhost:1333`
## Installing in Production
-This project is still young and isn't, at the momoment, very stable, so please procede with caution when running in production.
+This project is still young and isn't, at the moment, very stable, so please proceed with caution when running in production.
### Server setup
- Get a domain name and set up DNS for your server
- - Set your server up with appropriate firewalls for running a web application (this instruction set is tested again Ubuntu 20.04)
+ - Set your server up with appropriate firewalls for running a web application (this instruction set is tested against Ubuntu 20.04)
- Set up an email service (such as mailgun) and the appropriate SMTP/DNS settings
- Install Docker and docker-compose
### Install and configure BookWyrm
-The `production` branch of BookWyrm contains a number of tools not on the `main` branch that are suited for running in production, such as `docker-compose` changes to update the default commands or configuration of containers, and indivudal changes to container config to enable things like SSL or regular backups.
+The `production` branch of BookWyrm contains a number of tools not on the `main` branch that are suited for running in production, such as `docker-compose` changes to update the default commands or configuration of containers, and individual changes to container config to enable things like SSL or regular backups.
Instructions for running BookWyrm in production:
@@ -171,3 +171,4 @@ There are three concepts in the book data model:
- `Edition`, a concrete, actually published version of a book
Whenever a user interacts with a book, they are interacting with a specific edition. Every work has a default edition, but the user can select other editions. Reviews aggregated for all editions of a work when you view an edition's page.
+
diff --git a/bookwyrm/activitypub/__init__.py b/bookwyrm/activitypub/__init__.py
index 510f1f3f4..fdfbb1f06 100644
--- a/bookwyrm/activitypub/__init__.py
+++ b/bookwyrm/activitypub/__init__.py
@@ -2,13 +2,12 @@
import inspect
import sys
-from .base_activity import ActivityEncoder, Signature
+from .base_activity import ActivityEncoder, Signature, naive_parse
from .base_activity import Link, Mention
from .base_activity import ActivitySerializerError, resolve_remote_id
from .image import Image
from .note import Note, GeneratedNote, Article, Comment, Review, Quotation
from .note import Tombstone
-from .interaction import Boost, Like
from .ordered_collection import OrderedCollection, OrderedCollectionPage
from .ordered_collection import BookList, Shelf
from .person import Person, PublicKey
@@ -16,10 +15,15 @@ from .response import ActivitypubResponse
from .book import Edition, Work, Author
from .verbs import Create, Delete, Undo, Update
from .verbs import Follow, Accept, Reject, Block
-from .verbs import Add, AddBook, AddListItem, Remove
+from .verbs import Add, Remove
+from .verbs import Announce, Like
# this creates a list of all the Activity types that we can serialize,
# so when an Activity comes in from outside, we can check if it's known
cls_members = inspect.getmembers(sys.modules[__name__], inspect.isclass)
activity_objects = {c[0]: c[1] for c in cls_members \
if hasattr(c[1], 'to_model')}
+
+def parse(activity_json):
+ ''' figure out what activity this is and parse it '''
+ return naive_parse(activity_objects, activity_json)
diff --git a/bookwyrm/activitypub/base_activity.py b/bookwyrm/activitypub/base_activity.py
index 5f35f1d7e..57f1a7134 100644
--- a/bookwyrm/activitypub/base_activity.py
+++ b/bookwyrm/activitypub/base_activity.py
@@ -40,6 +40,20 @@ class Signature:
signatureValue: str
type: str = 'RsaSignature2017'
+def naive_parse(activity_objects, activity_json, serializer=None):
+ ''' this navigates circular import issues '''
+ if not serializer:
+ if activity_json.get('publicKeyPem'):
+ # ugh
+ activity_json['type'] = 'PublicKey'
+ try:
+ activity_type = activity_json['type']
+ serializer = activity_objects[activity_type]
+ except KeyError as e:
+ raise ActivitySerializerError(e)
+
+ return serializer(activity_objects=activity_objects, **activity_json)
+
@dataclass(init=False)
class ActivityObject:
@@ -47,13 +61,30 @@ class ActivityObject:
id: str
type: str
- def __init__(self, **kwargs):
+ def __init__(self, activity_objects=None, **kwargs):
''' this lets you pass in an object with fields that aren't in the
dataclass, which it ignores. Any field in the dataclass is required or
has a default value '''
for field in fields(self):
try:
value = kwargs[field.name]
+ if value in (None, MISSING):
+ raise KeyError()
+ try:
+ is_subclass = issubclass(field.type, ActivityObject)
+ except TypeError:
+ is_subclass = False
+ # serialize a model obj
+ if hasattr(value, 'to_activity'):
+ value = value.to_activity()
+ # parse a dict into the appropriate activity
+ elif is_subclass and isinstance(value, dict):
+ if activity_objects:
+ value = naive_parse(activity_objects, value)
+ else:
+ value = naive_parse(
+ activity_objects, value, serializer=field.type)
+
except KeyError:
if field.default == MISSING and \
field.default_factory == MISSING:
@@ -63,31 +94,29 @@ class ActivityObject:
setattr(self, field.name, value)
- def to_model(self, model, instance=None, save=True):
+ def to_model(self, model=None, instance=None, allow_create=True, save=True):
''' convert from an activity to a model instance '''
- if self.type != model.activity_serializer.type:
- raise ActivitySerializerError(
- 'Wrong activity type "%s" for activity of type "%s"' % \
- (model.activity_serializer.type,
- self.type)
- )
+ model = model or get_model_from_type(self.type)
- if not isinstance(self, model.activity_serializer):
- raise ActivitySerializerError(
- 'Wrong activity type "%s" for model "%s" (expects "%s")' % \
- (self.__class__,
- model.__name__,
- model.activity_serializer)
- )
+ # only reject statuses if we're potentially creating them
+ if allow_create and \
+ hasattr(model, 'ignore_activity') and \
+ model.ignore_activity(self):
+ return None
- if hasattr(model, 'ignore_activity') and model.ignore_activity(self):
- return instance
+ # check for an existing instance
+ instance = instance or model.find_existing(self.serialize())
- # check for an existing instance, if we're not updating a known obj
- instance = instance or model.find_existing(self.serialize()) or model()
+ if not instance and not allow_create:
+ # so that we don't create when we want to delete or update
+ return None
+ instance = instance or model()
for field in instance.simple_fields:
- field.set_field_from_activity(instance, self)
+ try:
+ field.set_field_from_activity(instance, self)
+ except AttributeError as e:
+ raise ActivitySerializerError(e)
# image fields have to be set after other fields because they can save
# too early and jank up users
@@ -139,7 +168,14 @@ class ActivityObject:
def serialize(self):
''' convert to dictionary with context attr '''
- data = self.__dict__
+ data = self.__dict__.copy()
+ # recursively serialize
+ for (k, v) in data.items():
+ try:
+ if issubclass(type(v), ActivityObject):
+ data[k] = v.serialize()
+ except TypeError:
+ pass
data = {k:v for (k, v) in data.items() if v is not None}
data['@context'] = 'https://www.w3.org/ns/activitystreams'
return data
@@ -182,7 +218,7 @@ def set_related_field(
getattr(model_field, 'activitypub_field'),
instance.remote_id
)
- item = activity.to_model(model)
+ item = activity.to_model()
# if the related field isn't serialized (attachments on Status), then
# we have to set it post-creation
@@ -191,11 +227,24 @@ def set_related_field(
item.save()
-def resolve_remote_id(model, remote_id, refresh=False, save=True):
+def get_model_from_type(activity_type):
+ ''' given the activity, what type of model '''
+ models = apps.get_models()
+ model = [m for m in models if hasattr(m, 'activity_serializer') and \
+ hasattr(m.activity_serializer, 'type') and \
+ m.activity_serializer.type == activity_type]
+ if not model:
+ raise ActivitySerializerError(
+ 'No model found for activity type "%s"' % activity_type)
+ return model[0]
+
+
+def resolve_remote_id(remote_id, model=None, refresh=False, save=True):
''' take a remote_id and return an instance, creating if necessary '''
- result = model.find_existing_by_remote_id(remote_id)
- if result and not refresh:
- return result
+ if model:# a bonus check we can do if we already know the model
+ result = model.find_existing_by_remote_id(remote_id)
+ if result and not refresh:
+ return result
# load the data and create the object
try:
@@ -204,13 +253,15 @@ def resolve_remote_id(model, remote_id, refresh=False, save=True):
raise ActivitySerializerError(
'Could not connect to host for remote_id in %s model: %s' % \
(model.__name__, remote_id))
+ # determine the model implicitly, if not provided
+ if not model:
+ model = get_model_from_type(data.get('type'))
# check for existing items with shared unique identifiers
- if not result:
- result = model.find_existing(data)
- if result and not refresh:
- return result
+ result = model.find_existing(data)
+ if result and not refresh:
+ return result
item = model.activity_serializer(**data)
# if we're refreshing, "result" will be set and we'll update it
- return item.to_model(model, instance=result, save=save)
+ return item.to_model(model=model, instance=result, save=save)
diff --git a/bookwyrm/activitypub/book.py b/bookwyrm/activitypub/book.py
index 680365599..87c40c90a 100644
--- a/bookwyrm/activitypub/book.py
+++ b/bookwyrm/activitypub/book.py
@@ -67,4 +67,4 @@ class Author(ActivityObject):
librarythingKey: str = ''
goodreadsKey: str = ''
wikipediaLink: str = ''
- type: str = 'Person'
+ type: str = 'Author'
diff --git a/bookwyrm/activitypub/interaction.py b/bookwyrm/activitypub/interaction.py
deleted file mode 100644
index 752b2fe3f..000000000
--- a/bookwyrm/activitypub/interaction.py
+++ /dev/null
@@ -1,20 +0,0 @@
-''' boosting and liking posts '''
-from dataclasses import dataclass
-
-from .base_activity import ActivityObject
-
-
-@dataclass(init=False)
-class Like(ActivityObject):
- ''' a user faving an object '''
- actor: str
- object: str
- type: str = 'Like'
-
-
-@dataclass(init=False)
-class Boost(ActivityObject):
- ''' boosting a status '''
- actor: str
- object: str
- type: str = 'Announce'
diff --git a/bookwyrm/activitypub/note.py b/bookwyrm/activitypub/note.py
index 1e0bdcb77..705d6eede 100644
--- a/bookwyrm/activitypub/note.py
+++ b/bookwyrm/activitypub/note.py
@@ -1,6 +1,7 @@
''' note serializer and children thereof '''
from dataclasses import dataclass, field
from typing import Dict, List
+from django.apps import apps
from .base_activity import ActivityObject, Link
from .image import Image
@@ -8,10 +9,13 @@ from .image import Image
@dataclass(init=False)
class Tombstone(ActivityObject):
''' the placeholder for a deleted status '''
- published: str
- deleted: str
type: str = 'Tombstone'
+ def to_model(self, *args, **kwargs):
+ ''' this should never really get serialized, just searched for '''
+ model = apps.get_model('bookwyrm.Status')
+ return model.find_existing_by_remote_id(self.id)
+
@dataclass(init=False)
class Note(ActivityObject):
diff --git a/bookwyrm/activitypub/ordered_collection.py b/bookwyrm/activitypub/ordered_collection.py
index cf6429941..14b35f3cf 100644
--- a/bookwyrm/activitypub/ordered_collection.py
+++ b/bookwyrm/activitypub/ordered_collection.py
@@ -17,6 +17,7 @@ class OrderedCollection(ActivityObject):
@dataclass(init=False)
class OrderedCollectionPrivate(OrderedCollection):
+ ''' an ordered collection with privacy settings '''
to: List[str] = field(default_factory=lambda: [])
cc: List[str] = field(default_factory=lambda: [])
@@ -38,6 +39,6 @@ class OrderedCollectionPage(ActivityObject):
''' structure of an ordered collection activity '''
partOf: str
orderedItems: List
- next: str
- prev: str
+ next: str = None
+ prev: str = None
type: str = 'OrderedCollectionPage'
diff --git a/bookwyrm/activitypub/response.py b/bookwyrm/activitypub/response.py
index bbc44c4de..8f3c050bb 100644
--- a/bookwyrm/activitypub/response.py
+++ b/bookwyrm/activitypub/response.py
@@ -9,7 +9,7 @@ class ActivitypubResponse(JsonResponse):
configures some stuff beforehand. Made to be a drop-in replacement of
JsonResponse.
"""
- def __init__(self, data, encoder=ActivityEncoder, safe=True,
+ def __init__(self, data, encoder=ActivityEncoder, safe=False,
json_dumps_params=None, **kwargs):
if 'content_type' not in kwargs:
diff --git a/bookwyrm/activitypub/verbs.py b/bookwyrm/activitypub/verbs.py
index 190cd7395..1236338b2 100644
--- a/bookwyrm/activitypub/verbs.py
+++ b/bookwyrm/activitypub/verbs.py
@@ -1,10 +1,12 @@
''' undo wrapper activity '''
from dataclasses import dataclass
from typing import List
+from django.apps import apps
-from .base_activity import ActivityObject, Signature
+from .base_activity import ActivityObject, Signature, resolve_remote_id
from .book import Edition
+
@dataclass(init=False)
class Verb(ActivityObject):
''' generic fields for activities - maybe an unecessary level of
@@ -12,6 +14,10 @@ class Verb(ActivityObject):
actor: str
object: ActivityObject
+ def action(self):
+ ''' usually we just want to save, this can be overridden as needed '''
+ self.object.to_model()
+
@dataclass(init=False)
class Create(Verb):
@@ -29,6 +35,12 @@ class Delete(Verb):
cc: List
type: str = 'Delete'
+ def action(self):
+ ''' find and delete the activity object '''
+ obj = self.object.to_model(save=False, allow_create=False)
+ obj.delete()
+
+
@dataclass(init=False)
class Update(Verb):
@@ -36,29 +48,60 @@ class Update(Verb):
to: List
type: str = 'Update'
+ def action(self):
+ ''' update a model instance from the dataclass '''
+ self.object.to_model(allow_create=False)
+
@dataclass(init=False)
class Undo(Verb):
''' Undo an activity '''
type: str = 'Undo'
+ def action(self):
+ ''' find and remove the activity object '''
+ # this is so hacky but it does make it work....
+ # (because you Reject a request and Undo a follow
+ model = None
+ if self.object.type == 'Follow':
+ model = apps.get_model('bookwyrm.UserFollows')
+ obj = self.object.to_model(model=model, save=False, allow_create=False)
+ obj.delete()
+
@dataclass(init=False)
class Follow(Verb):
''' Follow activity '''
+ object: str
type: str = 'Follow'
+ def action(self):
+ ''' relationship save '''
+ self.to_model()
+
+
@dataclass(init=False)
class Block(Verb):
''' Block activity '''
+ object: str
type: str = 'Block'
+ def action(self):
+ ''' relationship save '''
+ self.to_model()
+
+
@dataclass(init=False)
class Accept(Verb):
''' Accept activity '''
object: Follow
type: str = 'Accept'
+ def action(self):
+ ''' find and remove the activity object '''
+ obj = self.object.to_model(save=False, allow_create=False)
+ obj.accept()
+
@dataclass(init=False)
class Reject(Verb):
@@ -66,32 +109,60 @@ class Reject(Verb):
object: Follow
type: str = 'Reject'
+ def action(self):
+ ''' find and remove the activity object '''
+ obj = self.object.to_model(save=False, allow_create=False)
+ obj.reject()
+
@dataclass(init=False)
class Add(Verb):
'''Add activity '''
target: str
- object: ActivityObject
- type: str = 'Add'
-
-
-@dataclass(init=False)
-class AddBook(Add):
- '''Add activity that's aware of the book obj '''
object: Edition
type: str = 'Add'
-
-
-@dataclass(init=False)
-class AddListItem(AddBook):
- '''Add activity that's aware of the book obj '''
notes: str = None
order: int = 0
approved: bool = True
+ def action(self):
+ ''' add obj to collection '''
+ target = resolve_remote_id(self.target, refresh=False)
+ # we want to related field that isn't the book, this is janky af sorry
+ model = [t for t in type(target)._meta.related_objects \
+ if t.name != 'edition'][0].related_model
+ self.to_model(model=model)
+
@dataclass(init=False)
class Remove(Verb):
'''Remove activity '''
target: ActivityObject
type: str = 'Remove'
+
+ def action(self):
+ ''' find and remove the activity object '''
+ obj = self.object.to_model(save=False, allow_create=False)
+ obj.delete()
+
+
+@dataclass(init=False)
+class Like(Verb):
+ ''' a user faving an object '''
+ object: str
+ type: str = 'Like'
+
+ def action(self):
+ ''' like '''
+ self.to_model()
+
+
+@dataclass(init=False)
+class Announce(Verb):
+ ''' boosting a status '''
+ object: str
+ type: str = 'Announce'
+
+ def action(self):
+ ''' boost '''
+ self.to_model()
diff --git a/bookwyrm/connectors/abstract_connector.py b/bookwyrm/connectors/abstract_connector.py
index 5ccd9f91d..68ff2a483 100644
--- a/bookwyrm/connectors/abstract_connector.py
+++ b/bookwyrm/connectors/abstract_connector.py
@@ -127,7 +127,7 @@ class AbstractConnector(AbstractMinimalConnector):
# create activitypub object
work_activity = activitypub.Work(**work_data)
# this will dedupe automatically
- work = work_activity.to_model(models.Work)
+ work = work_activity.to_model(model=models.Work)
for author in self.get_authors_from_data(data):
work.authors.add(author)
@@ -141,7 +141,7 @@ class AbstractConnector(AbstractMinimalConnector):
mapped_data = dict_from_mappings(edition_data, self.book_mappings)
mapped_data['work'] = work.remote_id
edition_activity = activitypub.Edition(**mapped_data)
- edition = edition_activity.to_model(models.Edition)
+ edition = edition_activity.to_model(model=models.Edition)
edition.connector = self.connector
edition.save()
@@ -168,7 +168,7 @@ class AbstractConnector(AbstractMinimalConnector):
mapped_data = dict_from_mappings(data, self.author_mappings)
activity = activitypub.Author(**mapped_data)
# this will dedupe
- return activity.to_model(models.Author)
+ return activity.to_model(model=models.Author)
@abstractmethod
diff --git a/bookwyrm/connectors/bookwyrm_connector.py b/bookwyrm/connectors/bookwyrm_connector.py
index 1f877993d..00e6c62f1 100644
--- a/bookwyrm/connectors/bookwyrm_connector.py
+++ b/bookwyrm/connectors/bookwyrm_connector.py
@@ -7,7 +7,7 @@ class Connector(AbstractMinimalConnector):
''' this is basically just for search '''
def get_or_create_book(self, remote_id):
- edition = activitypub.resolve_remote_id(models.Edition, remote_id)
+ edition = activitypub.resolve_remote_id(remote_id, model=models.Edition)
work = edition.parent_work
work.default_edition = work.get_default_edition()
work.save()
diff --git a/bookwyrm/incoming.py b/bookwyrm/incoming.py
deleted file mode 100644
index e0e690550..000000000
--- a/bookwyrm/incoming.py
+++ /dev/null
@@ -1,360 +0,0 @@
-''' handles all of the activity coming in to the server '''
-import json
-from urllib.parse import urldefrag
-
-import django.db.utils
-from django.http import HttpResponse
-from django.http import HttpResponseBadRequest, HttpResponseNotFound
-from django.views.decorators.csrf import csrf_exempt
-from django.views.decorators.http import require_POST
-import requests
-
-from bookwyrm import activitypub, models
-from bookwyrm import status as status_builder
-from bookwyrm.tasks import app
-from bookwyrm.signatures import Signature
-
-
-@csrf_exempt
-@require_POST
-def inbox(request, username):
- ''' incoming activitypub events '''
- try:
- models.User.objects.get(localname=username)
- except models.User.DoesNotExist:
- return HttpResponseNotFound()
-
- return shared_inbox(request)
-
-
-@csrf_exempt
-@require_POST
-def shared_inbox(request):
- ''' incoming activitypub events '''
- try:
- resp = request.body
- activity = json.loads(resp)
- if isinstance(activity, str):
- activity = json.loads(activity)
- activity_object = activity['object']
- except (json.decoder.JSONDecodeError, KeyError):
- return HttpResponseBadRequest()
-
- if not has_valid_signature(request, activity):
- if activity['type'] == 'Delete':
- # Pretend that unauth'd deletes succeed. Auth may be failing because
- # the resource or owner of the resource might have been deleted.
- return HttpResponse()
- return HttpResponse(status=401)
-
- # if this isn't a file ripe for refactor, I don't know what is.
- handlers = {
- 'Follow': handle_follow,
- 'Accept': handle_follow_accept,
- 'Reject': handle_follow_reject,
- 'Block': handle_block,
- 'Create': {
- 'BookList': handle_create_list,
- 'Note': handle_create_status,
- 'Article': handle_create_status,
- 'Review': handle_create_status,
- 'Comment': handle_create_status,
- 'Quotation': handle_create_status,
- },
- 'Delete': handle_delete_status,
- 'Like': handle_favorite,
- 'Announce': handle_boost,
- 'Add': {
- 'Edition': handle_add,
- },
- 'Undo': {
- 'Follow': handle_unfollow,
- 'Like': handle_unfavorite,
- 'Announce': handle_unboost,
- 'Block': handle_unblock,
- },
- 'Update': {
- 'Person': handle_update_user,
- 'Edition': handle_update_edition,
- 'Work': handle_update_work,
- 'BookList': handle_update_list,
- },
- }
- activity_type = activity['type']
-
- handler = handlers.get(activity_type, None)
- if isinstance(handler, dict):
- handler = handler.get(activity_object['type'], None)
-
- if not handler:
- return HttpResponseNotFound()
-
- handler.delay(activity)
- return HttpResponse()
-
-
-def has_valid_signature(request, activity):
- ''' verify incoming signature '''
- try:
- signature = Signature.parse(request)
-
- key_actor = urldefrag(signature.key_id).url
- if key_actor != activity.get('actor'):
- raise ValueError("Wrong actor created signature.")
-
- remote_user = activitypub.resolve_remote_id(models.User, key_actor)
- if not remote_user:
- return False
-
- try:
- signature.verify(remote_user.key_pair.public_key, request)
- except ValueError:
- old_key = remote_user.key_pair.public_key
- remote_user = activitypub.resolve_remote_id(
- models.User, remote_user.remote_id, refresh=True
- )
- if remote_user.key_pair.public_key == old_key:
- raise # Key unchanged.
- signature.verify(remote_user.key_pair.public_key, request)
- except (ValueError, requests.exceptions.HTTPError):
- return False
- return True
-
-
-@app.task
-def handle_follow(activity):
- ''' someone wants to follow a local user '''
- try:
- relationship = activitypub.Follow(
- **activity
- ).to_model(models.UserFollowRequest)
- except django.db.utils.IntegrityError as err:
- if err.__cause__.diag.constraint_name != 'userfollowrequest_unique':
- raise
- relationship = models.UserFollowRequest.objects.get(
- remote_id=activity['id']
- )
- # send the accept normally for a duplicate request
-
- if not relationship.user_object.manually_approves_followers:
- relationship.accept()
-
-
-@app.task
-def handle_unfollow(activity):
- ''' unfollow a local user '''
- obj = activity['object']
- requester = activitypub.resolve_remote_id(models.User, obj['actor'])
- to_unfollow = models.User.objects.get(remote_id=obj['object'])
- # raises models.User.DoesNotExist
-
- to_unfollow.followers.remove(requester)
-
-
-@app.task
-def handle_follow_accept(activity):
- ''' hurray, someone remote accepted a follow request '''
- # figure out who they want to follow
- requester = models.User.objects.get(remote_id=activity['object']['actor'])
- # figure out who they are
- accepter = activitypub.resolve_remote_id(models.User, activity['actor'])
-
- try:
- request = models.UserFollowRequest.objects.get(
- user_subject=requester,
- user_object=accepter
- )
- request.delete()
- except models.UserFollowRequest.DoesNotExist:
- pass
- accepter.followers.add(requester)
-
-
-@app.task
-def handle_follow_reject(activity):
- ''' someone is rejecting a follow request '''
- requester = models.User.objects.get(remote_id=activity['object']['actor'])
- rejecter = activitypub.resolve_remote_id(models.User, activity['actor'])
-
- request = models.UserFollowRequest.objects.get(
- user_subject=requester,
- user_object=rejecter
- )
- request.delete()
- #raises models.UserFollowRequest.DoesNotExist
-
-@app.task
-def handle_block(activity):
- ''' blocking a user '''
- # create "block" databse entry
- activitypub.Block(**activity).to_model(models.UserBlocks)
- # the removing relationships is handled in model save
-
-
-@app.task
-def handle_unblock(activity):
- ''' undoing a block '''
- try:
- block_id = activity['object']['id']
- except KeyError:
- return
- try:
- block = models.UserBlocks.objects.get(remote_id=block_id)
- except models.UserBlocks.DoesNotExist:
- return
- block.delete()
-
-
-@app.task
-def handle_create_list(activity):
- ''' a new list '''
- activity = activity['object']
- activitypub.BookList(**activity).to_model(models.List)
-
-
-@app.task
-def handle_update_list(activity):
- ''' update a list '''
- try:
- book_list = models.List.objects.get(remote_id=activity['object']['id'])
- except models.List.DoesNotExist:
- book_list = None
- activitypub.BookList(
- **activity['object']).to_model(models.List, instance=book_list)
-
-
-@app.task
-def handle_create_status(activity):
- ''' someone did something, good on them '''
- # deduplicate incoming activities
- activity = activity['object']
- status_id = activity.get('id')
- if models.Status.objects.filter(remote_id=status_id).count():
- return
-
- try:
- serializer = activitypub.activity_objects[activity['type']]
- except KeyError:
- return
-
- activity = serializer(**activity)
- try:
- model = models.activity_models[activity.type]
- except KeyError:
- # not a type of status we are prepared to deserialize
- return
-
- status = activity.to_model(model)
- if not status:
- # it was discarded because it's not a bookwyrm type
- return
-
-
-@app.task
-def handle_delete_status(activity):
- ''' remove a status '''
- try:
- status_id = activity['object']['id']
- except TypeError:
- # this isn't a great fix, because you hit this when mastadon
- # is trying to delete a user.
- return
- try:
- status = models.Status.objects.get(
- remote_id=status_id
- )
- except models.Status.DoesNotExist:
- return
- models.Notification.objects.filter(related_status=status).all().delete()
- status_builder.delete_status(status)
-
-
-@app.task
-def handle_favorite(activity):
- ''' approval of your good good post '''
- fav = activitypub.Like(**activity)
- # we dont know this status, we don't care about this status
- if not models.Status.objects.filter(remote_id=fav.object).exists():
- return
-
- fav = fav.to_model(models.Favorite)
- if fav.user.local:
- return
-
-
-@app.task
-def handle_unfavorite(activity):
- ''' approval of your good good post '''
- like = models.Favorite.objects.filter(
- remote_id=activity['object']['id']
- ).first()
- if not like:
- return
- like.delete()
-
-
-@app.task
-def handle_boost(activity):
- ''' someone gave us a boost! '''
- try:
- activitypub.Boost(**activity).to_model(models.Boost)
- except activitypub.ActivitySerializerError:
- # this probably just means we tried to boost an unknown status
- return
-
-
-@app.task
-def handle_unboost(activity):
- ''' someone gave us a boost! '''
- boost = models.Boost.objects.filter(
- remote_id=activity['object']['id']
- ).first()
- if boost:
- boost.delete()
-
-
-@app.task
-def handle_add(activity):
- ''' putting a book on a shelf '''
- #this is janky as heck but I haven't thought of a better solution
- try:
- activitypub.AddBook(**activity).to_model(models.ShelfBook)
- return
- except activitypub.ActivitySerializerError:
- pass
- try:
- activitypub.AddListItem(**activity).to_model(models.ListItem)
- return
- except activitypub.ActivitySerializerError:
- pass
- try:
- activitypub.AddBook(**activity).to_model(models.UserTag)
- return
- except activitypub.ActivitySerializerError:
- pass
-
-
-@app.task
-def handle_update_user(activity):
- ''' receive an updated user Person activity object '''
- try:
- user = models.User.objects.get(remote_id=activity['object']['id'])
- except models.User.DoesNotExist:
- # who is this person? who cares
- return
- activitypub.Person(
- **activity['object']
- ).to_model(models.User, instance=user)
- # model save() happens in the to_model function
-
-
-@app.task
-def handle_update_edition(activity):
- ''' a remote instance changed a book (Document) '''
- activitypub.Edition(**activity['object']).to_model(models.Edition)
-
-
-@app.task
-def handle_update_work(activity):
- ''' a remote instance changed a book (Document) '''
- activitypub.Work(**activity['object']).to_model(models.Work)
diff --git a/bookwyrm/migrations/0046_sitesettings_privacy_policy.py b/bookwyrm/migrations/0046_sitesettings_privacy_policy.py
new file mode 100644
index 000000000..0c49d607c
--- /dev/null
+++ b/bookwyrm/migrations/0046_sitesettings_privacy_policy.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.0.7 on 2021-02-27 19:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('bookwyrm', '0045_auto_20210210_2114'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='sitesettings',
+ name='privacy_policy',
+ field=models.TextField(default='Add a privacy policy here.'),
+ ),
+ ]
diff --git a/bookwyrm/models/activitypub_mixin.py b/bookwyrm/models/activitypub_mixin.py
index 2c2e5a72d..bebe00d02 100644
--- a/bookwyrm/models/activitypub_mixin.py
+++ b/bookwyrm/models/activitypub_mixin.py
@@ -157,10 +157,14 @@ class ActivitypubMixin:
return recipients
- def to_activity(self):
+ def to_activity_dataclass(self):
''' convert from a model to an activity '''
activity = generate_activity(self)
- return self.activity_serializer(**activity).serialize()
+ return self.activity_serializer(**activity)
+
+ def to_activity(self, **kwargs): # pylint: disable=unused-argument
+ ''' convert from a model to a json activity '''
+ return self.to_activity_dataclass().serialize()
class ObjectMixin(ActivitypubMixin):
@@ -188,7 +192,7 @@ class ObjectMixin(ActivitypubMixin):
try:
software = None
- # do we have a "pure" activitypub version of this for mastodon?
+ # do we have a "pure" activitypub version of this for mastodon?
if hasattr(self, 'pure_content'):
pure_activity = self.to_create_activity(user, pure=True)
self.broadcast(pure_activity, user, software='other')
@@ -196,7 +200,7 @@ class ObjectMixin(ActivitypubMixin):
# sends to BW only if we just did a pure version for masto
activity = self.to_create_activity(user)
self.broadcast(activity, user, software=software)
- except KeyError:
+ except AttributeError:
# janky as heck, this catches the mutliple inheritence chain
# for boosts and ignores this auxilliary broadcast
return
@@ -225,26 +229,26 @@ class ObjectMixin(ActivitypubMixin):
def to_create_activity(self, user, **kwargs):
''' returns the object wrapped in a Create activity '''
- activity_object = self.to_activity(**kwargs)
+ activity_object = self.to_activity_dataclass(**kwargs)
signature = None
create_id = self.remote_id + '/activity'
- if 'content' in activity_object and activity_object['content']:
+ if hasattr(activity_object, 'content') and activity_object.content:
signer = pkcs1_15.new(RSA.import_key(user.key_pair.private_key))
- content = activity_object['content']
+ content = activity_object.content
signed_message = signer.sign(SHA256.new(content.encode('utf8')))
signature = activitypub.Signature(
creator='%s#main-key' % user.remote_id,
- created=activity_object['published'],
+ created=activity_object.published,
signatureValue=b64encode(signed_message).decode('utf8')
)
return activitypub.Create(
id=create_id,
actor=user.remote_id,
- to=activity_object['to'],
- cc=activity_object['cc'],
+ to=activity_object.to,
+ cc=activity_object.cc,
object=activity_object,
signature=signature,
).serialize()
@@ -257,7 +261,7 @@ class ObjectMixin(ActivitypubMixin):
actor=user.remote_id,
to=['%s/followers' % user.remote_id],
cc=['https://www.w3.org/ns/activitystreams#Public'],
- object=self.to_activity(),
+ object=self,
).serialize()
@@ -268,7 +272,7 @@ class ObjectMixin(ActivitypubMixin):
id=activity_id,
actor=user.remote_id,
to=['https://www.w3.org/ns/activitystreams#Public'],
- object=self.to_activity()
+ object=self
).serialize()
@@ -283,7 +287,7 @@ class OrderedCollectionPageMixin(ObjectMixin):
def to_ordered_collection(self, queryset, \
remote_id=None, page=False, collection_only=False, **kwargs):
- 'pure=pure, '' an ordered collection of whatevers '''
+ ''' an ordered collection of whatevers '''
if not queryset.ordered:
raise RuntimeError('queryset must be ordered')
@@ -309,7 +313,7 @@ class OrderedCollectionPageMixin(ObjectMixin):
activity['first'] = '%s?page=1' % remote_id
activity['last'] = '%s?page=%d' % (remote_id, paginated.num_pages)
- return serializer(**activity).serialize()
+ return serializer(**activity)
class OrderedCollectionMixin(OrderedCollectionPageMixin):
@@ -321,9 +325,13 @@ class OrderedCollectionMixin(OrderedCollectionPageMixin):
activity_serializer = activitypub.OrderedCollection
+ def to_activity_dataclass(self, **kwargs):
+ return self.to_ordered_collection(self.collection_queryset, **kwargs)
+
def to_activity(self, **kwargs):
''' an ordered collection of the specified model queryset '''
- return self.to_ordered_collection(self.collection_queryset, **kwargs)
+ return self.to_ordered_collection(
+ self.collection_queryset, **kwargs).serialize()
class CollectionItemMixin(ActivitypubMixin):
@@ -360,7 +368,7 @@ class CollectionItemMixin(ActivitypubMixin):
return activitypub.Add(
id='%s#add' % self.remote_id,
actor=self.user.remote_id,
- object=object_field.to_activity(),
+ object=object_field,
target=collection_field.remote_id
).serialize()
@@ -371,7 +379,7 @@ class CollectionItemMixin(ActivitypubMixin):
return activitypub.Remove(
id='%s#remove' % self.remote_id,
actor=self.user.remote_id,
- object=object_field.to_activity(),
+ object=object_field,
target=collection_field.remote_id
).serialize()
@@ -400,7 +408,7 @@ class ActivityMixin(ActivitypubMixin):
return activitypub.Undo(
id='%s#undo' % self.remote_id,
actor=user.remote_id,
- object=self.to_activity()
+ object=self,
).serialize()
@@ -495,4 +503,4 @@ def to_ordered_collection_page(
orderedItems=items,
next=next_page,
prev=prev_page
- ).serialize()
+ )
diff --git a/bookwyrm/models/fields.py b/bookwyrm/models/fields.py
index 55de1fab2..4ea527eba 100644
--- a/bookwyrm/models/fields.py
+++ b/bookwyrm/models/fields.py
@@ -122,13 +122,12 @@ class ActivitypubRelatedFieldMixin(ActivitypubFieldMixin):
return None
related_model = self.related_model
- if isinstance(value, dict) and value.get('id'):
+ if hasattr(value, 'id') and value.id:
if not self.load_remote:
# only look in the local database
- return related_model.find_existing(value)
+ return related_model.find_existing(value.serialize())
# this is an activitypub object, which we can deserialize
- activity_serializer = related_model.activity_serializer
- return activity_serializer(**value).to_model(related_model)
+ return value.to_model(model=related_model)
try:
# make sure the value looks like a remote id
validate_remote_id(value)
@@ -139,7 +138,7 @@ class ActivitypubRelatedFieldMixin(ActivitypubFieldMixin):
if not self.load_remote:
# only look in the local database
return related_model.find_existing_by_remote_id(value)
- return activitypub.resolve_remote_id(related_model, value)
+ return activitypub.resolve_remote_id(value, model=related_model)
class RemoteIdField(ActivitypubFieldMixin, models.CharField):
@@ -280,7 +279,8 @@ class ManyToManyField(ActivitypubFieldMixin, models.ManyToManyField):
except ValidationError:
continue
items.append(
- activitypub.resolve_remote_id(self.related_model, remote_id)
+ activitypub.resolve_remote_id(
+ remote_id, model=self.related_model)
)
return items
@@ -317,7 +317,8 @@ class TagField(ManyToManyField):
# tags can contain multiple types
continue
items.append(
- activitypub.resolve_remote_id(self.related_model, link.href)
+ activitypub.resolve_remote_id(
+ link.href, model=self.related_model)
)
return items
@@ -366,8 +367,8 @@ class ImageField(ActivitypubFieldMixin, models.ImageField):
image_slug = value
# when it's an inline image (User avatar/icon, Book cover), it's a json
# blob, but when it's an attached image, it's just a url
- if isinstance(image_slug, dict):
- url = image_slug.get('url')
+ if hasattr(image_slug, 'url'):
+ url = image_slug.url
elif isinstance(image_slug, str):
url = image_slug
else:
diff --git a/bookwyrm/models/list.py b/bookwyrm/models/list.py
index ef48ed956..1b14c2aa5 100644
--- a/bookwyrm/models/list.py
+++ b/bookwyrm/models/list.py
@@ -68,7 +68,7 @@ class ListItem(CollectionItemMixin, BookWyrmModel):
order = fields.IntegerField(blank=True, null=True)
endorsement = models.ManyToManyField('User', related_name='endorsers')
- activity_serializer = activitypub.AddListItem
+ activity_serializer = activitypub.Add
object_field = 'book'
collection_field = 'book_list'
diff --git a/bookwyrm/models/relationship.py b/bookwyrm/models/relationship.py
index f4df3b83f..3b0e85d41 100644
--- a/bookwyrm/models/relationship.py
+++ b/bookwyrm/models/relationship.py
@@ -5,6 +5,7 @@ from django.db.models import Q
from bookwyrm import activitypub
from .activitypub_mixin import ActivitypubMixin, ActivityMixin
+from .activitypub_mixin import generate_activity
from .base_model import BookWyrmModel
from . import fields
@@ -55,10 +56,13 @@ class UserRelationship(BookWyrmModel):
return '%s#%s/%d' % (base_path, status, self.id)
-class UserFollows(ActivitypubMixin, UserRelationship):
+class UserFollows(ActivityMixin, UserRelationship):
''' Following a user '''
status = 'follows'
- activity_serializer = activitypub.Follow
+
+ def to_activity(self):
+ ''' overrides default to manually set serializer '''
+ return activitypub.Follow(**generate_activity(self))
def save(self, *args, **kwargs):
''' really really don't let a user follow someone who blocked them '''
@@ -73,7 +77,9 @@ class UserFollows(ActivitypubMixin, UserRelationship):
)
).exists():
raise IntegrityError()
- super().save(*args, **kwargs)
+ # don't broadcast this type of relationship -- accepts and requests
+ # are handled by the UserFollowRequest model
+ super().save(*args, broadcast=False, **kwargs)
@classmethod
def from_request(cls, follow_request):
@@ -109,16 +115,19 @@ class UserFollowRequest(ActivitypubMixin, UserRelationship):
)
).exists():
raise IntegrityError()
-
super().save(*args, **kwargs)
if broadcast and self.user_subject.local and not self.user_object.local:
self.broadcast(self.to_activity(), self.user_subject)
if self.user_object.local:
+ manually_approves = self.user_object.manually_approves_followers
+ if not manually_approves:
+ self.accept()
+
model = apps.get_model('bookwyrm.Notification', require_ready=True)
- notification_type = 'FOLLOW_REQUEST' \
- if self.user_object.manually_approves_followers else 'FOLLOW'
+ notification_type = 'FOLLOW_REQUEST' if \
+ manually_approves else 'FOLLOW'
model.objects.create(
user=self.user_object,
related_user=self.user_subject,
@@ -129,28 +138,30 @@ class UserFollowRequest(ActivitypubMixin, UserRelationship):
def accept(self):
''' turn this request into the real deal'''
user = self.user_object
- activity = activitypub.Accept(
- id=self.get_remote_id(status='accepts'),
- actor=self.user_object.remote_id,
- object=self.to_activity()
- ).serialize()
+ if not self.user_subject.local:
+ activity = activitypub.Accept(
+ id=self.get_remote_id(status='accepts'),
+ actor=self.user_object.remote_id,
+ object=self.to_activity()
+ ).serialize()
+ self.broadcast(activity, user)
with transaction.atomic():
UserFollows.from_request(self)
self.delete()
- self.broadcast(activity, user)
def reject(self):
''' generate a Reject for this follow request '''
- user = self.user_object
- activity = activitypub.Reject(
- id=self.get_remote_id(status='rejects'),
- actor=self.user_object.remote_id,
- object=self.to_activity()
- ).serialize()
+ if self.user_object.local:
+ activity = activitypub.Reject(
+ id=self.get_remote_id(status='rejects'),
+ actor=self.user_object.remote_id,
+ object=self.to_activity()
+ ).serialize()
+ self.broadcast(activity, self.user_object)
+
self.delete()
- self.broadcast(activity, user)
class UserBlocks(ActivityMixin, UserRelationship):
diff --git a/bookwyrm/models/shelf.py b/bookwyrm/models/shelf.py
index 921b8617c..dfb8b9b31 100644
--- a/bookwyrm/models/shelf.py
+++ b/bookwyrm/models/shelf.py
@@ -57,7 +57,7 @@ class ShelfBook(CollectionItemMixin, BookWyrmModel):
user = fields.ForeignKey(
'User', on_delete=models.PROTECT, activitypub_field='actor')
- activity_serializer = activitypub.AddBook
+ activity_serializer = activitypub.Add
object_field = 'book'
collection_field = 'shelf'
diff --git a/bookwyrm/models/site.py b/bookwyrm/models/site.py
index 4670bd948..d39718b30 100644
--- a/bookwyrm/models/site.py
+++ b/bookwyrm/models/site.py
@@ -20,6 +20,8 @@ class SiteSettings(models.Model):
default='Contact an administrator to get an invite')
code_of_conduct = models.TextField(
default='Add a code of conduct here.')
+ privacy_policy = models.TextField(
+ default='Add a privacy policy here.')
allow_registration = models.BooleanField(default=True)
logo = models.ImageField(
upload_to='logos/', null=True, blank=True
diff --git a/bookwyrm/models/status.py b/bookwyrm/models/status.py
index 62effeb88..ba9727f58 100644
--- a/bookwyrm/models/status.py
+++ b/bookwyrm/models/status.py
@@ -84,6 +84,16 @@ class Status(OrderedCollectionPageMixin, BookWyrmModel):
related_status=self,
)
+ def delete(self, *args, **kwargs):#pylint: disable=unused-argument
+ ''' "delete" a status '''
+ if hasattr(self, 'boosted_status'):
+ # okay but if it's a boost really delete it
+ super().delete(*args, **kwargs)
+ return
+ self.deleted = True
+ self.deleted_date = timezone.now()
+ self.save()
+
@property
def recipients(self):
''' tagged users who definitely need to get this status in broadcast '''
@@ -96,6 +106,12 @@ class Status(OrderedCollectionPageMixin, BookWyrmModel):
@classmethod
def ignore_activity(cls, activity):
''' keep notes if they are replies to existing statuses '''
+ if activity.type == 'Announce':
+ # keep it if the booster or the boosted are local
+ boosted = activitypub.resolve_remote_id(activity.object, save=False)
+ return cls.ignore_activity(boosted.to_activity_dataclass())
+
+ # keep if it if it's a custom type
if activity.type != 'Note':
return False
if cls.objects.filter(
@@ -106,8 +122,8 @@ class Status(OrderedCollectionPageMixin, BookWyrmModel):
if activity.tag == MISSING or activity.tag is None:
return True
tags = [l['href'] for l in activity.tag if l['type'] == 'Mention']
+ user_model = apps.get_model('bookwyrm.User', require_ready=True)
for tag in tags:
- user_model = apps.get_model('bookwyrm.User', require_ready=True)
if user_model.objects.filter(
remote_id=tag, local=True).exists():
# we found a mention of a known use boost
@@ -139,9 +155,9 @@ class Status(OrderedCollectionPageMixin, BookWyrmModel):
remote_id='%s/replies' % self.remote_id,
collection_only=True,
**kwargs
- )
+ ).serialize()
- def to_activity(self, pure=False):# pylint: disable=arguments-differ
+ def to_activity_dataclass(self, pure=False):# pylint: disable=arguments-differ
''' return tombstone if the status is deleted '''
if self.deleted:
return activitypub.Tombstone(
@@ -149,25 +165,29 @@ class Status(OrderedCollectionPageMixin, BookWyrmModel):
url=self.remote_id,
deleted=self.deleted_date.isoformat(),
published=self.deleted_date.isoformat()
- ).serialize()
- activity = ActivitypubMixin.to_activity(self)
- activity['replies'] = self.to_replies()
+ )
+ activity = ActivitypubMixin.to_activity_dataclass(self)
+ activity.replies = self.to_replies()
# "pure" serialization for non-bookwyrm instances
if pure and hasattr(self, 'pure_content'):
- activity['content'] = self.pure_content
- if 'name' in activity:
- activity['name'] = self.pure_name
- activity['type'] = self.pure_type
- activity['attachment'] = [
+ activity.content = self.pure_content
+ if hasattr(activity, 'name'):
+ activity.name = self.pure_name
+ activity.type = self.pure_type
+ activity.attachment = [
image_serializer(b.cover, b.alt_text) \
for b in self.mention_books.all()[:4] if b.cover]
if hasattr(self, 'book') and self.book.cover:
- activity['attachment'].append(
+ activity.attachment.append(
image_serializer(self.book.cover, self.book.alt_text)
)
return activity
+ def to_activity(self, pure=False):# pylint: disable=arguments-differ
+ ''' json serialized activitypub class '''
+ return self.to_activity_dataclass(pure=pure).serialize()
+
class GeneratedNote(Status):
''' these are app-generated messages about user activity '''
@@ -266,7 +286,7 @@ class Boost(ActivityMixin, Status):
related_name='boosters',
activitypub_field='object',
)
- activity_serializer = activitypub.Boost
+ activity_serializer = activitypub.Announce
def save(self, *args, **kwargs):
''' save and notify '''
diff --git a/bookwyrm/models/tag.py b/bookwyrm/models/tag.py
index d75f6e050..83359170a 100644
--- a/bookwyrm/models/tag.py
+++ b/bookwyrm/models/tag.py
@@ -1,6 +1,7 @@
''' models for storing different kinds of Activities '''
import urllib.parse
+from django.apps import apps
from django.db import models
from bookwyrm import activitypub
@@ -15,17 +16,15 @@ class Tag(OrderedCollectionMixin, BookWyrmModel):
name = fields.CharField(max_length=100, unique=True)
identifier = models.CharField(max_length=100)
- @classmethod
- def book_queryset(cls, identifier):
- ''' county of books associated with this tag '''
- return cls.objects.filter(
- identifier=identifier
- ).order_by('-updated_date')
-
@property
- def collection_queryset(self):
- ''' books associated with this tag '''
- return self.book_queryset(self.identifier)
+ def books(self):
+ ''' count of books associated with this tag '''
+ edition_model = apps.get_model('bookwyrm.Edition', require_ready=True)
+ return edition_model.objects.filter(
+ usertag__tag__identifier=self.identifier
+ ).order_by('-created_date').distinct()
+
+ collection_queryset = books
def get_remote_id(self):
''' tag should use identifier not id in remote_id '''
@@ -50,7 +49,7 @@ class UserTag(CollectionItemMixin, BookWyrmModel):
tag = fields.ForeignKey(
'Tag', on_delete=models.PROTECT, activitypub_field='target')
- activity_serializer = activitypub.AddBook
+ activity_serializer = activitypub.Add
object_field = 'book'
collection_field = 'tag'
diff --git a/bookwyrm/models/user.py b/bookwyrm/models/user.py
index 9a6e6d665..f137236c0 100644
--- a/bookwyrm/models/user.py
+++ b/bookwyrm/models/user.py
@@ -140,7 +140,7 @@ class User(OrderedCollectionPageMixin, AbstractUser):
privacy__in=['public', 'unlisted'],
).select_subclasses().order_by('-published_date')
return self.to_ordered_collection(queryset, \
- collection_only=True, remote_id=self.outbox, **kwargs)
+ collection_only=True, remote_id=self.outbox, **kwargs).serialize()
def to_following_activity(self, **kwargs):
''' activitypub following list '''
@@ -375,4 +375,4 @@ def get_remote_reviews(outbox):
for activity in data['orderedItems']:
if not activity['type'] == 'Review':
continue
- activitypub.Review(**activity).to_model(Review)
+ activitypub.Review(**activity).to_model()
diff --git a/bookwyrm/templates/discover/about.html b/bookwyrm/templates/discover/about.html
index 091158070..9d3f66dcb 100644
--- a/bookwyrm/templates/discover/about.html
+++ b/bookwyrm/templates/discover/about.html
@@ -1,21 +1,35 @@
-{% extends 'layout.html' %}
-{% block content %}
+{% extends 'discover/landing_layout.html' %}
+{% block panel %}
-{{ site.name }}
- {{ site.instance_tagline }}
-
{{ site.registration_closed_text | safe}}
- {% endif %} -{{ site.registration_closed_text | safe}}
+ {% endif %} +{% if user.name %}{{ user.name }}{% else %}{{ user.localname }}{% endif %}
+ +Joined {{ user.created_date | naturaltime }}
++ {{ user.followers.count }} follower{{ user.followers.count | pluralize }}, + {{ user.following.count }} following +
+{{ user.summary | to_markdown | safe }}-