158 lines
5.6 KiB
Python
158 lines
5.6 KiB
Python
"""Download Scribd documents (PDF uploads, presentations) as a single PDF."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
|
|
import img2pdf
|
|
from playwright.sync_api import BrowserContext, Page, sync_playwright
|
|
from rich.console import Console
|
|
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
|
|
|
from scribd_downloader.auth import open_browser
|
|
from scribd_downloader.pages import parse_page_selection
|
|
from scribd_downloader.url import ScribdTarget, sanitize_filename
|
|
|
|
console = Console()
|
|
TEMP_DIR = Path("temp_capture")
|
|
|
|
ProgressCallback = Callable[[int, int, str], None]
|
|
PageCallback = Callable[[Path, int, int], None]
|
|
|
|
|
|
def _block_noise(context: BrowserContext) -> None:
|
|
for pattern in ("**/*osano*/**", "**/*analytics*/**", "**/*doubleclick*/**"):
|
|
context.route(pattern, lambda route: route.abort())
|
|
|
|
|
|
def _document_title(page: Page, target: ScribdTarget) -> str:
|
|
title = page.evaluate(
|
|
"""() => {
|
|
const og = document.querySelector('meta[property="og:title"]')?.content;
|
|
if (og && og.toLowerCase() !== 'scribd') return og.trim();
|
|
const inner = document.querySelector('.title_text, .doc_title')?.innerText;
|
|
return inner ? inner.trim() : '';
|
|
}"""
|
|
)
|
|
if title:
|
|
return sanitize_filename(title)
|
|
if target.title_slug:
|
|
return sanitize_filename(target.title_slug)
|
|
return "scribd_document"
|
|
|
|
|
|
def download_document(
|
|
target: ScribdTarget,
|
|
*,
|
|
output: str | None = None,
|
|
pages: str = "all",
|
|
delay: float = 2.0,
|
|
scale: int = 2,
|
|
headless: bool = True,
|
|
use_session: bool = True,
|
|
on_progress: ProgressCallback | None = None,
|
|
on_page: PageCallback | None = None,
|
|
) -> Path:
|
|
"""Capture document pages via the embed viewer and merge into one PDF."""
|
|
TEMP_DIR.mkdir(exist_ok=True)
|
|
|
|
with sync_playwright() as playwright:
|
|
browser, context = open_browser(
|
|
playwright,
|
|
headless=headless,
|
|
use_session=use_session,
|
|
device_scale_factor=float(scale),
|
|
)
|
|
_block_noise(context)
|
|
page = context.new_page()
|
|
|
|
if on_progress:
|
|
on_progress(0, 1, "Loading document from Scribd…")
|
|
else:
|
|
console.print("[cyan]Loading document from Scribd…[/cyan]")
|
|
page.goto(target.embed_url, wait_until="domcontentloaded", timeout=90_000)
|
|
|
|
try:
|
|
page.wait_for_selector(".outer_page", timeout=20_000)
|
|
except Exception:
|
|
pass
|
|
|
|
total = page.locator(".outer_page").count()
|
|
if total == 0:
|
|
context.close()
|
|
browser.close()
|
|
raise RuntimeError(
|
|
"No pages found. The document may be private, removed, or blocked. "
|
|
"Try: scribd-dl login"
|
|
)
|
|
|
|
doc_title = _document_title(page, target)
|
|
if not on_progress:
|
|
console.print(f"[dim]Title:[/dim] [bold]{doc_title}[/bold]")
|
|
console.print(f"[dim]Pages:[/dim] [bold cyan]{total}[/bold cyan]")
|
|
|
|
indices = parse_page_selection(pages, total)
|
|
image_paths: list[Path] = []
|
|
locators = page.locator(".outer_page")
|
|
total_capture = len(indices)
|
|
|
|
def capture_pages() -> None:
|
|
for n, idx in enumerate(indices, start=1):
|
|
if on_progress:
|
|
on_progress(n - 1, total_capture, f"Capturing page {idx + 1}…")
|
|
element = locators.nth(idx)
|
|
element.scroll_into_view_if_needed()
|
|
time.sleep(delay)
|
|
img_path = TEMP_DIR / f"page_{idx + 1:04d}.png"
|
|
element.screenshot(path=str(img_path))
|
|
image_paths.append(img_path)
|
|
if on_page:
|
|
on_page(img_path, idx + 1, total)
|
|
|
|
if on_progress:
|
|
capture_pages()
|
|
on_progress(total_capture, total_capture, "Building PDF…")
|
|
else:
|
|
with Progress(
|
|
SpinnerColumn(),
|
|
TextColumn("[progress.description]{task.description}"),
|
|
BarColumn(),
|
|
TaskProgressColumn(),
|
|
console=console,
|
|
) as progress:
|
|
task = progress.add_task("Capturing pages…", total=total_capture)
|
|
for n, idx in enumerate(indices, start=1):
|
|
element = locators.nth(idx)
|
|
element.scroll_into_view_if_needed()
|
|
time.sleep(delay)
|
|
img_path = TEMP_DIR / f"page_{idx + 1:04d}.png"
|
|
element.screenshot(path=str(img_path))
|
|
image_paths.append(img_path)
|
|
progress.advance(task)
|
|
progress.update(task, description="Building PDF…")
|
|
|
|
output_path = Path(output) if output else Path(f"{doc_title}.pdf")
|
|
if not output_path.suffix.lower() == ".pdf":
|
|
output_path = output_path.with_suffix(".pdf")
|
|
if pages.strip().lower() != "all":
|
|
stem = output_path.stem
|
|
safe_range = pages.replace(" ", "")
|
|
output_path = output_path.with_name(f"{stem}_[{safe_range}].pdf")
|
|
|
|
with open(output_path, "wb") as pdf_file:
|
|
pdf_file.write(img2pdf.convert([str(p) for p in image_paths]))
|
|
|
|
context.close()
|
|
browser.close()
|
|
|
|
for img in image_paths:
|
|
img.unlink(missing_ok=True)
|
|
if TEMP_DIR.exists() and not any(TEMP_DIR.iterdir()):
|
|
TEMP_DIR.rmdir()
|
|
|
|
if not on_progress:
|
|
console.print(f"[bold green]Saved:[/bold green] {output_path.resolve()}")
|
|
return output_path
|