- SEO: серверные локализованные страницы /en/ /de/ /fr/ /it/ /es/ /pt/ (title/description/OG/JSON-LD + self-hreflang), sitemap все языки + /developers, OG 1200x630 (static/og.png) - Бизнес-API /api/v1/* (ключи WEB_API_KEYS, rate-limit), страница /developers с самовыдачей ключа через Telegram - OCR-тумблер, загрузка папкой (webkitdirectory) и ZIP (/api/submit-zip-chunked) - Личный кабинет: WEB_API_KEYS/web_owner_id, /api/history - ocr прокинут в submit/submit-chunked/api/v1 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1636 lines
74 KiB
Python
1636 lines
74 KiB
Python
"""
|
||
pdf2scan web service — FastAPI backend.
|
||
Добавляет задания в очередь бота (та же БД, тот же temp/).
|
||
Бот обрабатывает и оставляет файл в temp/ (url_res_f='web_local').
|
||
Веб отдаёт файл напрямую и удаляет через 30 минут.
|
||
"""
|
||
|
||
import asyncio
|
||
import datetime
|
||
import hashlib
|
||
import hmac
|
||
import os
|
||
import re
|
||
import secrets
|
||
import sqlite3
|
||
import subprocess
|
||
import threading
|
||
import time
|
||
import uuid
|
||
from pathlib import Path
|
||
|
||
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
|
||
from fastapi.exceptions import RequestValidationError
|
||
from starlette.background import BackgroundTask
|
||
from starlette.middleware.base import BaseHTTPMiddleware
|
||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
# ── Config ────────────────────────────────────────────────────────────────────
|
||
BOT_TOKEN = os.getenv("TOKEN", "")
|
||
BOT_USERNAME = os.getenv("BOT_USERNAME", "pdf2scan_pybot")
|
||
DB_PATH = "/data/bot_db.db"
|
||
BOT_TEMP = "temp/" # относительный путь (рабочая директория /app)
|
||
WEB_USER_ID = 0 # фейковый TG user_id для веб-заданий
|
||
RESULT_TTL = 21600 # 6 часов (большие пачки не успевают за 30 мин)
|
||
AUTH_TOKEN_TTL = 600 # 10 минут на авторизацию через бота
|
||
|
||
AUTH_REQUIRED_PAGES = 100
|
||
AUTH_REQUIRED_MB = 50.0
|
||
|
||
# Чанковая загрузка (туннель схлопывает крупные передачи — грузим кусками ≤6 МБ)
|
||
UPLOAD_DIR = f"{BOT_TEMP}uploads/" # временные .part-файлы
|
||
MAX_CHUNK_BYTES = 12 * 1024 * 1024 # защита: один кусок не больше 12 МБ
|
||
MAX_UPLOAD_BYTES = 300 * 1024 * 1024 # суммарный предел собранного файла
|
||
|
||
_COLOR_MAP = {"color": "цветной", "bw": "черно-белый"}
|
||
|
||
# job_id → {original_name, stitching, created_at}
|
||
_meta: dict[str, dict] = {}
|
||
_meta_lock = threading.Lock()
|
||
|
||
# zip_id → {status, path, name, created_at} — асинхронная сборка больших ZIP
|
||
_zip_jobs: dict[str, dict] = {}
|
||
_zip_jobs_lock = threading.Lock()
|
||
|
||
# user_id → unix timestamp of verification (24h TTL)
|
||
_verified_users: dict[int, float] = {}
|
||
_verified_users_lock = threading.Lock()
|
||
|
||
|
||
# ── Конвертация документов ────────────────────────────────────────────────────
|
||
_LO_PROFILE_TEMPLATE = "/opt/lo-profile"
|
||
|
||
def _convert_doc_to_pdf(src_path: str, dst_path: str) -> None:
|
||
"""Конвертирует DOC/DOCX в PDF через libreoffice."""
|
||
import tempfile, shutil
|
||
with tempfile.TemporaryDirectory() as userdir:
|
||
# Копируем шаблон профиля (замена шрифтов Calibri→Carlito и т.д.)
|
||
if os.path.isdir(_LO_PROFILE_TEMPLATE):
|
||
shutil.copytree(_LO_PROFILE_TEMPLATE, userdir, dirs_exist_ok=True)
|
||
cmd = [
|
||
"libreoffice",
|
||
f"-env:UserInstallation=file://{userdir}",
|
||
"--headless", "--norestore",
|
||
"--convert-to", "pdf",
|
||
"--outdir", str(Path(dst_path).parent), str(src_path),
|
||
]
|
||
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
|
||
if result.returncode != 0:
|
||
raise RuntimeError(f"libreoffice convert failed: {result.stderr.decode(errors='ignore')}")
|
||
candidate = Path(dst_path).parent / (Path(src_path).stem + ".pdf")
|
||
if candidate.exists() and str(candidate) != dst_path:
|
||
candidate.rename(dst_path)
|
||
if not Path(dst_path).exists():
|
||
raise FileNotFoundError(f"Converted PDF not found: {dst_path}")
|
||
|
||
|
||
# ── БД-хелперы ────────────────────────────────────────────────────────────────
|
||
def _db_insert_job(
|
||
name_or_f, stitching, title, numeration, flip_side,
|
||
color, pdfa, quality, original_name, source_size_mb,
|
||
ocr=0, web_owner_id=0,
|
||
):
|
||
now = datetime.datetime.now()
|
||
date_str = now.strftime("%Y.%m.%d")
|
||
time_str = now.strftime("%H:%M:%S")
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("PRAGMA table_info(FILES)")
|
||
cols = {row[1] for row in cur.fetchall()}
|
||
|
||
fields = [
|
||
"date", "time", "name_or_f", "user_id",
|
||
"first_name", "last_name", "username",
|
||
"stitching", "title", "numeration", "flip_side",
|
||
"color", "pdfa", "num_pages", "name_res_f",
|
||
"url_res_f", "finish_time", "elapsed_time",
|
||
]
|
||
values = [
|
||
date_str, time_str, name_or_f, WEB_USER_ID,
|
||
"Web", "User", "webuser",
|
||
stitching, int(title), int(numeration), int(flip_side),
|
||
color, int(pdfa), 0, "-",
|
||
"-", "-", "-",
|
||
]
|
||
|
||
if "original_name" in cols:
|
||
fields.append("original_name")
|
||
values.append(original_name or "document.pdf")
|
||
if "source_size_mb" in cols:
|
||
fields.append("source_size_mb")
|
||
values.append(source_size_mb)
|
||
if "quality" in cols:
|
||
fields.append("quality")
|
||
values.append(quality or "high")
|
||
if "ocr" in cols:
|
||
fields.append("ocr")
|
||
values.append(int(ocr))
|
||
if "web_owner_id" in cols:
|
||
fields.append("web_owner_id")
|
||
values.append(int(web_owner_id or 0))
|
||
|
||
placeholders = ", ".join(["?"] * len(fields))
|
||
sql = f"INSERT INTO FILES ({', '.join(fields)}) VALUES ({placeholders})"
|
||
cur.execute(sql, values)
|
||
con.commit()
|
||
|
||
|
||
def _db_get_url_res_f(name_or_f: str) -> str | None:
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("SELECT url_res_f FROM FILES WHERE name_or_f = ?", (name_or_f,))
|
||
row = cur.fetchone()
|
||
return row[0] if row else None
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _db_get_job_meta(name_or_f: str):
|
||
"""(original_name, stitching) из FILES — имена для скачивания/ZIP переживают рестарт."""
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("SELECT original_name, stitching FROM FILES WHERE name_or_f = ?", (name_or_f,))
|
||
row = cur.fetchone()
|
||
if row:
|
||
return (row[0] or None, row[1] or None)
|
||
except Exception:
|
||
pass
|
||
return (None, None)
|
||
|
||
|
||
def _db_set_url_res_f(name_or_f: str, value: str):
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute("UPDATE FILES SET url_res_f = ? WHERE name_or_f = ?", (value, name_or_f))
|
||
con.commit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _db_queue_position(name_or_f: str) -> int:
|
||
"""Реальная позиция задания в очереди (1 = бот обрабатывает его сейчас; FIFO по rowid).
|
||
Бот не помечает задание 'processing' в БД, поэтому позицию считаем по rowid."""
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("SELECT rowid FROM FILES WHERE name_or_f = ?", (name_or_f,))
|
||
row = cur.fetchone()
|
||
if not row:
|
||
return 0
|
||
myrow = row[0]
|
||
cur.execute(
|
||
"SELECT COUNT(*) FROM FILES "
|
||
"WHERE (url_res_f IS NULL OR TRIM(url_res_f) IN ('', '-')) AND rowid <= ?",
|
||
(myrow,),
|
||
)
|
||
r = cur.fetchone()
|
||
return int(r[0]) if r else 0
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
# ── Web auth tokens (shared SQLite) ───────────────────────────────────────────
|
||
|
||
def _db_ensure_auth_table():
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute("""
|
||
CREATE TABLE IF NOT EXISTS WEB_AUTH_TOKENS (
|
||
token TEXT PRIMARY KEY,
|
||
user_id INTEGER,
|
||
first_name TEXT,
|
||
last_name TEXT,
|
||
username TEXT,
|
||
created_at REAL,
|
||
status TEXT DEFAULT 'pending'
|
||
)
|
||
""")
|
||
# Подтверждённые веб-пользователи — в БД, чтобы авторизация
|
||
# переживала рестарт контейнера (не только in-memory _verified_users).
|
||
con.execute("""
|
||
CREATE TABLE IF NOT EXISTS WEB_VERIFIED_USERS (
|
||
user_id INTEGER PRIMARY KEY,
|
||
verified_at REAL
|
||
)
|
||
""")
|
||
# API-ключи для бизнес-доступа (интеграции). owner_id — TG user_id
|
||
# владельца ключа (из веб-авторизации). Оплату/квоты прикрутим позже —
|
||
# поля plan/quota уже заложены.
|
||
con.execute("""
|
||
CREATE TABLE IF NOT EXISTS WEB_API_KEYS (
|
||
api_key TEXT PRIMARY KEY,
|
||
owner_id INTEGER,
|
||
name TEXT,
|
||
plan TEXT DEFAULT 'free',
|
||
active INTEGER DEFAULT 1,
|
||
req_count INTEGER DEFAULT 0,
|
||
created_at REAL,
|
||
last_req REAL
|
||
)
|
||
""")
|
||
# Авто-миграция FILES: колонки для OCR и владельца веб-задания
|
||
# (личный кабинет «Мои документы»). ADD COLUMN идемпотентен по факту наличия.
|
||
try:
|
||
cur = con.execute("PRAGMA table_info(FILES)")
|
||
have = {row[1] for row in cur.fetchall()}
|
||
if "ocr" not in have:
|
||
con.execute("ALTER TABLE FILES ADD COLUMN ocr INTEGER DEFAULT 0")
|
||
if "web_owner_id" not in have:
|
||
con.execute("ALTER TABLE FILES ADD COLUMN web_owner_id INTEGER DEFAULT 0")
|
||
except Exception as _mig:
|
||
print(f"FILES migrate error: {_mig}")
|
||
con.commit()
|
||
except Exception as e:
|
||
print(f"WEB_AUTH_TOKENS create error: {e}")
|
||
|
||
|
||
def _db_mark_verified(user_id: int):
|
||
if not user_id:
|
||
return
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute(
|
||
"INSERT INTO WEB_VERIFIED_USERS (user_id, verified_at) VALUES (?, ?) "
|
||
"ON CONFLICT(user_id) DO UPDATE SET verified_at=excluded.verified_at",
|
||
(int(user_id), time.time()),
|
||
)
|
||
con.commit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _db_is_verified(user_id: int) -> bool:
|
||
if not user_id:
|
||
return False
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("SELECT verified_at FROM WEB_VERIFIED_USERS WHERE user_id = ?", (int(user_id),))
|
||
row = cur.fetchone()
|
||
return bool(row) and (time.time() - (row[0] or 0) <= 86400)
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _db_create_auth_token(token: str):
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute(
|
||
"INSERT INTO WEB_AUTH_TOKENS (token, created_at, status) VALUES (?, ?, 'pending')",
|
||
(token, time.time()),
|
||
)
|
||
con.commit()
|
||
|
||
|
||
def _db_poll_auth_token(token: str) -> dict | None:
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute(
|
||
"SELECT status, user_id, first_name, last_name, username, created_at "
|
||
"FROM WEB_AUTH_TOKENS WHERE token = ?",
|
||
(token,),
|
||
)
|
||
row = cur.fetchone()
|
||
if not row:
|
||
return None
|
||
return {
|
||
"status": row[0], "user_id": row[1],
|
||
"first_name": row[2], "last_name": row[3],
|
||
"username": row[4], "created_at": row[5],
|
||
}
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
# ── Фоновая уборка файлов через 30 минут ──────────────────────────────────────
|
||
def _cleanup_loop():
|
||
while True:
|
||
time.sleep(60)
|
||
now = time.time()
|
||
# Удаляем просроченные сессии авторизации (24 ч)
|
||
with _verified_users_lock:
|
||
stale = [uid for uid, ts in _verified_users.items() if now - ts > 86400]
|
||
for uid in stale:
|
||
del _verified_users[uid]
|
||
# Удаляем старые auth-токены из БД (старше 1 часа)
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=5) as con:
|
||
con.execute(
|
||
"DELETE FROM WEB_AUTH_TOKENS WHERE created_at < ?",
|
||
(now - 3600,),
|
||
)
|
||
con.commit()
|
||
except Exception:
|
||
pass
|
||
# Удаляем старые результаты по mtime файла — не зависит от in-memory _meta,
|
||
# поэтому переживает рестарт контейнера (пачка не пропадает).
|
||
try:
|
||
for rp in Path(BOT_TEMP).glob("* скан *.pdf"):
|
||
try:
|
||
if now - rp.stat().st_mtime > RESULT_TTL:
|
||
rp.unlink()
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
with _meta_lock:
|
||
for jid in [j for j, m in _meta.items() if now - m["created_at"] > RESULT_TTL]:
|
||
_meta.pop(jid, None)
|
||
# Подчищаем оставшиеся ZIP-архивы (на случай, если их не скачали)
|
||
try:
|
||
for zp in Path(BOT_TEMP).glob("*.zip"):
|
||
if now - zp.stat().st_mtime > RESULT_TTL:
|
||
zp.unlink()
|
||
except Exception:
|
||
pass
|
||
# Подчищаем устаревшие записи фоновых zip-сборок
|
||
with _zip_jobs_lock:
|
||
for zid in [z for z, jj in _zip_jobs.items() if now - jj.get("created_at", now) > RESULT_TTL]:
|
||
old = _zip_jobs.pop(zid, {})
|
||
if old.get("path"):
|
||
_safe_remove(old["path"])
|
||
# Подчищаем брошенные куски чанковой загрузки (старше часа)
|
||
try:
|
||
for pp in Path(UPLOAD_DIR).glob("*.part"):
|
||
if now - pp.stat().st_mtime > 3600:
|
||
pp.unlink()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ── Auth ──────────────────────────────────────────────────────────────────────
|
||
def _verify_telegram_auth(data: dict) -> bool:
|
||
if not BOT_TOKEN:
|
||
return False
|
||
try:
|
||
data = dict(data)
|
||
check_hash = data.pop("hash", None)
|
||
if not check_hash:
|
||
return False
|
||
if time.time() - int(data.get("auth_date", 0)) > 86400:
|
||
return False
|
||
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(data.items()))
|
||
secret_key = hashlib.sha256(BOT_TOKEN.encode()).digest()
|
||
expected = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
|
||
return hmac.compare_digest(expected, check_hash)
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
# ── App ───────────────────────────────────────────────────────────────────────
|
||
app = FastAPI(title="pdf2scan web")
|
||
|
||
|
||
class NoIndexApiMiddleware(BaseHTTPMiddleware):
|
||
"""Запрещает индексирование /api/* роботами."""
|
||
async def dispatch(self, request: Request, call_next):
|
||
response = await call_next(request)
|
||
if request.url.path.startswith("/api/"):
|
||
response.headers["X-Robots-Tag"] = "noindex, nofollow"
|
||
return response
|
||
|
||
app.add_middleware(NoIndexApiMiddleware)
|
||
|
||
|
||
@app.exception_handler(RequestValidationError)
|
||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||
print(f"422 on {request.method} {request.url.path}: {exc.errors()}")
|
||
return JSONResponse(status_code=422, content={"detail": str(exc.errors())})
|
||
|
||
|
||
@app.on_event("startup")
|
||
async def _startup():
|
||
os.makedirs(BOT_TEMP, exist_ok=True)
|
||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||
_db_ensure_auth_table()
|
||
threading.Thread(target=_cleanup_loop, daemon=True).start()
|
||
|
||
|
||
app.mount("/static", StaticFiles(directory="/web_app/static"), name="static")
|
||
|
||
|
||
# ── SEO: серверный рендер локализованных языковых страниц ─────────────────────
|
||
# Отдельные URL на язык (/, /en/, /de/…) с локализованным <head> — краулеры видят
|
||
# правильные title/description/hreflang на своём языке, это открывает западный трафик.
|
||
SEO_BASE = "https://pdf2scan.online"
|
||
SEO_LANG_PATH = {
|
||
"ru": "/", "en": "/en/", "de": "/de/", "fr": "/fr/",
|
||
"it": "/it/", "es": "/es/", "pt": "/pt/",
|
||
}
|
||
SEO_LOCALE = {
|
||
"ru": "ru_RU", "en": "en_US", "de": "de_DE", "fr": "fr_FR",
|
||
"it": "it_IT", "es": "es_ES", "pt": "pt_PT",
|
||
}
|
||
SEO = {
|
||
"ru": {
|
||
"title": "pdf2scan — сделать скан из PDF онлайн бесплатно",
|
||
"desc": "Сделайте скан из PDF онлайн — бесплатно, без регистрации. Эффект сканирования, сшивка (нитка, ленточка, пружинка, уголок, дырокол), нумерация страниц и лист «прошито-пронумеровано».",
|
||
"og_desc": "Сделайте скан из PDF онлайн — бесплатно, без регистрации. Сшивка, нумерация, эффект сканирования в один клик.",
|
||
"keywords": "сделать скан из pdf онлайн, pdf в скан онлайн, сканирование pdf бесплатно, pdf с эффектом сканирования, прошить документ онлайн, сшивка документов онлайн, растровый pdf онлайн, pdf2scan",
|
||
"ld_desc": "Бесплатный онлайн-инструмент для создания PDF с эффектом сканирования. Сшивка нитками, ленточкой, уголком, пружинкой и дыроколом. Нумерация страниц, титульный лист, PDF/A.",
|
||
},
|
||
"en": {
|
||
"title": "pdf2scan — add a scan effect to PDF online, free",
|
||
"desc": "Make a PDF look scanned online — free, no signup. Add a realistic scan effect, binding (thread, ribbon, spiral, corner, hole punch), page numbering and a certification page. Word to scanned PDF too.",
|
||
"og_desc": "Make your PDF look scanned online — free, no signup. Scan effect, binding and page numbering in one click.",
|
||
"keywords": "pdf scanner effect online, make pdf look scanned, add scan effect to pdf, convert pdf to scanned document, scan effect pdf free, pdf to scan online, word to scanned pdf, pdf2scan",
|
||
"ld_desc": "Free online tool to give a PDF a realistic scan effect. Thread, ribbon, corner, spiral and hole-punch binding. Page numbering, title page, PDF/A.",
|
||
},
|
||
"de": {
|
||
"title": "pdf2scan — PDF online mit Scan-Effekt versehen, kostenlos",
|
||
"desc": "PDF online wie gescannt aussehen lassen — kostenlos, ohne Anmeldung. Realistischer Scan-Effekt, Bindung (Faden, Band, Spirale, Ecke, Lochung), Seitennummerierung und Zertifizierungsseite. Auch Word zu gescanntem PDF.",
|
||
"og_desc": "PDF online wie gescannt aussehen lassen — kostenlos, ohne Anmeldung. Scan-Effekt, Bindung und Nummerierung in einem Klick.",
|
||
"keywords": "pdf scan-effekt online, pdf wie gescannt, pdf in scan umwandeln, scan-effekt pdf kostenlos, word in gescanntes pdf, pdf2scan",
|
||
"ld_desc": "Kostenloses Online-Tool, um ein PDF wie einen echten Scan aussehen zu lassen. Faden-, Band-, Ecken-, Spiral- und Lochbindung. Seitennummerierung, Titelseite, PDF/A.",
|
||
},
|
||
"fr": {
|
||
"title": "pdf2scan — ajouter un effet scan à un PDF en ligne, gratuit",
|
||
"desc": "Donnez à un PDF l'apparence d'un document scanné en ligne — gratuit, sans inscription. Effet scan réaliste, reliure (fil, ruban, spirale, coin, perforation), numérotation et page de certification. Word vers PDF scanné aussi.",
|
||
"og_desc": "Donnez à un PDF l'apparence d'un scan en ligne — gratuit, sans inscription. Effet scan, reliure et numérotation en un clic.",
|
||
"keywords": "effet scan pdf en ligne, pdf aspect scanné, convertir pdf en scan, effet scan pdf gratuit, word en pdf scanné, pdf2scan",
|
||
"ld_desc": "Outil en ligne gratuit pour donner à un PDF un effet de scan réaliste. Reliure par fil, ruban, coin, spirale et perforateur. Numérotation, page de titre, PDF/A.",
|
||
},
|
||
"it": {
|
||
"title": "pdf2scan — aggiungi un effetto scansione al PDF online, gratis",
|
||
"desc": "Fai sembrare scansionato un PDF online — gratis, senza registrazione. Effetto scansione realistico, rilegatura (filo, nastro, spirale, angolo, foratura), numerazione e pagina di certificazione. Anche da Word a PDF scansionato.",
|
||
"og_desc": "Fai sembrare scansionato un PDF online — gratis, senza registrazione. Effetto scansione, rilegatura e numerazione in un clic.",
|
||
"keywords": "effetto scansione pdf online, pdf aspetto scansionato, convertire pdf in scansione, effetto scansione pdf gratis, word in pdf scansionato, pdf2scan",
|
||
"ld_desc": "Strumento online gratuito per dare a un PDF un effetto scansione realistico. Rilegatura con filo, nastro, angolo, spirale e perforatore. Numerazione, pagina del titolo, PDF/A.",
|
||
},
|
||
"es": {
|
||
"title": "pdf2scan — añade efecto de escaneo a un PDF online, gratis",
|
||
"desc": "Haz que un PDF parezca escaneado online — gratis, sin registro. Efecto de escaneo realista, encuadernación (hilo, cinta, espiral, esquina, perforación), numeración y página de certificación. También de Word a PDF escaneado.",
|
||
"og_desc": "Haz que un PDF parezca escaneado online — gratis, sin registro. Efecto de escaneo, encuadernación y numeración en un clic.",
|
||
"keywords": "efecto escaneo pdf online, pdf aspecto escaneado, convertir pdf a escaneado, efecto escaneo pdf gratis, word a pdf escaneado, pdf2scan",
|
||
"ld_desc": "Herramienta online gratuita para dar a un PDF un efecto de escaneo realista. Encuadernación con hilo, cinta, esquina, espiral y perforadora. Numeración, página de título, PDF/A.",
|
||
},
|
||
"pt": {
|
||
"title": "pdf2scan — adicione efeito de digitalização ao PDF online, grátis",
|
||
"desc": "Faça um PDF parecer digitalizado online — grátis, sem cadastro. Efeito de digitalização realista, encadernação (fio, fita, espiral, canto, furação), numeração e página de certificação. Também de Word para PDF digitalizado.",
|
||
"og_desc": "Faça um PDF parecer digitalizado online — grátis, sem cadastro. Efeito de digitalização, encadernação e numeração em um clique.",
|
||
"keywords": "efeito digitalização pdf online, pdf aparência digitalizada, converter pdf em digitalizado, efeito scan pdf grátis, word para pdf digitalizado, pdf2scan",
|
||
"ld_desc": "Ferramenta online gratuita para dar a um PDF um efeito de digitalização realista. Encadernação com fio, fita, canto, espiral e furador. Numeração, página de título, PDF/A.",
|
||
},
|
||
}
|
||
|
||
_INDEX_RAW: str | None = None
|
||
|
||
|
||
def _load_index_template() -> str:
|
||
global _INDEX_RAW
|
||
if _INDEX_RAW is None:
|
||
with open("/web_app/static/index.html", encoding="utf-8") as f:
|
||
_INDEX_RAW = f.read()
|
||
return _INDEX_RAW
|
||
|
||
|
||
def _esc_attr(s: str) -> str:
|
||
return s.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">")
|
||
|
||
|
||
def _build_seo_head(lang: str) -> str:
|
||
s = SEO[lang]
|
||
path = SEO_LANG_PATH[lang]
|
||
url = SEO_BASE + path
|
||
title = _esc_attr(s["title"])
|
||
desc = _esc_attr(s["desc"])
|
||
og_desc = _esc_attr(s["og_desc"])
|
||
keywords = _esc_attr(s["keywords"])
|
||
og_img = f"{SEO_BASE}/static/og.png"
|
||
|
||
hreflangs = "\n".join(
|
||
f'<link rel="alternate" hreflang="{lc}" href="{SEO_BASE}{p}">'
|
||
for lc, p in SEO_LANG_PATH.items()
|
||
)
|
||
ld = {
|
||
"@context": "https://schema.org",
|
||
"@type": "WebApplication",
|
||
"name": "pdf2scan",
|
||
"url": url,
|
||
"description": s["ld_desc"],
|
||
"applicationCategory": "UtilitiesApplication",
|
||
"operatingSystem": "Any",
|
||
"browserRequirements": "Requires JavaScript",
|
||
"inLanguage": list(SEO_LANG_PATH.keys()),
|
||
"offers": {"@type": "Offer", "price": "0", "priceCurrency": "RUB"},
|
||
"creator": {"@type": "Organization", "name": "pdf2scan", "url": SEO_BASE},
|
||
}
|
||
import json as _json
|
||
ld_json = _json.dumps(ld, ensure_ascii=False, indent=2)
|
||
|
||
return (
|
||
f"<title>{title}</title>\n"
|
||
f'<meta name="description" content="{desc}">\n'
|
||
f'<meta name="keywords" content="{keywords}">\n'
|
||
f'<link rel="canonical" href="{url}">\n'
|
||
f"{hreflangs}\n"
|
||
f'<link rel="alternate" hreflang="x-default" href="{SEO_BASE}/">\n'
|
||
f'<meta property="og:title" content="{title}">\n'
|
||
f'<meta property="og:description" content="{og_desc}">\n'
|
||
f'<meta property="og:url" content="{url}">\n'
|
||
f'<meta property="og:type" content="website">\n'
|
||
f'<meta property="og:image" content="{og_img}">\n'
|
||
f'<meta property="og:image:width" content="1200">\n'
|
||
f'<meta property="og:image:height" content="630">\n'
|
||
f'<meta property="og:locale" content="{SEO_LOCALE[lang]}">\n'
|
||
f'<meta name="twitter:card" content="summary_large_image">\n'
|
||
f'<meta name="twitter:title" content="{title}">\n'
|
||
f'<meta name="twitter:description" content="{og_desc}">\n'
|
||
f'<meta name="twitter:image" content="{og_img}">\n'
|
||
f'<link rel="icon" type="image/x-icon" href="/favicon.ico">\n'
|
||
f'<link rel="shortcut icon" href="/favicon.ico">\n'
|
||
f'<script type="application/ld+json">\n{ld_json}\n</script>'
|
||
)
|
||
|
||
|
||
def _render_index_html(lang: str) -> str:
|
||
lang = lang if lang in SEO else "ru"
|
||
html = _load_index_template()
|
||
# Локализуем язык документа. На корне (/ = ru/x-default) data-prelang оставляем
|
||
# пустым, чтобы уважать сохранённый выбор пользователя и авто-детект языка;
|
||
# на явных языковых URL (/en/, /de/…) prelang жёсткий — страница на своём языке.
|
||
prelang = "" if lang == "ru" else lang
|
||
html = html.replace(
|
||
'<html lang="ru" data-prelang="ru">',
|
||
f'<html lang="{lang}" data-prelang="{prelang}">',
|
||
)
|
||
# Заменяем SEO-блок между маркерами на локализованный
|
||
start = html.find("<!--SEO_HEAD-->")
|
||
end = html.find("<!--/SEO_HEAD-->")
|
||
if start != -1 and end != -1:
|
||
head = _build_seo_head(lang)
|
||
html = html[:start] + "<!--SEO_HEAD-->\n" + head + "\n" + html[end:]
|
||
return html
|
||
|
||
|
||
@app.get("/", response_class=HTMLResponse)
|
||
async def index():
|
||
return _render_index_html("ru")
|
||
|
||
|
||
@app.get("/en/", response_class=HTMLResponse)
|
||
@app.get("/en", response_class=HTMLResponse)
|
||
async def index_en():
|
||
return _render_index_html("en")
|
||
|
||
|
||
@app.get("/de/", response_class=HTMLResponse)
|
||
@app.get("/de", response_class=HTMLResponse)
|
||
async def index_de():
|
||
return _render_index_html("de")
|
||
|
||
|
||
@app.get("/fr/", response_class=HTMLResponse)
|
||
@app.get("/fr", response_class=HTMLResponse)
|
||
async def index_fr():
|
||
return _render_index_html("fr")
|
||
|
||
|
||
@app.get("/it/", response_class=HTMLResponse)
|
||
@app.get("/it", response_class=HTMLResponse)
|
||
async def index_it():
|
||
return _render_index_html("it")
|
||
|
||
|
||
@app.get("/es/", response_class=HTMLResponse)
|
||
@app.get("/es", response_class=HTMLResponse)
|
||
async def index_es():
|
||
return _render_index_html("es")
|
||
|
||
|
||
@app.get("/pt/", response_class=HTMLResponse)
|
||
@app.get("/pt", response_class=HTMLResponse)
|
||
async def index_pt():
|
||
return _render_index_html("pt")
|
||
|
||
|
||
@app.get("/favicon.ico", include_in_schema=False)
|
||
async def favicon():
|
||
return FileResponse("/web_app/static/favicon.ico", media_type="image/x-icon")
|
||
|
||
|
||
@app.get("/robots.txt")
|
||
async def robots():
|
||
return HTMLResponse(
|
||
content=(
|
||
"User-agent: *\n"
|
||
"Allow: /\n"
|
||
"Disallow: /api/\n"
|
||
"Disallow: /static/\n"
|
||
"\n"
|
||
"Sitemap: https://pdf2scan.online/sitemap.xml\n"
|
||
),
|
||
media_type="text/plain",
|
||
)
|
||
|
||
|
||
@app.get("/sitemap.xml")
|
||
async def sitemap():
|
||
today = datetime.date.today().isoformat()
|
||
# Все языковые страницы + перекрёстные hreflang-альтернативы (xhtml:link)
|
||
alternates = "".join(
|
||
f' <xhtml:link rel="alternate" hreflang="{lc}" href="{SEO_BASE}{p}"/>\n'
|
||
for lc, p in SEO_LANG_PATH.items()
|
||
)
|
||
alternates += f' <xhtml:link rel="alternate" hreflang="x-default" href="{SEO_BASE}/"/>\n'
|
||
urls = ""
|
||
for lc, p in SEO_LANG_PATH.items():
|
||
urls += (
|
||
' <url>\n'
|
||
f' <loc>{SEO_BASE}{p}</loc>\n'
|
||
f'{alternates}'
|
||
f' <lastmod>{today}</lastmod>\n'
|
||
' <changefreq>weekly</changefreq>\n'
|
||
f' <priority>{"1.0" if lc == "ru" else "0.9"}</priority>\n'
|
||
' </url>\n'
|
||
)
|
||
# Страница API-документации (для запросов «pdf scan api»)
|
||
urls += (
|
||
' <url>\n'
|
||
f' <loc>{SEO_BASE}/developers</loc>\n'
|
||
f' <lastmod>{today}</lastmod>\n'
|
||
' <changefreq>monthly</changefreq>\n'
|
||
' <priority>0.7</priority>\n'
|
||
' </url>\n'
|
||
)
|
||
return HTMLResponse(
|
||
content=(
|
||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n'
|
||
' xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
|
||
f'{urls}'
|
||
'</urlset>\n'
|
||
),
|
||
media_type="application/xml",
|
||
)
|
||
|
||
|
||
@app.post("/api/auth/token")
|
||
async def create_auth_token():
|
||
"""Создаёт одноразовый токен для авторизации через бота."""
|
||
token = secrets.token_hex(16)
|
||
_db_create_auth_token(token)
|
||
url = f"tg://resolve?domain={BOT_USERNAME}&start=webauth_{token}"
|
||
return {"token": token, "url": url, "expires_in": AUTH_TOKEN_TTL}
|
||
|
||
|
||
@app.get("/api/auth/poll/{token}")
|
||
async def poll_auth_token(token: str):
|
||
"""Проверяет статус авторизации по токену."""
|
||
row = _db_poll_auth_token(token)
|
||
if not row:
|
||
raise HTTPException(status_code=404, detail="Token not found")
|
||
if time.time() - row["created_at"] > AUTH_TOKEN_TTL:
|
||
return {"status": "expired"}
|
||
if row["status"] == "verified":
|
||
uid = row["user_id"]
|
||
if uid:
|
||
with _verified_users_lock:
|
||
_verified_users[uid] = time.time()
|
||
_db_mark_verified(uid)
|
||
return {
|
||
"status": "verified",
|
||
"user_id": uid,
|
||
"first_name": row["first_name"] or "",
|
||
"last_name": row["last_name"] or "",
|
||
"username": row["username"] or "",
|
||
}
|
||
return {"status": "pending"}
|
||
|
||
|
||
@app.post("/api/check")
|
||
async def check_auth_required(pages: int = Form(0), size_mb: float = Form(0.0)):
|
||
requires_auth = pages > AUTH_REQUIRED_PAGES or size_mb > AUTH_REQUIRED_MB
|
||
return {"requires_auth": requires_auth}
|
||
|
||
|
||
@app.post("/api/auth/verify")
|
||
async def verify_auth(data: dict):
|
||
if not _verify_telegram_auth(data):
|
||
raise HTTPException(status_code=401, detail="Invalid Telegram auth data")
|
||
try:
|
||
uid = int(data.get("id", 0))
|
||
if uid:
|
||
with _verified_users_lock:
|
||
_verified_users[uid] = time.time()
|
||
_db_mark_verified(uid)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return {"ok": True, "user_id": data.get("id")}
|
||
|
||
|
||
def _count_pdf_pages(content: bytes) -> int:
|
||
"""Быстрый подсчёт страниц по байтам PDF без внешних зависимостей."""
|
||
try:
|
||
matches = re.findall(rb'/Type\s*/Page[^s]', content)
|
||
return len(matches)
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def _write_bytes(path: str, data: bytes) -> None:
|
||
"""Синхронная запись файла — вызывается через asyncio.to_thread, чтобы не блокировать event-loop."""
|
||
with open(path, "wb") as f_out:
|
||
f_out.write(data)
|
||
|
||
|
||
def _read_and_count_pdf(path: str) -> int:
|
||
"""Читает PDF с диска и считает страницы (для запуска в отдельном потоке)."""
|
||
try:
|
||
with open(path, "rb") as f_in:
|
||
return _count_pdf_pages(f_in.read())
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def _safe_remove(path: str) -> None:
|
||
try:
|
||
os.remove(path)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
_UPLOAD_ID_RE = re.compile(r"^[A-Za-z0-9_-]{8,64}$")
|
||
|
||
|
||
def _chunk_part_path(upload_id: str):
|
||
"""Путь к временному .part-файлу чанковой загрузки (с валидацией upload_id)."""
|
||
if not upload_id or not _UPLOAD_ID_RE.match(upload_id):
|
||
return None
|
||
return f"{UPLOAD_DIR}{upload_id}.part"
|
||
|
||
|
||
def _write_chunk_at(path: str, data: bytes, offset: int) -> None:
|
||
"""Пишет кусок по смещению (идемпотентно при ретраях). Вызывается через to_thread."""
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o644)
|
||
try:
|
||
os.pwrite(fd, data, offset)
|
||
finally:
|
||
os.close(fd)
|
||
|
||
|
||
def _finalize_submit(job_id, file_path, original_name, stitching, title,
|
||
numeration, flip_side, color, pdfa, quality,
|
||
size_mb, pages, user_id, trusted=False, ocr=0, web_owner_id=None):
|
||
"""Общий хвост постановки задания: проверка авторизации, запись в БД, _meta.
|
||
trusted=True (бизнес-API по ключу) — пропускает порог авторизации по размеру.
|
||
web_owner_id — TG id владельца для истории «Мои документы» (по умолчанию = user_id)."""
|
||
if not trusted and (size_mb > AUTH_REQUIRED_MB or pages > AUTH_REQUIRED_PAGES):
|
||
verified = False
|
||
if user_id:
|
||
with _verified_users_lock:
|
||
ts = _verified_users.get(user_id)
|
||
if ts and time.time() - ts <= 86400:
|
||
verified = True
|
||
# Фоллбэк на БД — авторизация переживает рестарт контейнера
|
||
if not verified and _db_is_verified(user_id):
|
||
verified = True
|
||
if not verified:
|
||
_safe_remove(file_path)
|
||
raise HTTPException(
|
||
status_code=403,
|
||
detail="Для файлов больше 100 страниц или 50 МБ необходима авторизация через Telegram.",
|
||
)
|
||
|
||
bot_color = _COLOR_MAP.get(color, "цветной")
|
||
owner = web_owner_id if web_owner_id is not None else user_id
|
||
try:
|
||
_db_insert_job(
|
||
name_or_f=job_id,
|
||
stitching=stitching,
|
||
title=title,
|
||
numeration=numeration,
|
||
flip_side=flip_side,
|
||
color=bot_color,
|
||
pdfa=pdfa,
|
||
quality=quality,
|
||
original_name=original_name,
|
||
source_size_mb=size_mb,
|
||
ocr=ocr,
|
||
web_owner_id=owner,
|
||
)
|
||
except Exception as exc:
|
||
_safe_remove(file_path)
|
||
raise HTTPException(status_code=500, detail=f"Ошибка записи в БД: {exc}")
|
||
|
||
with _meta_lock:
|
||
_meta[job_id] = {
|
||
"original_name": original_name,
|
||
"stitching": stitching,
|
||
"created_at": time.time(),
|
||
}
|
||
return {"job_id": job_id}
|
||
|
||
|
||
def _build_zip(items) -> str:
|
||
"""Собирает ZIP из готовых PDF. items = [(src_path, arcname), ...]. Возвращает путь к временному архиву."""
|
||
import tempfile
|
||
import zipfile
|
||
fd, zip_path = tempfile.mkstemp(suffix=".zip", dir=BOT_TEMP)
|
||
os.close(fd)
|
||
# ZIP_STORED: PDF уже сжаты, повторное сжатие только грузит CPU без выгоды
|
||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as zf:
|
||
for src_path, arcname in items:
|
||
zf.write(src_path, arcname=arcname)
|
||
return zip_path
|
||
|
||
|
||
@app.post("/api/submit")
|
||
async def submit(
|
||
file: UploadFile = File(...),
|
||
stitching: str = Form("без сшивки"),
|
||
title: int = Form(0),
|
||
numeration: int = Form(0),
|
||
flip_side: int = Form(0),
|
||
color: str = Form("color"),
|
||
pdfa: int = Form(0),
|
||
quality: str = Form("high"),
|
||
ocr: int = Form(0),
|
||
user_id: int = Form(0),
|
||
):
|
||
original_name = file.filename or "document.pdf"
|
||
src_ext = os.path.splitext(original_name)[1].lower()
|
||
is_doc = src_ext in (".doc", ".docx")
|
||
|
||
# Именование аналогично телеграм-боту: YYYY.MM.DD_HH-MM-SS_имя_файла
|
||
_stem = os.path.splitext(original_name)[0].replace("'", "").replace(":", "")
|
||
job_id = f"{datetime.datetime.now().strftime('%Y.%m.%d_%H-%M-%S')}_{_stem}"
|
||
file_path = f"{BOT_TEMP}{job_id}.pdf"
|
||
|
||
content = await file.read()
|
||
size_mb = len(content) / (1024 * 1024)
|
||
|
||
if is_doc:
|
||
# Сохраняем оригинальный Word-документ во временный файл
|
||
src_path = f"{BOT_TEMP}{job_id}{src_ext}"
|
||
try:
|
||
await asyncio.to_thread(_write_bytes, src_path, content)
|
||
except Exception as exc:
|
||
raise HTTPException(status_code=500, detail=f"Не удалось сохранить файл: {exc}")
|
||
# Конвертируем в PDF через libreoffice
|
||
try:
|
||
await asyncio.to_thread(_convert_doc_to_pdf, src_path, file_path)
|
||
except Exception as exc:
|
||
try:
|
||
os.remove(src_path)
|
||
except Exception:
|
||
pass
|
||
raise HTTPException(status_code=500, detail=f"Не удалось конвертировать DOC/DOCX: {exc}")
|
||
finally:
|
||
try:
|
||
os.remove(src_path)
|
||
except Exception:
|
||
pass
|
||
# Считаем страницы из конвертированного PDF
|
||
pages = await asyncio.to_thread(_read_and_count_pdf, file_path)
|
||
else:
|
||
pages = await asyncio.to_thread(_count_pdf_pages, content)
|
||
try:
|
||
await asyncio.to_thread(_write_bytes, file_path, content)
|
||
except Exception as exc:
|
||
raise HTTPException(status_code=500, detail=f"Не удалось сохранить файл: {exc}")
|
||
|
||
return _finalize_submit(
|
||
job_id, file_path, original_name, stitching, title,
|
||
numeration, flip_side, color, pdfa, quality, size_mb, pages, user_id,
|
||
ocr=ocr,
|
||
)
|
||
|
||
|
||
@app.post("/api/upload-chunk")
|
||
async def upload_chunk(
|
||
upload_id: str = Form(...),
|
||
offset: int = Form(...),
|
||
chunk: UploadFile = File(...),
|
||
):
|
||
"""Приём одного куска файла (чанковая загрузка в обход потолка туннеля)."""
|
||
part_path = _chunk_part_path(upload_id)
|
||
if not part_path:
|
||
raise HTTPException(status_code=400, detail="Bad upload_id")
|
||
if offset < 0 or offset > MAX_UPLOAD_BYTES:
|
||
raise HTTPException(status_code=400, detail="Bad offset")
|
||
data = await chunk.read()
|
||
if len(data) > MAX_CHUNK_BYTES:
|
||
raise HTTPException(status_code=413, detail="Chunk too large")
|
||
if offset + len(data) > MAX_UPLOAD_BYTES:
|
||
raise HTTPException(status_code=413, detail="Upload too large")
|
||
await asyncio.to_thread(_write_chunk_at, part_path, data, offset)
|
||
return {"ok": True}
|
||
|
||
|
||
@app.post("/api/submit-chunked")
|
||
async def submit_chunked(
|
||
upload_id: str = Form(...),
|
||
filename: str = Form("document.pdf"),
|
||
total_size: int = Form(0),
|
||
stitching: str = Form("без сшивки"),
|
||
title: int = Form(0),
|
||
numeration: int = Form(0),
|
||
flip_side: int = Form(0),
|
||
color: str = Form("color"),
|
||
pdfa: int = Form(0),
|
||
quality: str = Form("high"),
|
||
ocr: int = Form(0),
|
||
user_id: int = Form(0),
|
||
):
|
||
"""Финализация чанковой загрузки: собранный .part становится заданием в очереди."""
|
||
part_path = _chunk_part_path(upload_id)
|
||
if not part_path or not os.path.exists(part_path):
|
||
raise HTTPException(status_code=404, detail="Загрузка не найдена")
|
||
actual = os.path.getsize(part_path)
|
||
if total_size and actual != total_size:
|
||
_safe_remove(part_path)
|
||
raise HTTPException(status_code=400, detail=f"Размер не совпал ({actual} != {total_size})")
|
||
|
||
original_name = filename or "document.pdf"
|
||
src_ext = os.path.splitext(original_name)[1].lower()
|
||
is_doc = src_ext in (".doc", ".docx")
|
||
_stem = os.path.splitext(original_name)[0].replace("'", "").replace(":", "")
|
||
job_id = f"{datetime.datetime.now().strftime('%Y.%m.%d_%H-%M-%S')}_{_stem}"
|
||
file_path = f"{BOT_TEMP}{job_id}.pdf"
|
||
size_mb = actual / (1024 * 1024)
|
||
|
||
try:
|
||
if is_doc:
|
||
src_path = f"{BOT_TEMP}{job_id}{src_ext}"
|
||
await asyncio.to_thread(os.replace, part_path, src_path)
|
||
try:
|
||
await asyncio.to_thread(_convert_doc_to_pdf, src_path, file_path)
|
||
finally:
|
||
_safe_remove(src_path)
|
||
pages = await asyncio.to_thread(_read_and_count_pdf, file_path)
|
||
else:
|
||
await asyncio.to_thread(os.replace, part_path, file_path)
|
||
pages = await asyncio.to_thread(_read_and_count_pdf, file_path)
|
||
except HTTPException:
|
||
raise
|
||
except Exception as exc:
|
||
_safe_remove(part_path)
|
||
_safe_remove(file_path)
|
||
raise HTTPException(status_code=500, detail=f"Не удалось обработать файл: {exc}")
|
||
|
||
return _finalize_submit(
|
||
job_id, file_path, original_name, stitching, title,
|
||
numeration, flip_side, color, pdfa, quality, size_mb, pages, user_id,
|
||
ocr=ocr,
|
||
)
|
||
|
||
|
||
@app.get("/api/status/{job_id}")
|
||
async def status(job_id: str):
|
||
url_res_f = _db_get_url_res_f(job_id)
|
||
|
||
if url_res_f is None:
|
||
raise HTTPException(status_code=404, detail="Job not found")
|
||
|
||
if url_res_f in ("-", "", None):
|
||
pos = _db_queue_position(job_id)
|
||
if pos <= 1:
|
||
# передний в очереди — бот его сейчас и обрабатывает (он не пишет 'processing' в БД)
|
||
return {"status": "processing", "progress": 50, "queue_pos": 0, "error": None}
|
||
return {"status": "queued", "progress": 0, "queue_pos": pos, "error": None}
|
||
|
||
if url_res_f in ("processing", "uploading"):
|
||
return {"status": "processing", "progress": 50, "queue_pos": 0, "error": None}
|
||
|
||
if url_res_f in ("ошибка", "error"):
|
||
return {"status": "error", "progress": 0, "queue_pos": 0, "error": "Ошибка обработки"}
|
||
|
||
if url_res_f == "cancelled":
|
||
return {"status": "error", "progress": 0, "queue_pos": 0, "error": "Обработка отменена"}
|
||
|
||
if url_res_f == "expired":
|
||
return {"status": "error", "progress": 0, "queue_pos": 0, "error": "Ссылка истекла. Отправьте файл заново."}
|
||
|
||
if url_res_f == "web_local":
|
||
# Считаем оставшееся время
|
||
with _meta_lock:
|
||
meta = _meta.get(job_id, {})
|
||
created_at = meta.get("created_at", time.time())
|
||
expires_in = max(0, int(RESULT_TTL - (time.time() - created_at)))
|
||
return {"status": "done", "progress": 100, "queue_pos": 0, "error": None, "expires_in": expires_in}
|
||
|
||
# Любой другой непустой статус — тоже готово
|
||
return {"status": "done", "progress": 100, "queue_pos": 0, "error": None}
|
||
|
||
|
||
def _make_download_response(job_id: str) -> FileResponse:
|
||
"""Готовит FileResponse с результатом задания (общий код для веба и бизнес-API)."""
|
||
url_res_f = _db_get_url_res_f(job_id)
|
||
if url_res_f != "web_local":
|
||
raise HTTPException(status_code=409, detail="Not ready")
|
||
|
||
with _meta_lock:
|
||
meta = _meta.get(job_id, {})
|
||
original_name = meta.get("original_name")
|
||
stitching = meta.get("stitching")
|
||
if not original_name or not stitching:
|
||
db_name, db_st = _db_get_job_meta(job_id) # фоллбэк на БД (переживает рестарт)
|
||
original_name = original_name or db_name or "document.pdf"
|
||
stitching = stitching or db_st or "без сшивки"
|
||
base = os.path.splitext(original_name)[0]
|
||
download_name = f"{base} скан.pdf"
|
||
result_path = f"{BOT_TEMP}{job_id} скан {stitching}.pdf"
|
||
|
||
if not os.path.exists(result_path):
|
||
_db_set_url_res_f(job_id, "expired")
|
||
raise HTTPException(status_code=404, detail="Файл не найден или уже удалён")
|
||
|
||
return FileResponse(
|
||
result_path,
|
||
media_type="application/pdf",
|
||
filename=download_name,
|
||
)
|
||
|
||
|
||
@app.get("/api/download/{job_id}")
|
||
async def download(job_id: str):
|
||
return _make_download_response(job_id)
|
||
|
||
|
||
def _collect_zip_items(job_ids):
|
||
"""[(result_path, arcname)] для готовых заданий (имена из _meta или БД)."""
|
||
items = []
|
||
used = set()
|
||
for jid in job_ids:
|
||
if not isinstance(jid, str):
|
||
continue
|
||
if _db_get_url_res_f(jid) != "web_local":
|
||
continue
|
||
with _meta_lock:
|
||
meta = _meta.get(jid, {})
|
||
original_name = meta.get("original_name")
|
||
stitching = meta.get("stitching")
|
||
if not original_name or not stitching:
|
||
db_name, db_st = _db_get_job_meta(jid)
|
||
original_name = original_name or db_name or "document.pdf"
|
||
stitching = stitching or db_st or "без сшивки"
|
||
result_path = f"{BOT_TEMP}{jid} скан {stitching}.pdf"
|
||
if not os.path.exists(result_path):
|
||
continue
|
||
base = os.path.splitext(os.path.basename(original_name))[0]
|
||
arcname = f"{base} скан.pdf"
|
||
n = 1
|
||
while arcname in used:
|
||
n += 1
|
||
arcname = f"{base} скан ({n}).pdf"
|
||
used.add(arcname)
|
||
items.append((result_path, arcname))
|
||
return items
|
||
|
||
|
||
def _zip_build_worker(zip_id, items):
|
||
"""Фоновая сборка ZIP (большие архивы не успевают за таймаут заголовков прокси)."""
|
||
try:
|
||
path = _build_zip(items)
|
||
with _zip_jobs_lock:
|
||
j = _zip_jobs.get(zip_id)
|
||
if j is not None:
|
||
j["status"] = "ready"
|
||
j["path"] = path
|
||
except Exception as exc:
|
||
with _zip_jobs_lock:
|
||
j = _zip_jobs.get(zip_id)
|
||
if j is not None:
|
||
j["status"] = "error"
|
||
j["error"] = str(exc)
|
||
|
||
|
||
@app.post("/api/zip/prepare")
|
||
async def zip_prepare(payload: dict):
|
||
"""Старт фоновой сборки ZIP. Возвращает zip_id; статус — /api/zip/status."""
|
||
job_ids = payload.get("job_ids") if isinstance(payload, dict) else None
|
||
if not isinstance(job_ids, list) or not job_ids:
|
||
raise HTTPException(status_code=400, detail="job_ids required")
|
||
if len(job_ids) > 20:
|
||
raise HTTPException(status_code=400, detail="Слишком много файлов (максимум 20)")
|
||
items = _collect_zip_items(job_ids)
|
||
if not items:
|
||
raise HTTPException(status_code=409, detail="Нет готовых файлов для архива")
|
||
zip_id = secrets.token_hex(8)
|
||
download_name = f"pdf2scan_{datetime.datetime.now().strftime('%Y-%m-%d')}.zip"
|
||
with _zip_jobs_lock:
|
||
_zip_jobs[zip_id] = {"status": "building", "created_at": time.time(), "name": download_name}
|
||
threading.Thread(target=_zip_build_worker, args=(zip_id, items), daemon=True).start()
|
||
return {"zip_id": zip_id, "name": download_name}
|
||
|
||
|
||
@app.get("/api/zip/status/{zip_id}")
|
||
async def zip_status(zip_id: str):
|
||
with _zip_jobs_lock:
|
||
j = _zip_jobs.get(zip_id)
|
||
if not j:
|
||
raise HTTPException(status_code=404, detail="not found")
|
||
return {"status": j.get("status"), "name": j.get("name"), "error": j.get("error")}
|
||
|
||
|
||
@app.get("/api/zip/file/{zip_id}")
|
||
async def zip_file(zip_id: str):
|
||
with _zip_jobs_lock:
|
||
j = _zip_jobs.get(zip_id)
|
||
if not j or j.get("status") != "ready" or not j.get("path") or not os.path.exists(j["path"]):
|
||
raise HTTPException(status_code=404, detail="Архив не готов")
|
||
path = j["path"]
|
||
name = j.get("name", "pdf2scan.zip")
|
||
|
||
def _cleanup():
|
||
_safe_remove(path)
|
||
with _zip_jobs_lock:
|
||
_zip_jobs.pop(zip_id, None)
|
||
|
||
return FileResponse(
|
||
path,
|
||
media_type="application/zip",
|
||
filename=name,
|
||
background=BackgroundTask(_cleanup),
|
||
)
|
||
|
||
|
||
# ══════════════════════════════════════════════════════════════════════════════
|
||
# Бизнес-API (доступ по ключу) — /api/v1/*
|
||
# ══════════════════════════════════════════════════════════════════════════════
|
||
API_RATE_PER_MIN = 60 # мягкий лимит запросов в минуту на ключ
|
||
_api_rate: dict[str, list] = {}
|
||
_api_rate_lock = threading.Lock()
|
||
|
||
|
||
def _db_create_api_key(owner_id: int, name: str, plan: str = "free") -> str:
|
||
key = "sk_" + secrets.token_hex(24)
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute(
|
||
"INSERT INTO WEB_API_KEYS (api_key, owner_id, name, plan, active, req_count, created_at) "
|
||
"VALUES (?, ?, ?, ?, 1, 0, ?)",
|
||
(key, int(owner_id or 0), (name or "key")[:64], plan, time.time()),
|
||
)
|
||
con.commit()
|
||
return key
|
||
|
||
|
||
def _db_get_api_key(key: str):
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute(
|
||
"SELECT api_key, owner_id, name, plan, active, req_count "
|
||
"FROM WEB_API_KEYS WHERE api_key = ?",
|
||
(key,),
|
||
)
|
||
row = cur.fetchone()
|
||
if not row:
|
||
return None
|
||
return {
|
||
"api_key": row[0], "owner_id": row[1], "name": row[2],
|
||
"plan": row[3], "active": row[4], "req_count": row[5],
|
||
}
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _db_touch_api_key(key: str):
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
con.execute(
|
||
"UPDATE WEB_API_KEYS SET req_count = req_count + 1, last_req = ? WHERE api_key = ?",
|
||
(time.time(), key),
|
||
)
|
||
con.commit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _extract_api_key(request: Request) -> str | None:
|
||
auth = request.headers.get("authorization") or ""
|
||
if auth.lower().startswith("bearer "):
|
||
return auth[7:].strip()
|
||
return request.headers.get("x-api-key")
|
||
|
||
|
||
def _require_api_key(request: Request) -> dict:
|
||
key = _extract_api_key(request)
|
||
if not key:
|
||
raise HTTPException(
|
||
status_code=401,
|
||
detail="Missing API key. Use 'Authorization: Bearer <key>' or 'X-API-Key' header.",
|
||
)
|
||
row = _db_get_api_key(key)
|
||
if not row or not row.get("active"):
|
||
raise HTTPException(status_code=401, detail="Invalid or inactive API key.")
|
||
now = time.time()
|
||
with _api_rate_lock:
|
||
bucket = [t for t in _api_rate.get(key, []) if now - t < 60]
|
||
if len(bucket) >= API_RATE_PER_MIN:
|
||
raise HTTPException(status_code=429, detail=f"Rate limit exceeded ({API_RATE_PER_MIN}/min).")
|
||
bucket.append(now)
|
||
_api_rate[key] = bucket
|
||
_db_touch_api_key(key)
|
||
return row
|
||
|
||
|
||
@app.post("/api/v1/keys")
|
||
async def api_create_key(token: str = Form(...), name: str = Form("api")):
|
||
"""Самовыдача ключа: нужен подтверждённый auth-токen (после входа через Telegram-бота)."""
|
||
row = _db_poll_auth_token(token)
|
||
if not row or row.get("status") != "verified" or not row.get("user_id"):
|
||
raise HTTPException(status_code=401, detail="Требуется вход через Telegram (verified token).")
|
||
key = _db_create_api_key(row["user_id"], name)
|
||
return {"api_key": key, "plan": "free", "rate_limit_per_min": API_RATE_PER_MIN,
|
||
"note": "Сохраните ключ — он показывается один раз."}
|
||
|
||
|
||
@app.post("/api/v1/scan")
|
||
async def api_scan(
|
||
request: Request,
|
||
file: UploadFile = File(...),
|
||
stitching: str = Form("без сшивки"),
|
||
title: int = Form(0),
|
||
numeration: int = Form(0),
|
||
flip_side: int = Form(0),
|
||
color: str = Form("color"),
|
||
pdfa: int = Form(0),
|
||
quality: str = Form("high"),
|
||
ocr: int = Form(0),
|
||
):
|
||
"""Постановка файла в обработку по API-ключу. Возвращает job_id."""
|
||
key_row = _require_api_key(request)
|
||
|
||
original_name = file.filename or "document.pdf"
|
||
src_ext = os.path.splitext(original_name)[1].lower()
|
||
is_doc = src_ext in (".doc", ".docx")
|
||
_stem = os.path.splitext(original_name)[0].replace("'", "").replace(":", "")
|
||
job_id = f"{datetime.datetime.now().strftime('%Y.%m.%d_%H-%M-%S')}_{_stem}"
|
||
file_path = f"{BOT_TEMP}{job_id}.pdf"
|
||
|
||
content = await file.read()
|
||
size_mb = len(content) / (1024 * 1024)
|
||
if size_mb > MAX_UPLOAD_BYTES / (1024 * 1024):
|
||
raise HTTPException(status_code=413, detail="File too large")
|
||
|
||
if is_doc:
|
||
src_path = f"{BOT_TEMP}{job_id}{src_ext}"
|
||
await asyncio.to_thread(_write_bytes, src_path, content)
|
||
try:
|
||
await asyncio.to_thread(_convert_doc_to_pdf, src_path, file_path)
|
||
except Exception as exc:
|
||
_safe_remove(src_path)
|
||
raise HTTPException(status_code=500, detail=f"DOC/DOCX convert failed: {exc}")
|
||
finally:
|
||
_safe_remove(src_path)
|
||
pages = await asyncio.to_thread(_read_and_count_pdf, file_path)
|
||
else:
|
||
pages = await asyncio.to_thread(_count_pdf_pages, content)
|
||
await asyncio.to_thread(_write_bytes, file_path, content)
|
||
|
||
result = _finalize_submit(
|
||
job_id, file_path, original_name, stitching, title,
|
||
numeration, flip_side, color, pdfa, quality, size_mb, pages,
|
||
user_id=WEB_USER_ID, trusted=True, ocr=ocr,
|
||
web_owner_id=key_row.get("owner_id") or 0,
|
||
)
|
||
return {"job_id": result["job_id"], "pages": pages,
|
||
"status_url": f"/api/v1/scan/{result['job_id']}",
|
||
"download_url": f"/api/v1/scan/{result['job_id']}/download"}
|
||
|
||
|
||
@app.get("/api/v1/scan/{job_id}")
|
||
async def api_scan_status(request: Request, job_id: str):
|
||
"""Статус задания по API-ключу: queued / processing / done / error."""
|
||
_require_api_key(request)
|
||
url_res_f = _db_get_url_res_f(job_id)
|
||
if url_res_f is None:
|
||
raise HTTPException(status_code=404, detail="Job not found")
|
||
if url_res_f in ("-", "", None):
|
||
pos = _db_queue_position(job_id)
|
||
if pos <= 1:
|
||
return {"status": "processing", "queue_pos": 0}
|
||
return {"status": "queued", "queue_pos": pos}
|
||
if url_res_f in ("processing", "uploading"):
|
||
return {"status": "processing", "queue_pos": 0}
|
||
if url_res_f in ("ошибка", "error"):
|
||
return {"status": "error", "error": "processing failed"}
|
||
if url_res_f == "cancelled":
|
||
return {"status": "error", "error": "cancelled"}
|
||
if url_res_f == "expired":
|
||
return {"status": "error", "error": "expired"}
|
||
return {"status": "done", "download_url": f"/api/v1/scan/{job_id}/download"}
|
||
|
||
|
||
@app.get("/api/v1/scan/{job_id}/download")
|
||
async def api_scan_download(request: Request, job_id: str):
|
||
"""Скачивание результата по API-ключу."""
|
||
_require_api_key(request)
|
||
return _make_download_response(job_id)
|
||
|
||
|
||
# ── Личный кабинет: история «Мои документы» ───────────────────────────────────
|
||
def _db_history(owner_id: int, limit: int = 40):
|
||
"""Последние веб-задания владельца (для личного кабинета)."""
|
||
rows = []
|
||
try:
|
||
with sqlite3.connect(DB_PATH, timeout=10) as con:
|
||
cur = con.cursor()
|
||
cur.execute("PRAGMA table_info(FILES)")
|
||
cols = {r[1] for r in cur.fetchall()}
|
||
if "web_owner_id" not in cols:
|
||
return rows
|
||
oname = "original_name" if "original_name" in cols else "name_or_f"
|
||
cur.execute(
|
||
f"SELECT name_or_f, {oname}, date, time, url_res_f, stitching "
|
||
"FROM FILES WHERE web_owner_id = ? ORDER BY rowid DESC LIMIT ?",
|
||
(int(owner_id), limit),
|
||
)
|
||
for r in cur.fetchall():
|
||
job_id, name, date, tm, url_res_f, stitching = r
|
||
if url_res_f == "web_local":
|
||
result_path = f"{BOT_TEMP}{job_id} скан {stitching}.pdf"
|
||
st = "available" if os.path.exists(result_path) else "expired"
|
||
elif url_res_f in ("-", "", None):
|
||
st = "processing"
|
||
elif url_res_f in ("ошибка", "error"):
|
||
st = "error"
|
||
else:
|
||
st = "expired"
|
||
rows.append({
|
||
"job_id": job_id, "name": name or "document.pdf",
|
||
"date": date, "time": tm, "status": st,
|
||
})
|
||
except Exception as exc:
|
||
print(f"history error: {exc}")
|
||
return rows
|
||
|
||
|
||
@app.get("/api/history/{user_id}")
|
||
async def history(user_id: int):
|
||
"""История документов пользователя. Только для подтверждённых (вошедших) юзеров."""
|
||
if not user_id or not _db_is_verified(user_id):
|
||
raise HTTPException(status_code=403, detail="Требуется вход через Telegram.")
|
||
return {"items": _db_history(user_id)}
|
||
|
||
|
||
# ── Загрузка ZIP: распаковка и постановка каждого PDF/DOCX в очередь ───────────
|
||
def _unpack_zip_and_enqueue(part_path: str, settings: dict, user_id: int) -> list[dict]:
|
||
"""Распаковывает ZIP, ставит в очередь каждый вложенный PDF/DOC(X). Возвращает [{job_id,name}]."""
|
||
import zipfile
|
||
created = []
|
||
verified = bool(user_id) and (_db_is_verified(user_id) or (
|
||
_verified_users.get(user_id, 0) and time.time() - _verified_users[user_id] <= 86400))
|
||
try:
|
||
with zipfile.ZipFile(part_path) as zf:
|
||
names = [n for n in zf.namelist()
|
||
if not n.endswith("/") and os.path.splitext(n)[1].lower() in (".pdf", ".doc", ".docx")]
|
||
names = names[:20] # не больше 20 файлов за раз
|
||
for inner in names:
|
||
ext = os.path.splitext(inner)[1].lower()
|
||
base = os.path.basename(inner) or f"file{ext}"
|
||
_stem = os.path.splitext(base)[0].replace("'", "").replace(":", "")
|
||
job_id = f"{datetime.datetime.now().strftime('%Y.%m.%d_%H-%M-%S')}_{_stem}_{secrets.token_hex(2)}"
|
||
file_path = f"{BOT_TEMP}{job_id}.pdf"
|
||
data = zf.read(inner)
|
||
size_mb = len(data) / (1024 * 1024)
|
||
try:
|
||
if ext in (".doc", ".docx"):
|
||
src_path = f"{BOT_TEMP}{job_id}{ext}"
|
||
_write_bytes(src_path, data)
|
||
try:
|
||
_convert_doc_to_pdf(src_path, file_path)
|
||
finally:
|
||
_safe_remove(src_path)
|
||
pages = _read_and_count_pdf(file_path)
|
||
else:
|
||
_write_bytes(file_path, data)
|
||
pages = _count_pdf_pages(data)
|
||
# авторизация по порогу — как в обычном submit (кроме verified)
|
||
if not verified and (size_mb > AUTH_REQUIRED_MB or pages > AUTH_REQUIRED_PAGES):
|
||
_safe_remove(file_path)
|
||
continue
|
||
_finalize_submit(
|
||
job_id, file_path, base, settings.get("stitching", "без сшивки"),
|
||
settings.get("title", 0), settings.get("numeration", 0),
|
||
settings.get("flip_side", 0), settings.get("color", "color"),
|
||
settings.get("pdfa", 0), settings.get("quality", "high"),
|
||
size_mb, pages, user_id, trusted=True, ocr=settings.get("ocr", 0),
|
||
web_owner_id=user_id,
|
||
)
|
||
created.append({"job_id": job_id, "name": base})
|
||
except Exception as exc:
|
||
print(f"zip entry '{inner}' failed: {exc}")
|
||
_safe_remove(file_path)
|
||
finally:
|
||
_safe_remove(part_path)
|
||
return created
|
||
|
||
|
||
@app.post("/api/submit-zip-chunked")
|
||
async def submit_zip_chunked(
|
||
upload_id: str = Form(...),
|
||
total_size: int = Form(0),
|
||
stitching: str = Form("без сшивки"),
|
||
title: int = Form(0),
|
||
numeration: int = Form(0),
|
||
flip_side: int = Form(0),
|
||
color: str = Form("color"),
|
||
pdfa: int = Form(0),
|
||
quality: str = Form("high"),
|
||
ocr: int = Form(0),
|
||
user_id: int = Form(0),
|
||
):
|
||
"""Финализация загруженного ZIP: распаковать и поставить вложенные файлы в очередь."""
|
||
part_path = _chunk_part_path(upload_id)
|
||
if not part_path or not os.path.exists(part_path):
|
||
raise HTTPException(status_code=404, detail="Загрузка не найдена")
|
||
actual = os.path.getsize(part_path)
|
||
if total_size and actual != total_size:
|
||
_safe_remove(part_path)
|
||
raise HTTPException(status_code=400, detail=f"Размер не совпал ({actual} != {total_size})")
|
||
settings = {
|
||
"stitching": stitching, "title": title, "numeration": numeration,
|
||
"flip_side": flip_side, "color": color, "pdfa": pdfa, "quality": quality, "ocr": ocr,
|
||
}
|
||
created = await asyncio.to_thread(_unpack_zip_and_enqueue, part_path, settings, user_id)
|
||
if not created:
|
||
raise HTTPException(status_code=400, detail="В архиве нет подходящих файлов (PDF/DOC/DOCX) или превышен лимит/порог авторизации.")
|
||
return {"jobs": created}
|
||
|
||
|
||
_API_DOCS_HTML = """<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>pdf2scan API — scan effect PDF API for business</title>
|
||
<meta name="description" content="pdf2scan REST API: add a scan effect, binding, page numbering and PDF/A to PDF and Word files programmatically. API for business integrations.">
|
||
<link rel="canonical" href="https://pdf2scan.online/developers">
|
||
<style>
|
||
:root{--bg:#0b1220;--card:#131c2e;--txt:#e7eefc;--sub:#9fb3d1;--acc:#3b93ff;--code:#0a2540;--border:#22314a;}
|
||
*{box-sizing:border-box}
|
||
body{margin:0;background:linear-gradient(160deg,#0b1220,#0e1830);color:var(--txt);
|
||
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;
|
||
line-height:1.6;padding:0 16px}
|
||
.wrap{max-width:860px;margin:0 auto;padding:48px 0 80px}
|
||
a{color:var(--acc);text-decoration:none} a:hover{text-decoration:underline}
|
||
h1{font-size:34px;margin:0 0 6px} h2{font-size:22px;margin:38px 0 12px}
|
||
h3{font-size:17px;margin:22px 0 8px;color:var(--sub)}
|
||
.sub{color:var(--sub);font-size:16px;margin-bottom:8px}
|
||
.badge{display:inline-block;background:#12325a;color:#9cd0ff;border-radius:20px;padding:3px 12px;font-size:13px;margin-bottom:22px}
|
||
.card{background:var(--card);border:1px solid #1e2b45;border-radius:14px;padding:20px 22px;margin:16px 0}
|
||
pre{background:var(--code);border:1px solid #16365c;border-radius:10px;padding:14px 16px;overflow-x:auto;font-size:13.5px}
|
||
code{font-family:'SF Mono',Menlo,Consolas,monospace}
|
||
.meth{display:inline-block;font-weight:700;font-size:12px;padding:2px 9px;border-radius:6px;margin-right:8px;vertical-align:middle}
|
||
.post{background:#1c4a2b;color:#7ee2a1} .get{background:#123a63;color:#7cc0ff}
|
||
table{width:100%;border-collapse:collapse;font-size:14px;margin:8px 0}
|
||
td,th{border-bottom:1px solid #1e2b45;padding:8px 6px;text-align:left;vertical-align:top}
|
||
th{color:var(--sub);font-weight:600}
|
||
.toplink{font-size:14px}
|
||
.foot{margin-top:44px;color:var(--sub);font-size:14px;border-top:1px solid #1e2b45;padding-top:18px}
|
||
.lead{background:#10233f;border-left:3px solid var(--acc);padding:12px 16px;border-radius:8px;margin:14px 0}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="wrap">
|
||
<div class="toplink"><a href="/">← pdf2scan.online</a></div>
|
||
<h1>pdf2scan API</h1>
|
||
<div class="badge">REST · JSON · for business</div>
|
||
<p class="sub">Программно превращайте PDF и Word в «скан»: эффект сканирования, сшивка, нумерация, титульный лист, PDF/A. Идеально для юрфирм, бухгалтерий, документооборота и тендерных отделов.</p>
|
||
<p class="sub"><em>Programmatically turn PDF/Word into scanned documents — scan effect, binding, numbering, PDF/A. Built for integrations.</em></p>
|
||
|
||
<div class="lead">
|
||
<strong>Базовый URL / Base URL:</strong> <code>https://pdf2scan.online/api/v1</code><br>
|
||
<strong>Аутентификация:</strong> заголовок <code>Authorization: Bearer <api_key></code> или <code>X-API-Key: <api_key></code><br>
|
||
<strong>Лимит:</strong> 60 запросов/мин на ключ (пробный тариф).
|
||
</div>
|
||
|
||
<h2>1. Получить ключ / Get an API key</h2>
|
||
<div class="card">
|
||
<p>Ключи привязаны к Telegram-аккаунту. Пока сервис бесплатный (тарифы и оплату добавим позже).</p>
|
||
<button id="genkey-btn" onclick="genKey()" style="background:var(--acc);color:#04121f;border:none;border-radius:10px;padding:11px 20px;font-size:15px;font-weight:700;cursor:pointer">🔑 Сгенерировать ключ через Telegram</button>
|
||
<div id="genkey-status" style="margin-top:12px;color:var(--sub);font-size:14px"></div>
|
||
<div id="genkey-result" style="display:none;margin-top:12px">
|
||
<p style="margin:0 0 6px;color:var(--sub);font-size:13px">Ваш ключ (показывается один раз — сохраните!):</p>
|
||
<pre style="margin:0"><code id="genkey-value"></code></pre>
|
||
</div>
|
||
<p style="margin-top:14px">Либо напишите <a href="https://t.me/berkio" target="_blank" rel="noopener">@berkio</a> — выдадим ключ вручную.</p>
|
||
</div>
|
||
|
||
<h2>2. Отправить файл / Submit a file</h2>
|
||
<div class="card">
|
||
<p><span class="meth post">POST</span><code>/api/v1/scan</code> — multipart/form-data</p>
|
||
<table>
|
||
<tr><th>Поле</th><th>Тип</th><th>По умолчанию</th><th>Описание</th></tr>
|
||
<tr><td>file</td><td>file</td><td>—</td><td>PDF / DOC / DOCX</td></tr>
|
||
<tr><td>stitching</td><td>string</td><td>без сшивки</td><td>нитка · ленточка · уголок · пружинка · дырокол · без сшивки</td></tr>
|
||
<tr><td>color</td><td>string</td><td>color</td><td><code>color</code> или <code>bw</code></td></tr>
|
||
<tr><td>quality</td><td>string</td><td>high</td><td><code>high</code> (300 DPI) · <code>medium</code> (250) · <code>low</code> (200)</td></tr>
|
||
<tr><td>numeration</td><td>0/1</td><td>0</td><td>нумерация страниц</td></tr>
|
||
<tr><td>title</td><td>0/1</td><td>0</td><td>титульный лист</td></tr>
|
||
<tr><td>flip_side</td><td>0/1</td><td>0</td><td>лист «прошито-пронумеровано»</td></tr>
|
||
<tr><td>pdfa</td><td>0/1</td><td>0</td><td>формат PDF/A</td></tr>
|
||
</table>
|
||
<h3>Пример / Example</h3>
|
||
<pre><code>curl -X POST https://pdf2scan.online/api/v1/scan \\
|
||
-H "Authorization: Bearer sk_your_key_here" \\
|
||
-F "file=@document.pdf" \\
|
||
-F "stitching=нитка" \\
|
||
-F "color=bw" \\
|
||
-F "numeration=1" \\
|
||
-F "pdfa=1"</code></pre>
|
||
<h3>Ответ / Response</h3>
|
||
<pre><code>{
|
||
"job_id": "2026.07.02_12-40-11_document",
|
||
"pages": 14,
|
||
"status_url": "/api/v1/scan/2026.07.02_12-40-11_document",
|
||
"download_url": "/api/v1/scan/2026.07.02_12-40-11_document/download"
|
||
}</code></pre>
|
||
</div>
|
||
|
||
<h2>3. Проверить статус / Check status</h2>
|
||
<div class="card">
|
||
<p><span class="meth get">GET</span><code>/api/v1/scan/{job_id}</code></p>
|
||
<pre><code>curl https://pdf2scan.online/api/v1/scan/JOB_ID \\
|
||
-H "Authorization: Bearer sk_your_key_here"
|
||
|
||
# { "status": "queued", "queue_pos": 3 }
|
||
# { "status": "processing", "queue_pos": 0 }
|
||
# { "status": "done", "download_url": "/api/v1/scan/JOB_ID/download" }</code></pre>
|
||
</div>
|
||
|
||
<h2>4. Скачать результат / Download result</h2>
|
||
<div class="card">
|
||
<p><span class="meth get">GET</span><code>/api/v1/scan/{job_id}/download</code> — возвращает PDF (готов ~6 часов).</p>
|
||
<pre><code>curl -L https://pdf2scan.online/api/v1/scan/JOB_ID/download \\
|
||
-H "Authorization: Bearer sk_your_key_here" \\
|
||
-o scan.pdf</code></pre>
|
||
</div>
|
||
|
||
<h2>Коды ошибок / Errors</h2>
|
||
<div class="card">
|
||
<table>
|
||
<tr><th>Код</th><th>Значение</th></tr>
|
||
<tr><td>401</td><td>Нет ключа / ключ неверный или отключён</td></tr>
|
||
<tr><td>409</td><td>Файл ещё не готов (проверьте статус)</td></tr>
|
||
<tr><td>413</td><td>Файл слишком большой</td></tr>
|
||
<tr><td>429</td><td>Превышен лимит запросов</td></tr>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="foot">
|
||
pdf2scan.online · <a href="/">Главная</a> · Вопросы по API — <a href="https://t.me/berkio" target="_blank" rel="noopener">@berkio</a>
|
||
</div>
|
||
</div>
|
||
<script>
|
||
var BOT = 'pdf2scan_pybot';
|
||
var pollTimer = null;
|
||
function setStatus(t){ document.getElementById('genkey-status').textContent = t; }
|
||
async function genKey(){
|
||
var btn = document.getElementById('genkey-btn');
|
||
btn.disabled = true;
|
||
setStatus('Создаём сессию входа...');
|
||
try{
|
||
var r = await fetch('/api/auth/token', {method:'POST'});
|
||
var d = await r.json();
|
||
var token = d.token;
|
||
window.open('https://t.me/' + BOT + '?start=webauth_' + token, '_blank');
|
||
setStatus('Откройте Telegram-бота и нажмите Start — ключ появится здесь автоматически...');
|
||
var tries = 0;
|
||
pollTimer = setInterval(async function(){
|
||
tries++;
|
||
if (tries > 150){ clearInterval(pollTimer); setStatus('Время ожидания истекло. Попробуйте снова.'); btn.disabled=false; return; }
|
||
try{
|
||
var pr = await fetch('/api/auth/poll/' + token);
|
||
if (!pr.ok) return;
|
||
var pd = await pr.json();
|
||
if (pd.status === 'verified'){
|
||
clearInterval(pollTimer);
|
||
setStatus('Вход подтверждён, выпускаем ключ...');
|
||
var fd = new FormData(); fd.append('token', token); fd.append('name', 'web');
|
||
var kr = await fetch('/api/v1/keys', {method:'POST', body: fd});
|
||
var kd = await kr.json();
|
||
if (kd.api_key){
|
||
document.getElementById('genkey-value').textContent = kd.api_key;
|
||
document.getElementById('genkey-result').style.display = 'block';
|
||
setStatus('Готово! Лимит: ' + kd.rate_limit_per_min + ' запросов/мин.');
|
||
} else {
|
||
setStatus('Не удалось выпустить ключ: ' + (kd.detail || 'ошибка'));
|
||
btn.disabled = false;
|
||
}
|
||
} else if (pd.status === 'expired'){
|
||
clearInterval(pollTimer); setStatus('Сессия истекла. Попробуйте снова.'); btn.disabled=false;
|
||
}
|
||
}catch(e){}
|
||
}, 2000);
|
||
}catch(e){
|
||
setStatus('Ошибка: ' + e); btn.disabled = false;
|
||
}
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>"""
|
||
|
||
|
||
@app.get("/developers", response_class=HTMLResponse)
|
||
@app.get("/api-docs", response_class=HTMLResponse)
|
||
async def developers_docs():
|
||
return _API_DOCS_HTML
|