diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c2efb6c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+*.bak
+*.bak-*
+__pycache__/
+*.pyc
+app/temp/
diff --git a/app/main.py b/app/main.py
index 18a2bcf..6674ee3 100644
--- a/app/main.py
+++ b/app/main.py
@@ -21,6 +21,7 @@ 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
@@ -31,18 +32,27 @@ 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 = 1800 # 30 минут
+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()
@@ -79,6 +89,7 @@ def _convert_doc_to_pdf(src_path: str, dst_path: str) -> None:
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")
@@ -112,6 +123,12 @@ def _db_insert_job(
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})"
@@ -130,6 +147,20 @@ def _db_get_url_res_f(name_or_f: str) -> str | None:
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:
@@ -140,15 +171,23 @@ def _db_set_url_res_f(name_or_f: str, value: str):
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 ('', '-'))"
+ "WHERE (url_res_f IS NULL OR TRIM(url_res_f) IN ('', '-')) AND rowid <= ?",
+ (myrow,),
)
- row = cur.fetchone()
- return int(row[0]) if row else 0
+ r = cur.fetchone()
+ return int(r[0]) if r else 0
except Exception:
return 0
@@ -169,11 +208,73 @@ def _db_ensure_auth_table():
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(
@@ -224,18 +325,40 @@ def _cleanup_loop():
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:
- expired = [jid for jid, m in _meta.items() if now - m["created_at"] > RESULT_TTL]
- for job_id in expired:
- with _meta_lock:
- meta = _meta.pop(job_id, {})
- stitching = meta.get("stitching", "")
- result_path = f"{BOT_TEMP}{job_id} скан {stitching}.pdf"
- try:
- os.remove(result_path)
- except Exception:
- pass
- _db_set_url_res_f(job_id, "expired")
+ 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 ──────────────────────────────────────────────────────────────────────
@@ -281,6 +404,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
@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()
@@ -288,10 +412,199 @@ async def _startup():
app.mount("/static", StaticFiles(directory="/web_app/static"), name="static")
+# ── SEO: серверный рендер локализованных языковых страниц ─────────────────────
+# Отдельные URL на язык (/, /en/, /de/…) с локализованным
— краулеры видят
+# правильные 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' '
+ 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} \n"
+ f' \n'
+ f' \n'
+ f' \n'
+ f"{hreflangs}\n"
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f' \n'
+ f''
+ )
+
+
+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(
+ '',
+ f'',
+ )
+ # Заменяем SEO-блок между маркерами на локализованный
+ start = html.find("")
+ end = html.find("")
+ if start != -1 and end != -1:
+ head = _build_seo_head(lang)
+ html = html[:start] + "\n" + head + "\n" + html[end:]
+ return html
+
+
@app.get("/", response_class=HTMLResponse)
async def index():
- with open("/web_app/static/index.html", encoding="utf-8") as f:
- return f.read()
+ 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)
@@ -317,16 +630,38 @@ async def robots():
@app.get("/sitemap.xml")
async def sitemap():
today = datetime.date.today().isoformat()
+ # Все языковые страницы + перекрёстные hreflang-альтернативы (xhtml:link)
+ alternates = "".join(
+ f' \n'
+ for lc, p in SEO_LANG_PATH.items()
+ )
+ alternates += f' \n'
+ urls = ""
+ for lc, p in SEO_LANG_PATH.items():
+ urls += (
+ ' \n'
+ f' {SEO_BASE}{p} \n'
+ f'{alternates}'
+ f' {today} \n'
+ ' weekly \n'
+ f' {"1.0" if lc == "ru" else "0.9"} \n'
+ ' \n'
+ )
+ # Страница API-документации (для запросов «pdf scan api»)
+ urls += (
+ ' \n'
+ f' {SEO_BASE}/developers \n'
+ f' {today} \n'
+ ' monthly \n'
+ ' 0.7 \n'
+ ' \n'
+ )
return HTMLResponse(
content=(
'\n'
- '\n'
- ' \n'
- ' https://pdf2scan.online/ \n'
- f' {today} \n'
- ' monthly \n'
- ' 1.0 \n'
- ' \n'
+ '\n'
+ f'{urls}'
' \n'
),
media_type="application/xml",
@@ -355,6 +690,7 @@ async def poll_auth_token(token: str):
if uid:
with _verified_users_lock:
_verified_users[uid] = time.time()
+ _db_mark_verified(uid)
return {
"status": "verified",
"user_id": uid,
@@ -380,6 +716,7 @@ async def verify_auth(data: dict):
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")}
@@ -394,6 +731,114 @@ def _count_pdf_pages(content: bytes) -> int:
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(...),
@@ -404,6 +849,7 @@ async def submit(
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"
@@ -422,8 +868,7 @@ async def submit(
# Сохраняем оригинальный Word-документ во временный файл
src_path = f"{BOT_TEMP}{job_id}{src_ext}"
try:
- with open(src_path, "wb") as f_out:
- f_out.write(content)
+ await asyncio.to_thread(_write_bytes, src_path, content)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Не удалось сохранить файл: {exc}")
# Конвертируем в PDF через libreoffice
@@ -441,67 +886,98 @@ async def submit(
except Exception:
pass
# Считаем страницы из конвертированного PDF
- try:
- with open(file_path, "rb") as f_in:
- pages = _count_pdf_pages(f_in.read())
- except Exception:
- pages = 0
+ pages = await asyncio.to_thread(_read_and_count_pdf, file_path)
else:
- pages = _count_pdf_pages(content)
+ pages = await asyncio.to_thread(_count_pdf_pages, content)
try:
- with open(file_path, "wb") as f_out:
- f_out.write(content)
+ await asyncio.to_thread(_write_bytes, file_path, content)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Не удалось сохранить файл: {exc}")
- # Серверная проверка авторизации
- if 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:
- try:
- os.remove(file_path)
- except Exception:
- pass
- raise HTTPException(
- status_code=403,
- detail="Для файлов больше 10 страниц или 10 МБ необходима авторизация через Telegram.",
- )
+ return _finalize_submit(
+ job_id, file_path, original_name, stitching, title,
+ numeration, flip_side, color, pdfa, quality, size_mb, pages, user_id,
+ ocr=ocr,
+ )
- bot_color = _COLOR_MAP.get(color, "цветной")
+
+@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:
- _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,
- )
+ 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:
- try:
- os.remove(file_path)
- except Exception:
- pass
- raise HTTPException(status_code=500, detail=f"Ошибка записи в БД: {exc}")
+ _safe_remove(part_path)
+ _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}
+ 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}")
@@ -513,6 +989,9 @@ async def status(job_id: str):
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"):
@@ -539,17 +1018,20 @@ async def status(job_id: str):
return {"status": "done", "progress": 100, "queue_pos": 0, "error": None}
-@app.get("/api/download/{job_id}")
-async def download(job_id: str):
+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", "document.pdf")
- stitching = meta.get("stitching", "без сшивки")
+ 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"
@@ -563,3 +1045,591 @@ async def download(job_id: str):
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 ' 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 = """
+
+
+
+
+pdf2scan API — scan effect PDF API for business
+
+
+
+
+
+
+
+
pdf2scan API
+
REST · JSON · for business
+
Программно превращайте PDF и Word в «скан»: эффект сканирования, сшивка, нумерация, титульный лист, PDF/A. Идеально для юрфирм, бухгалтерий, документооборота и тендерных отделов.
+
Programmatically turn PDF/Word into scanned documents — scan effect, binding, numbering, PDF/A. Built for integrations.
+
+
+ Базовый URL / Base URL: https://pdf2scan.online/api/v1
+ Аутентификация: заголовок Authorization: Bearer <api_key> или X-API-Key: <api_key>
+ Лимит: 60 запросов/мин на ключ (пробный тариф).
+
+
+
1. Получить ключ / Get an API key
+
+
Ключи привязаны к Telegram-аккаунту. Пока сервис бесплатный (тарифы и оплату добавим позже).
+
🔑 Сгенерировать ключ через Telegram
+
+
+
Ваш ключ (показывается один раз — сохраните!):
+
+
+
Либо напишите @berkio — выдадим ключ вручную.
+
+
+
2. Отправить файл / Submit a file
+
+
POST /api/v1/scan — multipart/form-data
+
+ Поле Тип По умолчанию Описание
+ file file — PDF / DOC / DOCX
+ stitching string без сшивки нитка · ленточка · уголок · пружинка · дырокол · без сшивки
+ color string color color или bw
+ quality string high high (300 DPI) · medium (250) · low (200)
+ numeration 0/1 0 нумерация страниц
+ title 0/1 0 титульный лист
+ flip_side 0/1 0 лист «прошито-пронумеровано»
+ pdfa 0/1 0 формат PDF/A
+
+
Пример / Example
+
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"
+
Ответ / Response
+
{
+ "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"
+}
+
+
+
3. Проверить статус / Check status
+
+
GET /api/v1/scan/{job_id}
+
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" }
+
+
+
4. Скачать результат / Download result
+
+
GET /api/v1/scan/{job_id}/download — возвращает PDF (готов ~6 часов).
+
curl -L https://pdf2scan.online/api/v1/scan/JOB_ID/download \\
+ -H "Authorization: Bearer sk_your_key_here" \\
+ -o scan.pdf
+
+
+
Коды ошибок / Errors
+
+
+ Код Значение
+ 401 Нет ключа / ключ неверный или отключён
+ 409 Файл ещё не готов (проверьте статус)
+ 413 Файл слишком большой
+ 429 Превышен лимит запросов
+
+
+
+
+
+
+
+"""
+
+
+@app.get("/developers", response_class=HTMLResponse)
+@app.get("/api-docs", response_class=HTMLResponse)
+async def developers_docs():
+ return _API_DOCS_HTML
diff --git a/app/static/index.html b/app/static/index.html
index 23bc6d8..29f9648 100644
--- a/app/static/index.html
+++ b/app/static/index.html
@@ -1,2044 +1,2749 @@
-
-
-
-
-
-pdf2scan — сделать скан из PDF онлайн бесплатно
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 🧷 Выберите тип сшивки и при необходимости дополнительные настройки, затем загрузите файл — получите готовый скан.
-
-
-
-
-
Файл
-
-
-
-
-
Выберите PDF или Word
-
или перетащите файл сюда
-
—
-
-
-
-
-
-
-
-
-
-
Дополнительно
-
-
-
-
-
-
- Титульный лист
-
-
-
-
-
-
-
- Нумерация страниц
-
-
-
-
-
-
-
- Лист «прошито-пронумеровано»
-
-
-
-
-
-
-
- Формат PDF/A
-
-
-
-
-
-
-
-
-
-
🔐 Требуется авторизация
-
Для файлов больше 100 страниц или 50 МБ необходим вход через Telegram.
-
- Войти через Telegram
-
-
-
-
-
-
-
-
-
-
- Выберите файл
-
-
-
-
- Обработка...
-
-
-
-
-
-
-
-
-
-
-
Готово!
-
Ваш PDF обработан и готов к скачиванию.
-
- ⏱ Ссылка активна 30 минут — скачайте файл сейчас
-
-
⬇ Скачать результат
-
Обработать ещё один файл
-
-
-
-
-
-
-
-
🍩
-
Поддержите проект
-
Если сервис полезен — поддержите его работу донатом. Это помогает оплачивать сервер и развивать проект.
-
-
-
-
-
Сканируйте для оплаты
-
-
-
-
-
-
-
- Как работает pdf2scan
-
-
-
1
-
Загрузите файл
-
PDF или Word — перетащите или выберите с устройства
-
-
-
2
-
Настройте параметры
-
Тип сшивки, цвет, качество, нумерация и другие опции
-
-
-
3
-
Скачайте результат
-
Готовый PDF со сканом доступен для скачивания 30 минут
-
-
- pdf2scan — бесплатный онлайн-инструмент для создания растрового PDF с эффектом сканирования. Поддерживает сшивку нитками, ленточкой, уголком, пружинкой и дыроколом. Идеально для подготовки документов к сдаче в архив, нотариусу или государственные органы. Без регистрации, без установки программ.
-
-
-
-
-
-
-
+
+
+
+
+
+
+pdf2scan — сделать скан из PDF онлайн бесплатно
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 🧷 Выберите тип сшивки и при необходимости дополнительные настройки, затем загрузите файл — получите готовый скан.
+
+
+
+
+
Файл
+
+
+
+
+
+
Выберите PDF или Word
+
или перетащите файлы сюда (до 20)
+
—
+
+
+ 📁 Папкой
+
+
+
+
+
+
+
Файлы
+
+
+ ⬇ Скачать всё архивом
+ Обработать ещё файлы
+
+
+
+
+
+
+
+
+
Дополнительно
+
+
+
+
+
+
+ Титульный лист
+
+
+
+
+
+
+
+ Нумерация страниц
+
+
+
+
+
+
+
+ Лист «прошито-пронумеровано»
+
+
+
+
+
+
+
+ Формат PDF/A
+
+
+
+
+
+
+
+
+ Распознать текст (OCR)
+ Скан станет искомым: текст можно копировать и находить поиском
+
+
+
+
+
+
+
+
+
+
+
🔐 Требуется авторизация
+
Для файлов больше 100 страниц или 50 МБ необходим вход через Telegram.
+
+ Войти через Telegram
+
+
+
+
+
+
+
+
+
+
+ Выберите файл
+
+
+
+
+ Обработка...
+
+
+
+
+
+
+
+
+
+
+
Готово!
+
Ваш PDF обработан и готов к скачиванию.
+
+ ⏱ Ссылка активна 30 минут — скачайте файл сейчас
+
+
⬇ Скачать результат
+
Обработать ещё один файл
+
+
+
+
+
+
+
+
🍩
+
Поддержите проект
+
Если сервис полезен — поддержите его работу донатом. Это помогает оплачивать сервер и развивать проект.
+
+
+
+
+
Сканируйте для оплаты
+
+
+
+
+
+
+
+
+
+
+ Как работает pdf2scan
+
+
+
1
+
Загрузите файл
+
PDF или Word — перетащите или выберите с устройства
+
+
+
2
+
Настройте параметры
+
Тип сшивки, цвет, качество, нумерация и другие опции
+
+
+
3
+
Скачайте результат
+
Готовый PDF со сканом доступен для скачивания 30 минут
+
+
+ pdf2scan — бесплатный онлайн-инструмент для создания растрового PDF с эффектом сканирования. Поддерживает сшивку нитками, ленточкой, уголком, пружинкой и дыроколом. Идеально для подготовки документов к сдаче в архив, нотариусу или государственные органы. Без регистрации, без установки программ.
+
+
+
+
+
+
+
diff --git a/app/static/og.png b/app/static/og.png
new file mode 100644
index 0000000..cd461ed
Binary files /dev/null and b/app/static/og.png differ