Skip to content
Snippets Groups Projects
Verified Commit 62225bac authored by TheJoeCoder's avatar TheJoeCoder
Browse files

Fix koreader<->ub sync

parent ed5e5a4b
No related branches found
No related tags found
No related merge requests found
import io
from django.db import models
from django.db.models import QuerySet
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from accounts.models import User
from reader.models import Book, UserBook
from .xpointer_cfi_utils import epub_kr_to_cfi
from .xpointer_cfi_utils import epub_kr_to_cfi, epub_cfi_to_kr
# Create your models here.
......@@ -20,20 +23,35 @@ class SyncDocumentEntry(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
@receiver(post_save, sender=SyncDocumentEntry)
def post_save_document(sender, instance, **kwargs):
book_matches = Book.objects.filter(partial_md5__iexact=instance.key)
def post_save_document(sender, instance: SyncDocumentEntry, **kwargs):
book_matches: QuerySet[Book] = Book.objects.filter(partial_md5__iexact=instance.key)
if book_matches:
book = book_matches.first()
user_book = UserBook.objects.filter(user_id=instance.user.id, book_id=book.id)
if user_book:
user_book_qs: QuerySet[UserBook] = UserBook.objects.filter(user_id=instance.user.id, book_id=book.id)
if user_book_qs:
# Get User book
user_book = user_book.first()
user_book = user_book_qs.first()
# Detect type of file
if book.original_file.name.endswith(".epub"):
user_book.last_progress_cfi = epub_kr_to_cfi(user_book.original_file.name, instance.progress)
if book.file_type == "epub":
user_book.last_progress_cfi = epub_kr_to_cfi(io.BytesIO(book.original_file.open("rb").read()), instance.progress)
else:
user_book.last_progress_cfi = instance.progress
user_book.percentage_read = instance.percentage
user_book.last_progress_device = "KoReader - " + instance.device
user_book.last_read = timezone.now()
user_book.last_read = instance.updated_at
user_book.save()
@receiver(post_save, sender=UserBook)
def post_save_userbook(sender, instance: UserBook, **kwargs):
# Find the corresponding SyncDocumentEntry
sync_doc_q: QuerySet[SyncDocumentEntry] = SyncDocumentEntry.objects.filter(user=instance.user, key__iexact=instance.book.partial_md5)
if sync_doc_q.first():
sync_doc: SyncDocumentEntry = sync_doc_q.first()
if instance.book.file_type == "epub":
sync_doc.progress = epub_cfi_to_kr(io.BytesIO(instance.book.original_file.open("rb").read()), instance.last_progress_cfi)
else:
sync_doc.progress = instance.last_progress_cfi
sync_doc.percentage = instance.percentage_read
sync_doc.device = instance.last_progress_device
sync_doc.updated_at = instance.last_read
sync_doc.save()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment