revert-cover-urls.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. """Revert book cover URLs from full URLs back to relative paths"""
  3. import asyncio
  4. import sqlite3
  5. from app.database import async_session
  6. from app.models import Book, User
  7. from sqlalchemy import select
  8. async def revert_cover_urls():
  9. """Convert full URLs back to relative paths"""
  10. async with async_session() as db:
  11. # Get all users to find the ABS URL patterns
  12. result = await db.execute(select(User))
  13. users = result.scalars().all()
  14. if not users:
  15. print("No users found")
  16. return
  17. # Get unique ABS URLs
  18. abs_urls = set(u.abs_url.rstrip('/') for u in users)
  19. print(f"Found ABS URLs: {abs_urls}")
  20. # Get all books with cover URLs
  21. result = await db.execute(
  22. select(Book).where(
  23. Book.cover_url.isnot(None),
  24. Book.cover_url != ''
  25. )
  26. )
  27. books = result.scalars().all()
  28. reverted_count = 0
  29. for book in books:
  30. if book.cover_url:
  31. # Check if it's a full URL
  32. for abs_url in abs_urls:
  33. if book.cover_url.startswith(abs_url):
  34. # Strip the ABS URL to get relative path
  35. old_url = book.cover_url
  36. book.cover_url = book.cover_url[len(abs_url):]
  37. print(f"Reverted: {book.title[:50]}")
  38. print(f" Old: {old_url}")
  39. print(f" New: {book.cover_url}")
  40. print()
  41. reverted_count += 1
  42. break
  43. await db.commit()
  44. print(f"\nReverted {reverted_count} cover URLs to relative paths")
  45. if __name__ == "__main__":
  46. print("Reverting book cover URLs to relative paths...")
  47. print("-" * 60)
  48. asyncio.run(revert_cover_urls())