migrate_page_to_scrobbledpage.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from books.models import Book
  2. from django.core.management.base import BaseCommand
  3. from scrobbles.models import ScrobbledPage
  4. class Command(BaseCommand):
  5. def add_arguments(self, parser):
  6. parser.add_argument(
  7. "--commit",
  8. action="store_true",
  9. help="Actually populate data",
  10. )
  11. def handle(self, *args, **options):
  12. dry_run = True
  13. if options["commit"]:
  14. dry_run = False
  15. pages_to_create = []
  16. associated_scrobble = None
  17. last_scrobble = None
  18. for book in Book.objects.all():
  19. for page in book.page_set.all().order_by("number"):
  20. notes = ""
  21. last_scrobble = associated_scrobble
  22. if (
  23. not associated_scrobble
  24. or page.number > associated_scrobble.book_pages_read
  25. ):
  26. associated_scrobble = page.user.scrobble_set.filter(
  27. book=page.book,
  28. timestamp__gte=page.start_time,
  29. timestamp__lte=page.end_time,
  30. ).first()
  31. if (
  32. last_scrobble
  33. and not associated_scrobble
  34. and page.number > last_scrobble.book_pages_read
  35. ):
  36. associated_scrobble = last_scrobble
  37. notes = f"Extrapolated reading from scrobble {associated_scrobble.id}"
  38. pages_to_create.append(
  39. ScrobbledPage(
  40. scrobble=associated_scrobble,
  41. number=page.number,
  42. start_time=page.start_time,
  43. end_time=page.end_time,
  44. duration_seconds=page.duration_seconds,
  45. notes=notes,
  46. )
  47. )
  48. pages_to_move_len = len(pages_to_create)
  49. if dry_run:
  50. print(
  51. f"Found {pages_to_move_len} to migrate. Use --commit to move them"
  52. )
  53. return
  54. ScrobbledPage.objects.bulk_create(pages_to_create)
  55. print(f"Migrated {pages_to_move_len} generic pages to scrobbled pages")