152 lines
5.9 KiB
Python
152 lines
5.9 KiB
Python
"""Download Scribd ebooks (reflowable text) chapter by chapter."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import shutil
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from pypdf import PdfWriter
|
|
from playwright.sync_api import sync_playwright
|
|
from rich.console import Console
|
|
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
|
|
from scribd_downloader.auth import ensure_logged_in, open_browser
|
|
from scribd_downloader.url import ScribdTarget, sanitize_filename
|
|
|
|
console = Console()
|
|
ZOOM = 0.625
|
|
|
|
|
|
def download_book(
|
|
target: ScribdTarget,
|
|
*,
|
|
output: str | None = None,
|
|
headless: bool = True,
|
|
) -> Path:
|
|
"""Render ebook pages to PDF. Requires an active Scribd subscription (login)."""
|
|
read_url = target.read_url or target.original_url.replace("/book/", "/read/")
|
|
|
|
with sync_playwright() as playwright:
|
|
ensure_logged_in(playwright)
|
|
|
|
browser, context = open_browser(playwright, headless=headless, use_session=True)
|
|
page = context.new_page()
|
|
|
|
console.print("[cyan]Opening book reader…[/cyan]")
|
|
page.goto(read_url, wait_until="domcontentloaded", timeout=120_000)
|
|
|
|
if "Browser limit exceeded" in page.content():
|
|
context.close()
|
|
browser.close()
|
|
raise RuntimeError(
|
|
"Scribd blocked this book (too many browsers). Wait up to 24 hours."
|
|
)
|
|
|
|
font_style = page.locator("#fontfaces").inner_html()
|
|
|
|
page.locator(".icon-ic_displaysettings").wait_for(state="visible", timeout=60_000)
|
|
page.evaluate("() => document.querySelector('.icon-ic_displaysettings').click()")
|
|
page.locator(".vertical_mode_btn").wait_for(state="visible")
|
|
page.evaluate("() => document.querySelector('.vertical_mode_btn').click()")
|
|
|
|
page.locator('div.vertical_page[data-page="0"], motion.div.vertical_page[data-page="0"]').first.wait_for(
|
|
state="visible", timeout=60_000
|
|
)
|
|
page.evaluate("() => document.querySelector('.icon-ic_toc_list').click()")
|
|
chapter_selector = page.locator('li.text_btn[role="none"]')
|
|
chapter_selector.nth(0).wait_for(state="visible")
|
|
num_chapters = chapter_selector.count()
|
|
|
|
page.evaluate('() => document.querySelector(\'li.text_btn[data-idx="0"]\').click()')
|
|
|
|
book_title = sanitize_filename(target.title_slug or f"book_{target.content_id}")
|
|
cache_dir = Path(f".cache_{target.content_id}")
|
|
cache_dir.mkdir(exist_ok=True)
|
|
|
|
render_page = context.new_page()
|
|
render_page.set_viewport_size({"width": 1200, "height": 1600})
|
|
|
|
chapter_no = 1
|
|
with Progress(
|
|
SpinnerColumn(),
|
|
TextColumn("[progress.description]{task.description}"),
|
|
console=console,
|
|
) as progress:
|
|
while True:
|
|
task = progress.add_task(
|
|
f"Chapter {chapter_no}/{num_chapters}…", total=None
|
|
)
|
|
page.locator(
|
|
'motion.div.vertical_page[data-page="0"], div.vertical_page[data-page="0"]'
|
|
).first.wait_for()
|
|
chapter_pages = page.locator("motion.div.vertical_page, div.vertical_page")
|
|
page_count = chapter_pages.count()
|
|
|
|
chapter_writer = PdfWriter()
|
|
for page_no in range(1, page_count + 1):
|
|
page_elem = chapter_pages.nth(page_no - 1)
|
|
html = page_elem.inner_html()
|
|
html = html.replace('src="/', 'src="https://www.scribd.com/')
|
|
|
|
match = re.findall(
|
|
r"width: ([0-9.]+)px; height: ([0-9.]+)px;", html
|
|
)
|
|
if not match:
|
|
continue
|
|
width, height = float(match[0]), float(match[1])
|
|
style = (
|
|
f"@page {{ size: {width * ZOOM}px {height * ZOOM}px; margin: 0; }} "
|
|
f"@media print {{ html, body {{ height: {height * ZOOM}px; "
|
|
f"width: {width * ZOOM}px;}}}}"
|
|
)
|
|
html = re.sub(
|
|
'data-colindex="0" style="',
|
|
'data-colindex="0" x="',
|
|
html,
|
|
)
|
|
html = re.sub(
|
|
r'position: absolute.*?"',
|
|
f'overflow: hidden; height: {height}px; width: {width}px; '
|
|
f'white-space: nowrap; zoom: {ZOOM};"',
|
|
html,
|
|
)
|
|
|
|
content = f"<html><head>{style}{font_style}</head><body>{html}</body></html>"
|
|
render_page.set_content(content)
|
|
part_pdf = cache_dir / f"{chapter_no}_{page_no}.pdf"
|
|
render_page.pdf(path=str(part_pdf), prefer_css_page_size=True)
|
|
chapter_writer.append(str(part_pdf))
|
|
part_pdf.unlink(missing_ok=True)
|
|
|
|
chapter_pdf = cache_dir / f"{chapter_no}.pdf"
|
|
with open(chapter_pdf, "wb") as f:
|
|
chapter_writer.write(f)
|
|
progress.remove_task(task)
|
|
|
|
if chapter_no >= num_chapters:
|
|
break
|
|
page.evaluate(
|
|
"() => document.querySelectorAll('button.load_next_btn')[0].click()"
|
|
)
|
|
time.sleep(1)
|
|
chapter_no += 1
|
|
|
|
output_path = Path(output or f"{book_title}.pdf")
|
|
if output_path.suffix.lower() != ".pdf":
|
|
output_path = output_path.with_suffix(".pdf")
|
|
|
|
final_writer = PdfWriter()
|
|
for ch in range(1, num_chapters + 1):
|
|
final_writer.append(str(cache_dir / f"{ch}.pdf"))
|
|
with open(output_path, "wb") as f:
|
|
final_writer.write(f)
|
|
|
|
shutil.rmtree(cache_dir, ignore_errors=True)
|
|
context.close()
|
|
browser.close()
|
|
|
|
console.print(f"[bold green]Saved:[/bold green] {output_path.resolve()}")
|
|
return output_path
|