+ if self.mode == 'text':
+ return f'{self.book.slug}/{self.anchor}'
+ else:
+ return f'{self.book.slug}/audio/{self.audio_timestamp}'
+
+ @classmethod
+ def get_by_location(cls, user, location, create=False):
+ Book = apps.get_model('catalogue', 'Book')
+ try:
+ slug, anchor = location.split('/', 1)
+ except:
+ return None
+ if '/' in anchor:
+ try:
+ mode, audio_timestamp = anchor.split('/', 1)
+ assert mode == 'audio'
+ audio_timestamp = int(audio_timestamp)
+ except:
+ return None
+ anchor = ''
+ instance = cls.objects.filter(
+ user=user,
+ book__slug=slug,
+ mode=mode,
+ audio_timestamp=audio_timestamp,
+ ).first()
+ else:
+ mode = 'text'
+ audio_timestamp = None
+ instance = cls.objects.filter(
+ user=user,
+ book__slug=slug,
+ mode='text',
+ anchor=anchor,
+ ).first()
+ if instance is None and create:
+ try:
+ book = Book.objects.get(slug=slug)
+ except Book.DoesNotExist:
+ return None
+ instance = cls.objects.create(
+ user=user,
+ book=book,
+ mode=mode,
+ anchor=anchor,
+ audio_timestamp=audio_timestamp,
+ )
+ return instance