#!/usr/bin/env python3 """media-sync — อัปโหลดรูปจาก media/ ขึ้น object storage (SeaweedFS) หลักคิด: code อยู่ใน git · รูปอยู่บน storage local : media/images/cinemas/lido-connect.jpg remote: https://storage.hobbypj.com/hobbypj/alterflixhub/images/cinemas/lido-connect.jpg โหมด (ค่าเริ่มต้น = --check คือไม่เขียนอะไร): python scripts/media-sync.py --check # เทียบ local กับ storage (HEAD) python scripts/media-sync.py --upload # อัปโหลดไฟล์ที่ยังไม่มี/ขนาดไม่ตรง python scripts/media-sync.py --upload --only images og การยืนยันตัวตน — เลือกทางใดทางหนึ่ง 1) Basic auth ของ host storage (ค่าเดียวกับ Traefik middleware filer-auth) ALTERFLIX_STORAGE_USER=... ALTERFLIX_STORAGE_PASS=... python scripts/media-sync.py --upload 2) ทะลุผ่าน SSH ไปที่ SeaweedFS filer ตรง ๆ (ไม่ต้องมีรหัส; host storage บังคับ auth) ssh -N -L 13103:127.0.0.1:3103 @ python scripts/media-sync.py --upload --base http://127.0.0.1:13103/hobbypj/alterflixhub หมายเหตุ: path บน storage ต้องตรงกับ URL ที่หน้าเว็บอ้าง (ดู docs/media-storage.md) """ from __future__ import annotations import argparse import base64 import mimetypes import os import sys import urllib.error import urllib.request from pathlib import Path REPO = Path(__file__).resolve().parents[1] LOCAL_ROOT = REPO / "media" DEFAULT_BASE = "https://storage.hobbypj.com/hobbypj/alterflixhub" EXTS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".svg", ".gif"} def walk(root: Path): for p in sorted(root.rglob("*")): if p.is_file() and p.suffix.lower() in EXTS: yield p.relative_to(root).as_posix(), p def auth_header(user: str, password: str) -> dict: if not user: return {} token = base64.b64encode(f"{user}:{password}".encode()).decode() return {"Authorization": "Basic " + token} def request(url: str, headers: dict, method: str = "GET", body: bytes | None = None) -> tuple[int, bytes]: data = body if method in {"PUT", "POST"} else None req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=60) as r: return r.status, r.read() if method == "GET" else b"" except urllib.error.HTTPError as e: return e.code, b"" except urllib.error.URLError as e: print(f" (network) {e}", file=sys.stderr) return 0, b"" def main() -> int: ap = argparse.ArgumentParser(description="sync media/ → object storage") ap.add_argument("--base", default=os.environ.get("ALTERFLIX_STORAGE_BASE", DEFAULT_BASE)) ap.add_argument("--user", default=os.environ.get("ALTERFLIX_STORAGE_USER", "")) ap.add_argument("--pass", dest="password", default=os.environ.get("ALTERFLIX_STORAGE_PASS", "")) ap.add_argument("--check", action="store_true", help="เทียบ local กับ storage (ค่าเริ่มต้น)") ap.add_argument("--upload", action="store_true", help="อัปโหลดไฟล์ที่ขาด/ขนาดไม่ตรง") ap.add_argument("--dry-run", action="store_true") ap.add_argument("--only", nargs="*", default=None, help="จำกัดเฉพาะโฟลเดอร์ เช่น images og") args = ap.parse_args() if not LOCAL_ROOT.exists(): sys.exit(f"ไม่พบโฟลเดอร์รูป: {LOCAL_ROOT}") base = args.base.rstrip("/") headers = auth_header(args.user, args.password) local: dict[str, Path] = {} for rel, path in walk(LOCAL_ROOT): area = rel.split("/", 1)[0] if args.only and area not in args.only: continue local[rel] = path if not local: sys.exit("ไม่พบไฟล์ให้ทำ (ตรวจ media/ หรือ --only)") missing: list[tuple[str, Path]] = [] for rel, path in local.items(): code, _ = request(f"{base}/{rel}", {**headers, "Range": "bytes=0-0"}, method="GET") if code not in (200, 206): missing.append((rel, path)) if not args.upload: total = sum(p.stat().st_size for p in local.values()) print(f"local {len(local)} ไฟล์ · {total / 1048576:.1f} MB → {base}") print(f"ขาด/อ่านไม่ได้บน storage {len(missing)} ไฟล์") for rel, _ in missing[:10]: print(" •", rel) return 0 print(f"จะอัปโหลด {len(missing)}/{len(local)} ไฟล์ → {base}") if args.dry_run: for rel, _ in missing[:10]: print(" ↑", rel) return 0 ok = 0 for rel, path in missing: ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream" code, _ = request(f"{base}/{rel}", {**headers, "Content-Type": ctype}, method="PUT", body=path.read_bytes()) print(f" {'✓' if 200 <= code < 300 else '✗'} {code} {rel}") ok += 1 if 200 <= code < 300 else 0 print(f"อัปโหลดสำเร็จ {ok}/{len(missing)}") return 0 if ok == len(missing) else 1 if __name__ == "__main__": raise SystemExit(main())