#!/usr/bin/env python3 """ catalog_app.py — каталог книг и статистика чтения. ЧТО ДЕЛАЕТ: * хранит каталог читателей (книги, серии, статусы); * показывает прогресс по сериям, что прочитано, что искать; * считает статистику; * по каждой «следующей» книге даёт ссылки поиска. Работает на стандартной библиотеке Python — ничего лишнего ставить не надо. Доступ закрыт единым входом (заголовок X-Auth-Request-Email от oauth2-proxy). """ import json import os import re import sqlite3 import urllib.parse from datetime import datetime from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer BASE = "/app" DB = os.path.join(BASE, "catalog.db") SEED = os.environ.get("SEED_FILE", os.path.join(BASE, "data", "polina-library.json")) CSS = """ :root{--bg:#0f1220;--card:#171b2e;--fg:#e8eaf6;--muted:#9aa0bf;--acc:#7c9cff;--ok:#4caf7d;--warn:#e0a83c;--bad:#e06c6c} *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,Segoe UI,Roboto,sans-serif} a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline} .wrap{max-width:1100px;margin:0 auto;padding:24px} h1{font-size:24px;margin:0 0 4px}h2{font-size:18px;margin:28px 0 10px} .sub{color:var(--muted);margin-bottom:20px} .cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px} .card{background:var(--card);border-radius:12px;padding:14px} .card .n{font-size:26px;font-weight:600}.card .l{color:var(--muted);font-size:13px} table{width:100%;border-collapse:collapse;background:var(--card);border-radius:12px;overflow:hidden} th,td{padding:9px 12px;text-align:left;border-bottom:1px solid #232840;font-size:14px} th{color:var(--muted);font-weight:500;font-size:13px} tr:last-child td{border-bottom:0} .b{display:inline-block;padding:2px 8px;border-radius:8px;font-size:12px} .b-ok{background:#1e3a2c;color:#8ee0b0}.b-warn{background:#3a3320;color:#e8c777}.b-bad{background:#3a2020;color:#e8a0a0} .bar{height:8px;background:#232840;border-radius:6px;overflow:hidden;min-width:80px} .bar i{display:block;height:100%;background:var(--acc)} .links a{margin-right:10px;font-size:13px} .nav{margin-bottom:18px;font-size:14px} .nav a{margin-right:16px} .foot{color:var(--muted);font-size:12px;margin-top:28px} """ STATUS_LABEL = { "completed_read": ("прочитано", "ok"), "available_unread": ("следующая доступна", "warn"), "caught_up_waiting": ("ждём продолжения", "warn"), "waiting_release": ("ждём выхода", "warn"), "waiting_ru": ("ждём перевод", "warn"), "waiting_ru_or_copy": ("нужна копия", "warn"), "other_line_available": ("другая линия есть", "warn"), "waiting_release_other_line": ("другая линия в работе", "warn"), "main_line_completed": ("основная линия закрыта", "ok"), "selected_lines_completed": ("выбранные линии закрыты", "ok"), "not_interested": ("не интересно", "bad"), } def db(): con = sqlite3.connect(DB) con.row_factory = sqlite3.Row return con def init_db(): con = db() con.executescript( """ create table if not exists readers(id integer primary key, name text unique, slug text unique); create table if not exists books( id text primary key, reader_id integer, author text, title text, reading_status text, read_year integer, series text, series_relation text, ru_status text, needs_verification integer ); create table if not exists series( id text primary key, reader_id integer, name text, authors text, read_count integer, read_titles text, publication_status text, personal_status text, relation text, next_title text, next_availability text, next_ru_status text, next_note text ); create index if not exists idx_books_reader on books(reader_id); create index if not exists idx_series_reader on series(reader_id); """ ) con.commit() con.close() def import_catalog(path, reader_name="Полина", reader_slug="polina"): con = db() cur = con.execute("select id from readers where slug=?", (reader_slug,)) row = cur.fetchone() if row: rid = row["id"] else: con.execute("insert into readers(name,slug) values(?,?)", (reader_name, reader_slug)) rid = con.execute("select last_insert_rowid() as i").fetchone()["i"] with open(path, encoding="utf-8") as f: cat = json.load(f) con.execute("delete from books where reader_id=?", (rid,)) con.execute("delete from series where reader_id=?", (rid,)) for b in cat.get("books") or []: con.execute( "insert or replace into books values(?,?,?,?,?,?,?,?,?,?)", ( f"{reader_slug}:{b.get('id')}", rid, b.get("author"), b.get("title"), b.get("reading_status"), b.get("read_year"), b.get("series"), b.get("series_relation"), b.get("ru_status"), 1 if b.get("needs_manual_verification") else 0, ), ) for s in cat.get("series") or []: nxt = s.get("next") or {} con.execute( "insert or replace into series values(?,?,?,?,?,?,?,?,?,?,?,?,?)", ( f"{reader_slug}:{s.get('id')}", rid, s.get("name"), ", ".join(s.get("authors") or []), s.get("read_count"), json.dumps(s.get("read_titles") or [], ensure_ascii=False), s.get("publication_status"), s.get("personal_status"), s.get("relation"), nxt.get("title"), nxt.get("availability"), nxt.get("ru_status"), nxt.get("note"), ), ) con.commit() con.close() return rid def search_links(title, author): q = urllib.parse.quote(f"{author} {title}" if author else title) return [ ("ЛитРес", f"https://www.litres.ru/search/?q={q}"), ("Bookmate", f"https://bookmate.com/search?q={q}"), ("ФантЛаб", f"https://fantlab.ru/searchmain?searchstr={q}"), ("Open Library", f"https://openlibrary.org/search?q={q}"), ("Архив", f"https://archive.org/search?query={q}"), ("Гутенберг", f"https://www.gutenberg.org/ebooks/search/?query={urllib.parse.quote(title)}"), ("Либген", f"https://libgen.is/search.php?req={q}"), ("Флибуста", f"https://flibusta.is/booksearch?ask={q}"), ("Анна", f"https://annas-archive.org/search?q={q}"), ("Z-Library", f"https://z-lib.gs/s/{q}"), ("КулЛиб", f"https://coollib.net/search?ask={q}"), ("ЛитМир", f"https://www.litmir.me/search/?q={q}"), ] def esc(s): return ( str(s or "").replace("&", "&").replace("<", "<").replace(">", ">") .replace('"', """) ) def page(title, body, nav=True): n = '' if nav else "" return f""" {esc(title)}
{n}

