refactor(media): แยกรูปออกจาก code — รูปทั้งหมดอยู่บน object storage

code อยู่ใน git · รูปอยู่บน SeaweedFS (https://storage.hobbypj.com/hobbypj/alterflixhub/)

- อัปโหลด images/ (21 ไฟล์) + og/ (1 ไฟล์) ขึ้น storage แล้วตรวจ sha256 ตรงทุกไฟล์
- แทนที่อ้างอิง 894 จุด ใน 37 ไฟล์: /images/… → <storage>/images/…, /og/… → <storage>/og/…
  (absolute URL ทุกที่ รวม JSON-LD/og:image/twitter:image และ placeholder ในหลังบ้าน)
- ลบ images/ + og/ ออกจาก repo · สำเนาในเครื่องย้ายไป media/ (gitignored)
- scripts/media-to-storage.py: สคริปต์ที่ใช้ย้าย (บันทึกวิธี + ใช้ซ้ำได้เมื่อเปลี่ยน base)
- scripts/media-sync.py: --check / --upload รูปขึ้น storage (basic auth หรือ SSH tunnel ไป filer)
- sw.js: bump v2.1.6 + แคชรูปจาก storage แบบ cache-first (isMedia/mediaCacheFirst) กันออฟไลน์แล้วรูปหาย
- docker/traefik-storage-alterflixhub.yml: router เปิดอ่านสาธารณะเฉพาะ /hobbypj/alterflixhub/
  (host storage บังคับ Basic auth ทั้ง host — ต้องมี router priority 300 + CORS ก่อน)
- docs/media-storage.md: วิธีอัปโหลด/เพิ่มรูป + ข้อกำหนดฝั่ง Traefik
- .gitignore/.dockerignore: กัน media/, images/, og/ กลับเข้า repo/image

ไอคอน PWA (icon-*.png, favicon.svg) ยังอยู่ใน repo — ต้อง same-origin ให้ติดตั้ง PWA ได้
This commit is contained in:
Bkk1234 committed 2026-11-27 02:08:19 +07:00
1 parent bc0e7a963e
commit ddfb0a5053
67 files changed
+442 -104

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
#!/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 <user>@<server>
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())
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""ย้ายรูปออกจาก repo → ชี้ไป object storage (SeaweedFS)
ใช้ครั้งเดียว (2026-11-27) แล้วเก็บไว้เป็นบันทึก:
python scripts/media-to-storage.py --dry-run
python scripts/media-to-storage.py
แทนที่
/images/... → https://storage.hobbypj.com/hobbypj/alterflixhub/images/...
/og/... → https://storage.hobbypj.com/hobbypj/alterflixhub/og/...
https://alterflixhub.hobbypj.com/og/ → https://storage.hobbypj.com/hobbypj/alterflixhub/og/
ไม่แตะ docs/ (เป็นเอกสาร ไม่ใช่หน้าจริง) และไม่แตะ URL ที่ชี้ storage อยู่แล้ว
"""
from __future__ import annotations
import argparse
import re
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
STORAGE = "https://storage.hobbypj.com/hobbypj/alterflixhub"
SUFFIXES = {".html", ".js", ".json", ".webmanifest", ".xml", ".txt"}
SKIP_DIRS = {".git", "docs", "scripts", "node_modules", "_backup"}
RULES = [
(re.compile(r"https://alterflixhub\.hobbypj\.com/og/"), STORAGE + "/og/"),
(re.compile(r"(?<![\w./-])/og/"), STORAGE + "/og/"),
(re.compile(r"(?<![\w./-])/images/"), STORAGE + "/images/"),
]
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--base", default=STORAGE, help="เปลี่ยน base ได้ (default = production)")
args = ap.parse_args()
storage = args.base.rstrip("/")
total_files = 0
total_hits = 0
per_file = []
for path in sorted(REPO.rglob("*")):
if not path.is_file() or path.suffix.lower() not in SUFFIXES:
continue
rel = path.relative_to(REPO)
if any(part in SKIP_DIRS for part in rel.parts):
continue
with path.open(encoding="utf-8", newline="") as fh:
text = fh.read()
hits = 0
new = text
for pattern, repl in RULES:
target = repl if repl.startswith("http") else repl
if repl == STORAGE + "/og/" or repl == STORAGE + "/images/":
# เคารพ --base
tail = "/og/" if repl.endswith("/og/") else "/images/"
target = storage + tail
new, n = pattern.subn(lambda _m, t=target: t, new)
hits += n
if new != text:
total_files += 1
total_hits += hits
per_file.append((str(rel), hits))
if not args.dry_run:
path.write_text(new, encoding="utf-8", newline="")
mode = "[dry-run] " if args.dry_run else ""
print(f"{mode}แก้ {total_files} ไฟล์ · {total_hits} จุด → {storage}")
for rel, hits in per_file[:20]:
print(f" • {rel} ({hits})")
if len(per_file) > 20:
print(f" … อีก {len(per_file) - 20} ไฟล์")
return 0
if __name__ == "__main__":
raise SystemExit(main())