Skip to content

Commit

Permalink
Use endposition when serializing Quotation
Browse files Browse the repository at this point in the history
  • Loading branch information
dato committed Sep 17, 2023
1 parent 1322a0c commit ce3885d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
13 changes: 11 additions & 2 deletions bookwyrm/models/status.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
""" models for storing different kinds of Activities """
from dataclasses import MISSING
from typing import Optional
import re

from django.apps import apps
Expand Down Expand Up @@ -351,14 +352,22 @@ class Quotation(BookStatus):
blank=True,
)

def _format_position(self) -> Optional[str]:
"""serialize page position"""
beg = self.position
end = self.endposition or 0
if self.position_mode != "PG" or not beg:
return None
return f"pp. {beg}-{end}" if end > beg else f"p. {beg}"

@property
def pure_content(self):
"""indicate the book in question for mastodon (or w/e) users"""
quote = re.sub(r"^<p>", '<p>"', self.quote)
quote = re.sub(r"</p>$", '"</p>', quote)
citation = f'-- <a href="{self.book.remote_id}">"{self.book.title}"</a>'
if self.position_mode == "PG" and self.position and (self.position > 0):
citation += f", p. {self.position}"
if position := self._format_position():
citation += f", {position}"
return f"{quote} <p>{citation}</p>{self.content}"

activity_serializer = activitypub.Quotation
Expand Down
23 changes: 23 additions & 0 deletions bookwyrm/tests/models/test_status_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,29 @@ def test_quotation_to_pure_activity(self, *_):
)
self.assertEqual(activity["attachment"][0]["name"], "Test Edition")

def test_quotation_page_serialization(self, *_):
"""serialization of quotation page position"""
tests = [
("single pos", 7, None, "p. 7"),
("page range", 7, 10, "pp. 7-10"),
]
for desc, beg, end, pages in tests:
with self.subTest(desc):
status = models.Quotation.objects.create(
quote="<p>my quote</p>",
content="",
user=self.local_user,
book=self.book,
position=beg,
endposition=end,
position_mode="PG",
)
activity = status.to_activity(pure=True)
self.assertRegex(
activity["content"],
f'^<p>"my quote"</p> <p>-- <a .+</a>, {pages}</p>$',
)

def test_review_to_activity(self, *_):
"""subclass of the base model version with a "pure" serializer"""
status = models.Review.objects.create(
Expand Down

0 comments on commit ce3885d

Please sign in to comment.