{esc(title)}

{body}
Обновлено {datetime.now():%d.%m.%Y %H:%M} · Buryans Hub
""" class Handler(BaseHTTPRequestHandler): server_version = "CatalogApp/1.0" def log_message(self, fmt, *args): try: with open(os.path.join(BASE, "catalog.log"), "a", encoding="utf-8") as f: f.write("%s %s\n" % (datetime.now().isoformat(), fmt % args)) except OSError: pass def user(self): return self.headers.get("X-Auth-Request-Email") or self.headers.get("X-Forwarded-User") or "гость" def send_html(self, html, code=200): data = html.encode("utf-8") self.send_response(code) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def send_json(self, obj, code=200): data = json.dumps(obj, ensure_ascii=False, indent=2).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): path = urllib.parse.urlparse(self.path).path prefix = os.environ.get("PREFIX", "").rstrip("/") if prefix and path.startswith(prefix): path = path[len(prefix):] or "/" try: if path == "/": return self.page_home() if path == "/series": return self.page_series() if path == "/books": return self.page_books() if path == "/wanted": return self.page_wanted() if path == "/api/summary": return self.api_summary() if path == "/health": return self.send_json({"status": "ok"}) return self.send_html(page("Не найдено", "

Страница не найдена.

"), 404) except Exception as e: return self.send_html(page("Ошибка", f"

{esc(e)}

"), 500) def readers(self): con = db() rows = con.execute("select * from readers order by id").fetchall() con.close() return rows def page_home(self): rid = self.reader_id() con = db() total = con.execute("select count(*) c from books where reader_id=?", (rid,)).fetchone()["c"] ser = con.execute("select count(*) c from series where reader_id=?", (rid,)).fetchone()["c"] read = con.execute("select count(*) c from books where reader_id=? and reading_status='read'", (rid,)).fetchone()["c"] want = con.execute( "select count(*) c from series where reader_id=? and next_title is not null " "and coalesce(next_availability,'') not in ('scheduled','announced_no_date')", (rid,), ).fetchone()["c"] statuses = con.execute( "select personal_status s, count(*) c from series where reader_id=? group by 1 order by 2 desc", (rid,), ).fetchall() con.close() body = f"""
Читатель: {esc(self.reader_name(rid))} · вы вошли как {esc(self.user())}
{total}
книг в каталоге
{read}
прочитано
{ser}
серий
{want}
книг к поиску

Состояние серий

""" for s in statuses: label, kind = STATUS_LABEL.get(s["s"], (s["s"] or "—", "warn")) body += f'' body += "
СтатусСерий
{esc(label)}{s["c"]}
" if len(self.readers()) > 1: body += "

Читатели

" con = db() for r in self.readers(): c = con.execute("select count(*) c from books where reader_id=?", (r["id"],)).fetchone()["c"] body += f'' con.close() body += "
ИмяКниг
{esc(r["name"])}{c}
" return self.send_html(page("Каталог книг", body)) def reader_id(self): qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) slug = (qs.get("reader") or [None])[0] con = db() if slug: row = con.execute("select id from readers where slug=?", (slug,)).fetchone() else: row = con.execute("select id from readers order by id limit 1").fetchone() con.close() return row["id"] if row else 1 def reader_name(self, rid): con = db() row = con.execute("select name from readers where id=?", (rid,)).fetchone() con.close() return row["name"] if row else "—" def page_series(self): rid = self.reader_id() con = db() rows = con.execute( "select * from series where reader_id=? order by name collate nocase", (rid,) ).fetchall() con.close() body = '' for r in rows: label, kind = STATUS_LABEL.get(r["personal_status"], (r["personal_status"] or "—", "warn")) nxt = r["next_title"] or "—" body += ( f'' f'' f'' f'' ) body += "
СерияАвторПрочитаноСтатусСледующая
{esc(r["name"])}{esc(r["authors"])}{r["read_count"] or 0}{esc(label)}{esc(nxt)}
" return self.send_html(page("Серии", body)) def page_books(self): rid = self.reader_id() con = db() rows = con.execute( "select * from books where reader_id=? order by author collate nocase, title collate nocase", (rid,), ).fetchall() con.close() body = '' for r in rows: body += ( f'' f'' ) body += "
АвторНазваниеСерия
{esc(r["author"])}{esc(r["title"])}{esc(r["series"] or "—")}
" return self.send_html(page(f"Книги ({len(rows)})", body)) def page_wanted(self): rid = self.reader_id() con = db() rows = con.execute( "select * from series where reader_id=? and next_title is not null " "and coalesce(next_availability,'') not in ('scheduled','announced_no_date') " "order by name collate nocase", (rid,), ).fetchall() con.close() body = f'
Книг к поиску: {len(rows)}. Ссылки открывают поиск в каждом источнике.
' for r in rows: author = r["authors"] links = search_links(r["next_title"], author) body += ( f'

{esc(r["next_title"])}

' f'
серия «{esc(r["name"])}» · {esc(author)} · ' f'прочитано {r["read_count"] or 0} · {esc(r["next_availability"] or "")}
' '" ) return self.send_html(page("Что искать", body)) def api_summary(self): rid = self.reader_id() con = db() out = { "reader": self.reader_name(rid), "books": con.execute("select count(*) c from books where reader_id=?", (rid,)).fetchone()["c"], "series": con.execute("select count(*) c from series where reader_id=?", (rid,)).fetchone()["c"], "read": con.execute( "select count(*) c from books where reader_id=? and reading_status='read'", (rid,) ).fetchone()["c"], "wanted": con.execute( "select count(*) c from series where reader_id=? and next_title is not null " "and coalesce(next_availability,'') not in ('scheduled','announced_no_date')", (rid,), ).fetchone()["c"], "updated": datetime.now().isoformat(timespec="seconds"), } con.close() return self.send_json(out) def main(): init_db() if os.path.exists(SEED): try: import_catalog(SEED) print("каталог импортирован из", SEED, flush=True) except Exception as e: print("импорт не удался:", e, flush=True) port = int(os.environ.get("PORT", "9200")) srv = ThreadingHTTPServer(("0.0.0.0", port), Handler) print(f"каталог слушает на {port}", flush=True) srv.serve_forever() if __name__ == "__main__": main()