diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 40f60e1de89e0f904c11d302058de8c039f587a9..0000000000000000000000000000000000000000 --- a/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -__pycache__/ -*.pyc -data/ -.data -.huggingface/ -.restart_trigger diff --git a/.huggingface/rebuild b/.huggingface/rebuild new file mode 100644 index 0000000000000000000000000000000000000000..f21d842ee947ba47cf302f26bde1d185298eb2f8 --- /dev/null +++ b/.huggingface/rebuild @@ -0,0 +1 @@ +trigger rebuild \ No newline at end of file diff --git a/.rebuild b/.rebuild new file mode 100644 index 0000000000000000000000000000000000000000..d1e9c67432345af8a80936be5174cc9f93ad27b2 --- /dev/null +++ b/.rebuild @@ -0,0 +1 @@ +1782552642 \ No newline at end of file diff --git a/.restart_trigger b/.restart_trigger new file mode 100644 index 0000000000000000000000000000000000000000..e580802946b9a7220d15085342b4e831279626c7 --- /dev/null +++ b/.restart_trigger @@ -0,0 +1 @@ +# restart trigger - v5.1 rewrite fix 2026-06-27 diff --git a/CHANGELOG.md b/CHANGELOG.md index bed2a391f57aae4c106228b98824a5a07c71913b..30dbc8acd7e303933080c6d983cfbafb2890b0e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,27 @@ -# FPT Play Stream Selector Update +# VNEWS v5.1 - Rewrite Fix -Added FPT Play channel with stream selector UI similar to VTV6: +## Changes -- New tab "FPT" (orange themed) in the channel tabs -- Stream selector with 4 sources: - 1. 🌐 Web FPT Play (iframe) - 2. 📡 HLS Proxy (via /api/proxy/m3u8) - 3. 🔗 HLS Direct - 4. 📺 HD1.xemtv.net (iframe from LINK 1) -- Backend vtv_api.py now returns stream_selectors for fpt-the-thao channel -- Frontend handles stream switching automatically when FPT tab is active +### Critical Fix: Rewrite button not creating posts on Tường AI +**Root cause**: `_run.py` imports from `app_v2_entry.py`, but the `/api/rewrite_share` endpoint was only defined in `ai_runtime_patch_fast.py` (loaded through `app_entry.py` which is NOT used). The frontend called a non-existent endpoint → 404 → silent failure. -## Changes -- `static/vtv_init.js`: Added FPT tab + stream selector UI logic -- `vtv_api.py`: Added FPT Play endpoint responses with stream_selectors data +**Fix applied**: +1. **app_v2_entry.py** — Added 3 new endpoints: + - `POST /api/rewrite_slide` — Fast extractive summary (no AI needed), creates slides from article key points + images, saves to wall + - `POST /api/rewrite_share` — AI-powered rewrite with extractive fallback, saves to wall + - `POST /api/url_wall` — URL submission endpoint (alias for rewrite_share) + - All endpoints use the same `_load_wall_posts()` / `_save_wall_posts()` and `WALL_FILE` path as the existing `/api/wall` endpoint + +2. **static/index_v2.html** — Added `` to load the rewrite fix + +3. **static/rewrite_fix_v2.js** — New file that overrides `rewriteArticle()` to: + - Call `/api/rewrite_slide` first (fast, no AI needed) + - Fallback to `/api/rewrite_share` if slide fails + - Show slide preview overlay after successful post + - Use `prependWallPost()` to add the new post to Tường AI + +### Previous changes (v5) +- Rewrote match_detail_v2.py with correct event parsing +- 2-tab layout for match detail (stats + timeline) +- Fixed _run.py import +- Dockerfile cache busting diff --git a/Dockerfile b/Dockerfile index 5e4cdaa1a67afb1e0ab5faa307e619fbb285f0c2..1ba3320590f4c27d463fa54b0d2e19320add3655 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,48 +2,14 @@ FROM python:3.12-slim WORKDIR /app -RUN echo "[BUILD] step1: apt-get update+install ffmpeg + Vietnamese fonts" && \ - apt-get update && apt-get install -y --no-install-recommends \ - ffmpeg \ - fonts-dejavu-core \ - fonts-noto \ - fonts-noto-cjk \ - fonts-noto-color-emoji \ - fonts-liberation \ - fonts-freefont-ttf \ - libfreetype6 \ - && rm -rf /var/lib/apt/lists/* && \ - echo "[BUILD] step1 done" - -RUN echo "[BUILD] step2: pip base pkgs (bs4/lxml)" && \ - pip install --no-cache-dir "beautifulsoup4>=4.12" lxml && \ - echo "[BUILD] step2 done" - -RUN echo "[BUILD] step3: pip main pkgs" && \ - pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx pycryptodome && \ - echo "[BUILD] step3 done" +RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-dejavu-core && rm -rf /var/lib/apt/lists/* +RUN pip install --no-cache-dir "beautifulsoup4>=4.12" lxml +RUN pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx COPY requirements.txt . -RUN echo "[BUILD] step4: pip requirements.txt" && \ - pip install --no-cache-dir -r requirements.txt || true && \ - echo "[BUILD] step4 done" +RUN pip install --no-cache-dir -r requirements.txt || true COPY . . EXPOSE 7860 -RUN echo "[BUILD] step5: setup Vietnamese font symlink" && \ - mkdir -p /usr/share/fonts/truetype/vn && \ - # Prefer Noto Sans for Vietnamese - it has full diacritic support - if [ -f /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf ]; then \ - ln -sf /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \ - elif [ -f /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf ]; then \ - ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \ - ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf /usr/share/fonts/truetype/vn/VNFont-Bold.ttf; \ - fi; \ - fc-cache -f -v || true; \ - date > /app/.build_done && \ - echo "[BUILD] step5 done" - -CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860"] -# v3.0-vn-font-fix-short-video-2026-07-19 -# rebuild-trigger: m3u-perf-fix-20260829 +CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860", "--reload"] \ No newline at end of file diff --git a/README.md b/README.md index f65ec063b0184f66ec5c41d94307c4f38f4c0a38..dc357a7ef1b414efed6580b6ca6d3ed5e257e4fe 100644 --- a/README.md +++ b/README.md @@ -9,50 +9,17 @@ tags: - ml-intern --- -# VNEWS - Tin Tức Việt Nam - -**v18 - FIXED VTV2/VTV3/VTV6/VTV9 stream hanging** - -## 🔧 Changes in v18 (2026-07-06) -- **VTV2, VTV3, VTV6, VTV9**: Skip expired ssaimh CDN token → immediately fall through to sv2.xemtivitop.com -- **15+ extraction patterns** for m3u8 URL (up from 5), including: file:, src=, source:, player.src(), hls.loadSource(), href=, ``, url:, window.location, iframe follow (3 levels deep), base64 decode -- **Backup CDN** `tv.mediacdn.vn` for VTV2/VTV3/VTV6/VTV9 -- **Fast timeout** 5s for CDN, 12s for PHP endpoints (was 15s each = 60s+ total) -- **sv2.xemtivitop.com** re-prioritized to check BEFORE xemtv.us -- **Iframe chain following**: if a PHP page returns an iframe → follow it up to 3 levels to find the m3u8 - -## Features: -- 📰 News from VnExpress (10 categories) + GenK AI -- ⚽ Livescore from bongda.com.vn (live, today, upcoming, results, standings) -- 🎬 Football highlights from xemlaibongda.top (8 leagues) -- 📺 VTV live channels (VTV1→VTV10, VTV Prime) - - Priority: ssaimh CDN → sv2.xemtivitop.com → xemtv.us → xemtivitop blogspot → FPTPlay → VTVGo → mediacdn → xemtv.net -- 🏆 World Cup 2026 (news, fixtures, standings, stats, highlights) -- 🤖 AI article writing + TTS (multilingual, emotion-aware) -- 🔍 Topic search (8 news sources) -- 🎤 TTS: voice selector + emotion selector + speed control - -## 🎬 Short AI — Video từ link (scrap YouTube / TikTok / tin tức) - -Short creator có chế độ **"🔗 Video từ link"**: dán link video YouTube / TikTok / -VnExpress / Dân trí / Znews / 24h... → bấm "Lấy video" để xem trước → tạo short -chạy video + ảnh đã chọn bù phần còn thiếu nếu video ngắn hơn giọng đọc. - -### 🔑 Cài cookies cho YouTube (bỏ chặn "Sign in to confirm you're not a bot") -YouTube đôi khi chặn IP datacenter. Cách khắc phục bằng cookies: - -1. Cài extension trình duyệt **"Get cookies.txt LOCALLY"** (Chrome/Edge) hoặc - **"cookies.txt"** (Firefox). -2. Mở `https://www.youtube.com` (đã đăng nhập) → bấm extension → **Export** → ra file `cookies.txt` (định dạng Netscape). -3. Đưa cookies vào Space bằng **một trong hai cách**: - - **Cách A (khuyến nghị):** Vào Settings của Space - `huggingface.co/spaces/bep40/VNEWS/settings` → **Variables and secrets** → - tạo secret tên **`YT_COOKIES`**, giá trị = toàn bộ nội dung file `cookies.txt`. - - **Cách B:** đặt file `cookies.txt` vào thư mục gốc repo `VNEWS/` và commit - (chú ý: cookies sẽ công khai nếu repo public — ưu tiên Cách A). -4. Rebuild Space (mỗi lần đổi secret phải **Restart** Space). - -Backend tự đọc `YT_COOKIES` (secret) hoặc `/app/cookies.txt`, ghi thành file tạm -và truyền cho yt-dlp qua `cookiefile`. Không cần sửa code. - -> Lưu ý: cookies có hạn (thường vài tuần). Khi hết hạn, export lại và cập nhật secret. \ No newline at end of file +# bep40/vnews + + + + + + + + + + + + + diff --git a/RESTART_TRIGGER.md b/RESTART_TRIGGER.md deleted file mode 100644 index 4f06e808a6b0999217d1d33deb76e800158a5db7..0000000000000000000000000000000000000000 --- a/RESTART_TRIGGER.md +++ /dev/null @@ -1,10 +0,0 @@ -# VNEWS Space Restart Trigger - -trigger rebuild v20260829m3ufix - -## Fixes applied this build: -1. **M3U channel logo fix**: `.m3u-channel-thumb` changed from `height:60px; object-fit-cover` (rectangular crop with syntax error — missing colon) to `aspect-ratio:1/1; max-width:80px; height:auto; object-fit:contain` (square thumbnails showing full logos without cropping) -2. **Black screen on live channels fix**: HLS manifest in `proxy_m3u_hls` changed from `#EXTINF:6.0` with `MEDIA-SEQUENCE:0` and no `ENDLIST` (causing Hls.js to not re-request segments after 6s) to `#EXTINF:3600` with `#EXT-X-ENDLIST` (single continuous segment that Hls.js plays indefinitely) -3. **proxy_segment timeout fix**: Changed `timeout=15` to `timeout=(10, 60)` for live TS streams that may not send data for several seconds, and `max_sec` default from 60 to 0 (open-ended streaming) - -FORCE REBUILD: this commit retriggers the Space container with the latest fixes \ No newline at end of file diff --git a/_run.py b/_run.py index de72380c3006dba490ec49c1fe421c87723a0490..4a7a26bd2553b700d918ace5f77e2a3e369e0be2 100644 --- a/_run.py +++ b/_run.py @@ -1 +1 @@ -from app_v2_entry import app # v5-stable inline bongda proxy \ No newline at end of file +from app_v2_entry import app # v5-stable inline bongda proxy diff --git a/ai_ext.py b/ai_ext.py index ab7540db0765711cf34947d481888084e0f87c65..688ba54317c3df69d702269d4cee2edf60e7d621 100644 --- a/ai_ext.py +++ b/ai_ext.py @@ -13,16 +13,7 @@ from bs4 import BeautifulSoup from fastapi import Request, Query from fastapi.responses import HTMLResponse, JSONResponse, FileResponse -# Try to import main app, but don't fail if it doesn't exist -try: - from main import app -except ImportError: - # Create a minimal FastAPI app for standalone testing - try: - from fastapi import FastAPI - app = FastAPI() - except Exception: - app = None +from main import app # Import wall store from main.py so we read/write the SAME file try: @@ -50,10 +41,6 @@ except ImportError: def _web_context(topic): return "" -# ai_ext alias for backward compatibility -_load_ai_wall = _load_wall -_save_ai_wall = _save_wall - try: from huggingface_hub import AsyncInferenceClient except Exception: @@ -79,254 +66,77 @@ def _hf_token(): return v return "" - -def _clean_text(s: str) -> str: - """Clean text for processing.""" - s = html_lib.unescape(s or "") - s = re.sub(r"\s+", " ", s) - return s.strip() - - -def _domain(url: str) -> str: - """Extract domain from URL.""" - try: - return urlparse(url or "").netloc.replace("www.", "") - except Exception: - return "" - - -async def qwen_generate(prompt: str, image_url: str = None, max_tokens: int = 1200) -> str: - """Generate text using Llama/Qwen models via Hugging Face Inference API. +HF_TOKEN = _hf_token() +QWEN_VL_MODEL = os.getenv("QWEN_VL_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct") +QWEN_TEXT_MODELS = [m.strip() for m in os.getenv( + "QWEN_TEXT_MODELS", + "Qwen/Qwen2.5-72B-Instruct,meta-llama/Llama-3.3-70B-Instruct,Qwen/Qwen2.5-7B-Instruct" +).split(",") if m.strip()] +_WORKING_MODEL_TEXT = None +_WORKING_MODEL_VL = None +DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data" +SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") +HEADERS = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36", + "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8" +} +LAST_QWEN_ERROR = "" + +# ===== MULTILINGUAL VOICES FOR TTS ===== +MULTILINGUAL_VOICES = { + # Vietnamese + "vi_female": "vi-VN-HoaMyNeural", + "vi_male": "vi-VN-NamMinhNeural", + "hoaimy": "vi-VN-HoaMyNeural", + "namminh": "vi-VN-NamMinhNeural", + # Multilingual - Andrew (hỗ trợ tiếng Việt) + "en_andrew": "en-US-AndrewNeural", + "andrew": "en-US-AndrewNeural", + # Multilingual - Jenny + "en_jenny": "en-US-JennyNeural", + "jenny": "en-US-JennyNeural", + # Portuguese - Thalita Multilingual + "pt_thalita": "pt-BR-ThalitaMultilingualNeural", + "thalita": "pt-BR-ThalitaMultilingualNeural", + "pt_francisco": "pt-BR-FranciscoNeural", + # Spanish + "es_ela": "es-ES-ElaNeural", + "ela": "es-ES-ElaNeural", + "es_carlos": "es-ES-CarlosNeural", + # French + "fr_denise": "fr-FR-DeniseNeural", + "denise": "fr-FR-DeniseNeural", + # German + "de_katja": "de-DE-KatjaNeural", + "katja": "de-DE-KatjaNeural", + # Japanese + "ja_nanami": "ja-JP-NanamiNeural", + "nanami": "ja-JP-NanamiNeural", + # Korean + "ko_sunhee": "ko-KR-SunHeeNeural", + "sunhee": "ko-KR-SunHeeNeural", + # Chinese + "zh_xiaochen": "zh-CN-XiaochenNeural", + "xiaochen": "zh-CN-XiaochenNeural", +} + +def _detect_voice_emotion(title, text): + """Detect appropriate voice and emotion based on content for multilingual TTS.""" + content = ((title or "") + " " + (text or "")).lower() - Prioritizes Llama-3.3-70B for better creative/opinion writing. - """ - token = _hf_token() - errors = [] + # World Cup / Football content - use Andrew multilingual + if any(kw in content for kw in ["world cup", "wc 2026", "fifa", "bóng đá", "trận đấu", "bóng bóng", "đội tuyển", "cầu thủ"]): + return ("andrew", "excited") # Andrew multilingual hỗ trợ tiếng Việt - # Try HF router API with multiple models - Llama FIRST for opinion writing - if token: - models = [ - os.getenv("QWEN_VL_MODEL", ""), - "meta-llama/Llama-3.3-70B-Instruct", # FIRST - best for opinion/analysis - "Qwen/Qwen2.5-VL-7B-Instruct", - "Qwen/Qwen2.5-72B-Instruct", - ] - # Deduplicate while preserving order - seen = set() - models = [m for m in models if m and m not in seen and not seen.add(m)] - - headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} - - for model in models: - try: - is_vl = "VL" in model and image_url - if is_vl: - user_content = [ - {"type": "image_url", "image_url": {"url": image_url}}, - {"type": "text", "text": prompt} - ] - else: - user_content = prompt - - payload = { - "model": model, - "messages": [ - {"role": "system", "content": "Bạn là nhà báo phản biện chuyên nghiệp. Luôn viết theo quan điểm cá nhân, phân tích sâu, không sao chép nguyên văn nguồn tin."}, - {"role": "user", "content": user_content}, - ], - "max_tokens": min(int(max_tokens or 2000), 2500), - "temperature": 0.75, - "top_p": 0.9, - } - - r = requests.post( - "https://router.huggingface.co/v1/chat/completions", - headers=headers, - json=payload, - timeout=95 - ) - - if r.status_code >= 300: - errors.append(f"{model}: HTTP {r.status_code}") - continue - - j = r.json() - txt = (j.get("choices", [{}])[0].get("message", {}).get("content") or "").strip() - - if txt: - return txt - - errors.append(f"{model}: empty response") - - except Exception as e: - errors.append(f"{model}: {type(e).__name__}") + # News categories - choose appropriate voice + if any(kw in content for kw in ["kinh tế", "tài chính", "thị trường", "economics", "finance"]): + return ("jenny", "calm") + if any(kw in content for kw in ["thiên tai", "bão", "lũ lụt", "cháy nổ", "tai nạn", "disaster", "accident"]): + return ("thalita", "serious") # Portuguese multilingual + if any(kw in content for kw in ["giải trí", "showbiz", "entertainment", "hài hước"]): + return ("ela", "happy") + if any(kw in content for kw in ["công nghệ", "tech", "technology", "ai", "trí tuệ nhân tạo"]): + return ("katja", "excited") - # Fallback: extractive summary from prompt - LAST_QWEN_ERROR = errors[-3:] if errors else "unknown error" - return _fallback_summary_from_prompt(prompt, max_units=6) - - -def _fallback_summary_from_prompt(prompt: str, max_units: int = 6) -> str: - """Generate a simple fallback summary when AI is unavailable.""" - text = prompt or "" - for marker in ["Nội dung nguồn:", "Nội dung bài:", "Nội dung gốc:", "Nội dung:", "Nguồn/bối cảnh internet:"]: - if marker in text: - text = text.split(marker, 1)[1] - break - text = re.sub(r"https?://\S+", "", text) - text = re.sub(r"\s+", " ", text).strip() - - # Split into sentences - sentences = re.split(r"(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])", text) - units = [] - for s in sentences: - s = _clean_text(s) - if len(s) >= 30: - units.append(s) - - if units: - result_units = units[:max_units] - return "\n".join("• " + u for u in result_units) - if text: - chunks = [] - for i in range(0, min(len(text), max_units * 300), 280): - chunk = _clean_text(text[i:i+300]) - if chunk and chunk not in chunks: - chunks.append(chunk) - if len(chunks) >= max_units: - break - if chunks: - return "\n".join("• " + c for c in chunks) - return "• Không có đủ nội dung để tóm tắt." - -# ===== URL scraping & article processing ===== -HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8"} - -try: - _shorts_base = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -except Exception: - _shorts_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -SHORTS_DIR = os.path.join(_shorts_base, "ai_shorts") -os.makedirs(SHORTS_DIR, exist_ok=True) - -import random as _random2 -from datetime import datetime, timezone, timedelta -_VN_TZ = timezone(timedelta(hours=7)) - - -def _safe_name(filename: str) -> str: - """Sanitize filename.""" - return re.sub(r"[^a-zA-Z0-9_.-]", "_", filename)[:120] - - -def pollinations_image_url(topic: str) -> str: - """Generate a placeholder image URL via Pollinations.""" - try: - return "https://image.pollinations.ai/prompt/" + quote("Vietnamese editorial illustration, " + topic, safe="") + "?width=1024&height=576&nologo=true" - except Exception: - return "" - - -def _download_image(url: str, fallback_title: str, out_path: str) -> str: - """Download an image from URL or create a placeholder.""" - if url: - try: - r = requests.get(url, headers=HEADERS, timeout=15) - if r.status_code == 200 and len(r.content) > 1200: - os.makedirs(os.path.dirname(out_path), exist_ok=True) - with open(out_path, "wb") as f: - f.write(r.content) - return out_path - except Exception: - pass - # Fallback: create a placeholder image - try: - from PIL import Image, ImageDraw, ImageFont - img = Image.new("RGB", (1080, 760), (24, 24, 24)) - draw = ImageDraw.Draw(img) - try: - font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48) - except Exception: - font = None - text = (fallback_title or "VNEWS")[:40] - try: - bbox = draw.textbbox((0, 0), text, font=font) - tw = bbox[2] - bbox[0] - except Exception: - tw = len(text) * 24 - draw.text(((1080 - tw) // 2, 330), text, fill=(255, 255, 255), font=font) - os.makedirs(os.path.dirname(out_path), exist_ok=True) - img.save(out_path, quality=90) - return out_path - except Exception: - return out_path - - -def scrape_any_url(url: str) -> dict: - """Scrape article content from any URL.""" - if not url or not url.startswith("http"): - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": ""} - try: - r = requests.get(url, headers=HEADERS, timeout=15, allow_redirects=True) - if r.status_code != 200 or not r.text: - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)} - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - for tag in soup.find_all(["script", "style", "nav", "footer", "aside", "form", "noscript", "iframe", ".ads", ".ad", ".banner-ads", ".fb-comments", ".fb-root", ".social-share", ".related-news", ".breadcrumb"]): - tag.decompose() - title = "" - ogt = soup.find("meta", property="og:title") - if ogt: - title = ogt.get("content", "") - h1 = soup.find("h1") - if not title and h1: - title = h1.get_text(strip=True) - if not title: - t = soup.find("title") - if t: - title = t.get_text(strip=True) - og_image = "" - ogi = soup.find("meta", property="og:image") - if ogi: - og_image = ogi.get("content", "") - if og_image.startswith("//"): - og_image = "https:" + og_image - summary = "" - ogd = soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"}) - if ogd: - summary = ogd.get("content", "")[:500] - body_text = [] - for sel in ["article", ".singular-content", ".detail-content", ".fck_detail", ".content-detail", ".knc-content", "main", ".cms-body", ".article__body", ".post-content", ".entry-content"]: - el = soup.select_one(sel) - if el and len(el.find_all("p")) >= 2: - for p in el.find_all("p"): - t = _clean_text(p.get_text(strip=True)) - if t and len(t) > 30: - body_text.append(t) - break - if not body_text and soup.body: - for p in soup.body.find_all("p"): - t = _clean_text(p.get_text(strip=True)) - if t and len(t) > 30: - body_text.append(t) - text = "\n".join(body_text) - return {"title": _clean_text(title), "text": text, "summary": _clean_text(summary), "image": og_image, "og_image": og_image, "via": _domain(url), "url": url} - except Exception as e: - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)} - - -def make_post(title: str, text: str, img: str, url: str, kind: str = "auto", sources: list = None) -> dict: - """Create a wall post dict.""" - import random as _r2 - now = int(time.time() * 1000) - return { - "id": str(now) + str(_r2.randint(100, 999)), - "title": (title or "Bài viết")[:200], - "text": (text or "")[:5000], - "img": img or "", - "url": url or "", - "kind": kind or "auto", - "sources": sources or [], - "created": now, - "created_str": datetime.now(_VN_TZ).strftime("%H:%M %d/%m/%Y"), - } + # Default Vietnamese + return ("hoaimy", "trung_tinh") diff --git a/ai_patch.py b/ai_patch.py index 41aeba3d810744429c14e473c32c3a9fb8e3a605..838f49f293c523e5ecf7f003f5b424a2928e23ee 100644 --- a/ai_patch.py +++ b/ai_patch.py @@ -42,17 +42,17 @@ def _similar(a, b): return len(ta & tb) / max(1, min(len(ta), len(tb))) >= 0.72 -def _dedupe_units(units, max_units=25): - """Deduplicate units - only skip exact matches to ensure all bullet points are read.""" +def _dedupe_units(units, max_units=7): out, seen = [], set() for u in units: u = _clean(re.sub(r"^[-•*\d\.\)\s]+", "", u)) if len(u) < 18: continue nu = _norm(u) - # Only skip exact matches, NOT similar content (to avoid skipping valid bullet points) if nu in seen: continue + if any(_similar(u, old) for old in out): + continue seen.add(nu) out.append(u) if len(out) >= max_units: @@ -60,7 +60,7 @@ def _dedupe_units(units, max_units=25): return out -def _postprocess_ai_text(text, max_units=20): +def _postprocess_ai_text(text, max_units=7): text = _clean(text) if not text: return text @@ -79,9 +79,10 @@ def _postprocess_ai_text(text, max_units=20): raw_lines.append(line) units = [] for line in raw_lines: - # KEEP FULL bullet point - don't truncate or split into segments - if len(line) >= 18: - units.append(_clean(re.sub(r"^[-•*\d\.\)\s]+", "", line))) + if len(line) > 260: + units.extend(re.split(r"(?<=[\.\!\?])\s+(?=[A-ZÀ-Ỹ0-9])", line)) + else: + units.append(line) units = _dedupe_units(units, max_units=max_units) if not units: return text[:900] @@ -268,7 +269,7 @@ async def qwen_generate_resilient(prompt: str, image_url=None, max_tokens: int = errors.append("missing HF_TOKEN") base.LAST_QWEN_ERROR = " | ".join(errors[-6:]) or "Qwen unavailable; used extractive fallback" print("[qwen resilient fallback]", base.LAST_QWEN_ERROR) - return _fallback_summary_from_prompt(prompt, max_units=12) + return _fallback_summary_from_prompt(prompt, max_units=6) if not hasattr(base, "_original_qwen_generate"): @@ -321,30 +322,12 @@ Yêu cầu bắt buộc: Nội dung bài: {art['raw'][:14000]}""" - text = await base.qwen_generate(prompt, image_url=art.get('image') or None, max_tokens=1500) - text = _postprocess_ai_text(text, max_units=20) + text = await base.qwen_generate(prompt, image_url=art.get('image') or None, max_tokens=900) + text = _postprocess_ai_text(text, max_units=6) src = [art['source']] if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) post = base.make_post(art['title'], text, art.get('image') or base.pollinations_image_url(art['title']), art.get('url') or '', 'topic_article', sources=src) - - # Generate slides for this post so they persist after page reload - try: - page_data = _scrape_article_images(art.get('url', '')) - if page_data and page_data.get('paragraphs'): - key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12) - if key_points: - relevant_imgs = page_data.get('images', []) - if not relevant_imgs and page_data.get('og_img'): - relevant_imgs = [page_data['og_img']] - slides = [] - for i, point in enumerate(key_points): - img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') - slides.append({'text': point, 'image': img, 'index': i + 1}) - post['slides'] = slides - except Exception: - pass - new_posts.append(post) posts = new_posts + posts base._save_ai_wall(posts) @@ -365,142 +348,14 @@ async def compat_url_wall(request: Request): if len(raw) < 120: return JSONResponse({'error': 'URL không có đủ nội dung để tóm tắt'}, status_code=422) prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url)) - text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=1500) - text = _postprocess_ai_text(text, max_units=20) + text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=850) + text = _postprocess_ai_text(text, max_units=6) src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}] if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'url', sources=src) - - # Generate slides so they persist after page reload - slides = [] - try: - page_data = _scrape_article_images(url) - if page_data and page_data.get('paragraphs'): - key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12) - if key_points: - relevant_imgs = page_data.get('images', []) - if not relevant_imgs and page_data.get('og_img'): - relevant_imgs = [page_data['og_img']] - for i, point in enumerate(key_points): - img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') - slides.append({'text': point, 'image': img, 'index': i + 1}) - except Exception: - pass - post['slides'] = slides - posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts) - return JSONResponse({'post': post, 'slides': slides}) - - -def _is_relevant_image(img_url, title, text): - """Check if an image is relevant to the article content.""" - if not img_url: - return False - skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif', - 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite', - 'advertisement', 'ad-banner', 'sponsored', 'banner-ads'] - img_lower = img_url.lower() - for p in skip_patterns: - if p in img_lower: - return False - if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']): - return False - return True - - -def _filter_relevant_images(images, title, text, max_images=8): - """Filter and rank images by relevance to article content.""" - if not images: - return [] - seen = set() - relevant = [] - for img in images: - if img in seen: - continue - seen.add(img) - if _is_relevant_image(img, title, text): - relevant.append(img) - return relevant[:max_images] - - -def _extract_key_points_for_slides(paragraphs, max_points=12): - """Extract key points from paragraphs for slides - extracts ALL sentences, not just first one.""" - points = [] - for p in paragraphs: - if len(points) >= max_points: - break - p = _clean(p) - if not p: - continue - # Split paragraph into sentences using Vietnamese + English punctuation - GET ALL SENTENCES - sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p) - sentences = [s.strip() for s in sentences if s.strip()] - - for sentence in sentences: - if len(points) >= max_points: - break - sentence = _clean(sentence) - if len(sentence) < 30: - continue - if any(sentence[:60] in existing for existing in points): - continue - if not sentence.endswith(('.', '!', '?')): - sentence = sentence + '.' - points.append(sentence) - return points - - -def _scrape_article_images(url): - """Scrape article page and return only relevant images.""" - try: - headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", - "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8"} - r = requests.get(url, headers=headers, timeout=15, allow_redirects=True) - r.encoding = 'utf-8' - soup = BeautifulSoup(r.text, 'lxml') - for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']): - tag.decompose() - h1 = soup.find('h1') - ogt = soup.find('meta', property='og:title') - title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '') - ogi = soup.find('meta', property='og:image') - og_img = ogi.get('content', '') if ogi else '' - if og_img and og_img.startswith('//'): - og_img = 'https:' + og_img - block = None - for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']: - el = soup.select_one(sel) - if el and len(el.find_all('p')) >= 2: - block = el - break - if not block: - block = soup.body or soup - paragraphs = [] - all_images = [] - seen_imgs = set() - if og_img and og_img not in seen_imgs: - all_images.append(og_img) - seen_imgs.add(og_img) - for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True): - if el.name == 'p': - t = _clean(el.get_text(strip=True)) - if t and len(t) > 40: - paragraphs.append(t) - elif el.name in ('figure', 'img'): - im = el if el.name == 'img' else el.find('img') - if im: - src = im.get('data-src') or im.get('src') or im.get('data-original') or '' - if src and 'base64' not in src: - if src.startswith('//'): - src = 'https:' + src - if src not in seen_imgs: - all_images.append(src) - seen_imgs.add(src) - relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5])) - return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img} - except Exception: - return None + return JSONResponse({'post': post}) @app.post('/api/rewrite_share') @@ -517,42 +372,31 @@ async def compat_rewrite_share(request: Request): if len(raw) < 120: return JSONResponse({'error': 'Bài viết không đủ nội dung để tóm tắt'}, status_code=422) prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url)) - text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=1500) - text = _postprocess_ai_text(text, max_units=20) + text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=850) + text = _postprocess_ai_text(text, max_units=6) src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}] if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'summary', sources=src) - - # Generate slides with relevant images only - slides = [] - page_data = _scrape_article_images(url) - if page_data and page_data.get('paragraphs'): - key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12) - if key_points: - relevant_imgs = page_data.get('images', []) - if not relevant_imgs and page_data.get('og_img'): - relevant_imgs = [page_data['og_img']] - for i, point in enumerate(key_points): - img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') - slides.append({'text': point, 'image': img, 'index': i + 1}) - - # FIX: Save slides into post so they persist after page reload - post['slides'] = slides posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts) - - return JSONResponse({'post': post, 'slides': slides}) + return JSONResponse({'post': post}) def _emotion_script(text, emotion): - """Prepend emotion-appropriate prefix to text based on emotion type. - - NOTE: Prefix is NOT added to avoid cluttering Short AI speech. - The emotion is still used for voice selection but content is read cleanly. - """ + """Prepend emotion-appropriate prefix to text based on emotion type.""" text = _clean(text) - # REMOVED: No prefix added to keep content clean and natural - return text + prefixes = { + 'urgent': 'Tin nhanh. ', + 'warm': 'Câu chuyện đáng chú ý. ', + 'serious': 'Bản tin nghiêm túc. ', + 'energetic': 'Cập nhật nổi bật. ', + 'happy': 'Tin vui! ', + 'sad': 'Tin buồn. ', + 'humorous': 'Chút hài hước. ', + 'neutral': '', + } + prefix = prefixes.get(emotion, '') + return prefix + text def _tts_script_smart(post, emotion): @@ -561,12 +405,11 @@ def _tts_script_smart(post, emotion): raw = re.sub(r"\s*\n\s*", ". ", raw) raw = re.sub(r"([\.\!\?])\s*", r"\1\n", raw) raw = re.sub(r"\n{2,}", "\n", raw).strip() - # REMOVED: _emotion_script call - read content cleanly without prefix - # INCREASED to 3000 to read full content of all bullet points - if len(raw) > 3000: - raw = raw[:3000] + raw = _emotion_script(raw, emotion) + if len(raw) > 1000: + raw = raw[:1000] cut = max(raw.rfind("."), raw.rfind("!"), raw.rfind("?")) - if cut > 700: + if cut > 350: raw = raw[:cut + 1] return raw @@ -681,7 +524,7 @@ def _make_short_frame_full(post, img_path, out_path): -def _summary_segments_from_post(post, max_segments=25): +def _summary_segments_from_post(post, max_segments=7): raw = _clean(post.get('text') or post.get('title') or '') raw = re.sub(r'^Bản tin AI viết lại:\s*', '', raw, flags=re.I) raw = re.sub(r'Nguồn tham khảo:.*$', '', raw, flags=re.I|re.S).strip() @@ -692,7 +535,7 @@ def _summary_segments_from_post(post, max_segments=25): low=ln.lower() if low.startswith(('điểm chính','tiêu đề','sapo','nguồn tham khảo')): continue if len(ln)>=18: lines.append(ln) - if len(lines)<3: + if len(lines)<2: lines=[] for s in re.split(r'(?<=[\.\!\?])\s+', raw): s=_clean(s) @@ -744,8 +587,7 @@ def _make_scene_frame(post, segment, idx, total, img_path, out_path, emotion='ne draw.rounded_rectangle((48,834,260,880), radius=20, fill=(28,70,45)) draw.text((66,842),f'Đoạn {idx+1}/{total}',fill=(235,235,235),font=font_small) y=940; maxw=W-96 - # INCREASED from 12 to 18 for full content display - each key point can span multiple lines - for ln in _wrap_text_px(draw, segment, font_seg, maxw, 18): + for ln in _wrap_text_px(draw, segment, font_seg, maxw, 8): draw.text((48,y),ln,fill=(255,255,255),font=font_seg) y+=74 if y>1500: break @@ -757,11 +599,10 @@ def _make_scene_frame(post, segment, idx, total, img_path, out_path, emotion='ne bg.save(out_path, quality=92) -def _estimate_audio_duration(path, fallback=15.0): - """Estimate audio duration with 15s minimum per segment for complete bullet reading.""" +def _estimate_audio_duration(path, fallback=4.0): try: pr=subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','default=noprint_wrappers=1:no_key=1',path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20) - return max(12.0, float((pr.stdout or b'').decode().strip() or fallback)) + return max(1.5, float((pr.stdout or b'').decode().strip() or fallback)) except Exception: return fallback @@ -774,7 +615,7 @@ async def patched_ai_short(post_id: str, request: Request): body = {} voice = str(body.get('voice', 'nu')).strip().lower() emotion = str(body.get('emotion', 'neutral')).strip().lower() - speed = float(body.get('speed', 1.0) or 1.0) + speed = float(body.get('speed', 1.2) or 1.2) speed = max(0.85, min(1.35, speed)) posts = base._load_ai_wall() @@ -782,7 +623,7 @@ async def patched_ai_short(post_id: str, request: Request): if not post: return JSONResponse({'error': 'post not found'}, status_code=404) - segments = _summary_segments_from_post(post, max_segments=25) + segments = _summary_segments_from_post(post, max_segments=7) seg_hash = hashlib.md5(('|'.join(segments)+voice+emotion+str(speed)).encode('utf-8')).hexdigest()[:8] os.makedirs(base.SHORTS_DIR, exist_ok=True) suffix = f"_{voice}_{emotion}_{str(speed).replace('.', 'p')}_{seg_hash}_scenes_nosub" @@ -806,62 +647,50 @@ async def patched_ai_short(post_id: str, request: Request): base._download_image(post.get('img'), post.get('title', 'AI news'), img) edge_voice = { # Vietnamese - 'vi-vn-hoaimyneural': 'vi-VN-HoaiMyNeural', - 'vi-vn-namminhneural': 'vi-VN-NamMinhNeural', - 'hoaimy': 'vi-VN-HoaiMyNeural', - 'namminh': 'vi-VN-NamMinhNeural', 'nam': 'vi-VN-NamMinhNeural', 'male': 'vi-VN-NamMinhNeural', 'nu': 'vi-VN-HoaiMyNeural', 'female': 'vi-VN-HoaiMyNeural', 'mien-nam': 'vi-VN-HoaiMyNeural', - # English - Multilingual - 'en-us-andrewmultilingualneural': 'en-US-AndrewMultilingualNeural', - 'en-au-williammultilingualneural': 'en-AU-WilliamMultilingualNeural', - 'andrew': 'en-US-AndrewMultilingualNeural', - 'en_andrew': 'en-US-AndrewMultilingualNeural', - 'jenny': 'en-US-AndrewMultilingualNeural', - 'en_jenny': 'en-US-AndrewMultilingualNeural', - # Portuguese - Multilingual (ONLY Thalita) - 'pt-br-thalitamultilingualneural': 'pt-BR-ThalitaMultilingualNeural', + 'hoaimy': 'vi-VN-HoaiMyNeural', + 'namminh': 'vi-VN-NamMinhNeural', + # Multilingual - Andrew + 'andrew': 'en-US-AndrewNeural', + 'en_andrew': 'en-US-AndrewNeural', + # Multilingual - Jenny + 'jenny': 'en-US-JennyNeural', + 'en_jenny': 'en-US-JennyNeural', + # Portuguese - Thalita Multilingual 'thalita': 'pt-BR-ThalitaMultilingualNeural', 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural', 'pt_br_thalita': 'pt-BR-ThalitaMultilingualNeural', - 'pt': 'pt-BR-ThalitaMultilingualNeural', - 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural', - # French - Multilingual - 'fr-fr-viviennemultilingualneural': 'fr-FR-VivienneMultilingualNeural', - 'fr-fr-remymultilingualneural': 'fr-FR-RemyMultilingualNeural', - 'denise': 'fr-FR-VivienneMultilingualNeural', - 'fr': 'fr-FR-VivienneMultilingualNeural', - 'fr_denise': 'fr-FR-VivienneMultilingualNeural', - # German - Multilingual - 'de-de-seraphinamultilingualneural': 'de-DE-SeraphinaMultilingualNeural', - 'de-de-florianmultilingualneural': 'de-DE-FlorianMultilingualNeural', - 'katja': 'de-DE-SeraphinaMultilingualNeural', - 'de': 'de-DE-SeraphinaMultilingualNeural', - 'de_katja': 'de-DE-SeraphinaMultilingualNeural', - # Korean - Multilingual (Hyunsu, NOT SunHee) - 'ko-kr-hyusumultilingualneural': 'ko-KR-HyunsuMultilingualNeural', - 'ko-kr-hyunsuneural': 'ko-KR-HyunsuMultilingualNeural', - 'sunhee': 'ko-KR-HyunsuMultilingualNeural', - 'ko': 'ko-KR-HyunsuMultilingualNeural', - 'ko_sunhee': 'ko-KR-HyunsuMultilingualNeural', - # Italian - Multilingual - 'it-it-giuseppemultilingualneural': 'it-IT-GiuseppeMultilingualNeural', - # Spanish (keep for backward compat) - 'ela': 'en-US-AndrewMultilingualNeural', - 'es_ela': 'en-US-AndrewMultilingualNeural', - 'es': 'en-US-AndrewMultilingualNeural', - 'es_carlos': 'en-US-AndrewMultilingualNeural', - # Japanese (keep for backward compat) - 'nanami': 'en-US-AndrewMultilingualNeural', - 'ja': 'en-US-AndrewMultilingualNeural', - 'ja_nanami': 'en-US-AndrewMultilingualNeural', - # Chinese (keep for backward compat) - 'xiaochen': 'en-US-AndrewMultilingualNeural', - 'zh': 'en-US-AndrewMultilingualNeural', - 'zh_xiaochen': 'en-US-AndrewMultilingualNeural', + 'pt': 'pt-BR-FranciscoNeural', + 'pt_francisco': 'pt-BR-FranciscoNeural', + # Spanish + 'ela': 'es-ES-ElaNeural', + 'es_ela': 'es-ES-ElaNeural', + 'es': 'es-ES-CarlosNeural', + 'es_carlos': 'es-ES-CarlosNeural', + # French + 'denise': 'fr-FR-DeniseNeural', + 'fr': 'fr-FR-DeniseNeural', + 'fr_denise': 'fr-FR-DeniseNeural', + # German + 'katja': 'de-DE-KatjaNeural', + 'de': 'de-DE-KatjaNeural', + 'de_katja': 'de-DE-KatjaNeural', + # Japanese + 'nanami': 'ja-JP-NanamiNeural', + 'ja': 'ja-JP-NanamiNeural', + 'ja_nanami': 'ja-JP-NanamiNeural', + # Korean + 'sunhee': 'ko-KR-SunHeeNeural', + 'ko': 'ko-KR-SunHeeNeural', + 'ko_sunhee': 'ko-KR-SunHeeNeural', + # Chinese + 'xiaochen': 'zh-CN-XiaochenNeural', + 'zh': 'zh-CN-XiaochenNeural', + 'zh_xiaochen': 'zh-CN-XiaochenNeural', }.get(voice, 'vi-VN-HoaiMyNeural') part_files=[] for idx, seg in enumerate(segments): @@ -880,7 +709,7 @@ async def patched_ai_short(post_id: str, request: Request): except TypeError: base.gTTS(spoken, lang='vi', slow=False).save(aud) subprocess.run(['ffmpeg','-y','-i',aud,'-filter:a',f'atempo={speed}','-vn',aud_fast], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90) - dur=_estimate_audio_duration(aud_fast, fallback=15.0)+0.35 + dur=_estimate_audio_duration(aud_fast, fallback=4.0)+0.35 subprocess.run(['ffmpeg','-y','-loop','1','-t',str(dur),'-i',frame,'-i',aud_fast,'-shortest','-c:v','libx264','-tune','stillimage','-pix_fmt','yuv420p','-c:a','aac','-b:a','128k',part], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150) part_files.append(part) concat=os.path.join(work,'concat.txt') diff --git a/ai_runtime_fix.py b/ai_runtime_fix.py deleted file mode 100644 index 0ec96f7c3c57d95b682765689d6ed0964058cd85..0000000000000000000000000000000000000000 --- a/ai_runtime_fix.py +++ /dev/null @@ -1,394 +0,0 @@ -"""VNEWS Short Video Fix - standalone module with clean registration. -This module MUST be imported LAST to register /api/ai/short endpoints. -FIX v1: No route filtering issues - registers endpoints unconditionally. -FIX v2: SSE inline endpoint for auto homepage updates -""" -import os -import re -import time -import json -import sys -import logging -import asyncio -import hashlib -import subprocess -import requests -from datetime import datetime, timezone, timedelta -from urllib.parse import urlparse -from fastapi import Request, Query -from fastapi.responses import JSONResponse, FileResponse - -# Import dependencies -try: - import ai_ext as base -except ImportError: - import ai_runtime_final6 as base - -# Try to import app from various sources -try: - from app_v2_entry import app -except ImportError: - try: - from main import app - except ImportError: - from ai_runtime_final6 import app - -_log = logging.getLogger("short_fix") -_log.setLevel(logging.INFO) -if not _log.handlers: - _log.addHandler(logging.StreamHandler(sys.stderr)) - -DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data" -os.makedirs(DATA_DIR, exist_ok=True) -SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") -os.makedirs(SHORTS_DIR, exist_ok=True) - -# ===== VIETNAMESE FONT DETECTION ===== -_VN_FONT_REG = None -_VN_FONT_BOLD = None - -def _get_vn_fonts(): - """Find Vietnamese-supporting fonts.""" - global _VN_FONT_REG, _VN_FONT_BOLD - if _VN_FONT_REG is not None: - return _VN_FONT_REG, _VN_FONT_BOLD - - try: - from PIL import ImageFont - except Exception: - _log.error("PIL not available!") - return None, None - - # Priority: Noto > DejaVu > Liberation - reg_paths = [ - "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", - "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", - "/usr/share/fonts/truetype/freefont/FreeSans.ttf", - ] - bold_paths = [ - "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf", - "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", - "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", - "/usr/share/fonts/truetype/freefont/FreeSans.ttf", - ] - - for path in reg_paths: - if os.path.exists(path): - try: - _VN_FONT_REG = ImageFont.truetype(path, 40) - _log.info(f"Found regular font: {path}") - break - except: - continue - - for path in bold_paths: - if os.path.exists(path): - try: - _VN_FONT_BOLD = ImageFont.truetype(path, 52) - _log.info(f"Found bold font: {path}") - break - except: - continue - - if _VN_FONT_REG is None: - _VN_FONT_REG = ImageFont.load_default() - if _VN_FONT_BOLD is None: - _VN_FONT_BOLD = _VN_FONT_REG - - return _VN_FONT_REG, _VN_FONT_BOLD - - -def _clean(s): - import html as html_lib - return re.sub(r"\s+", " ", html_lib.unescape(str(s or ""))).strip() - - -# ===== ROBUST TEXT SEGMENTATION ===== -def _split_into_segments(text, max_segments=10, min_len=30): - """Split text into segments - multi strategy.""" - text = _clean(text) - if not text: - return [] - - # Strategy 1: bullet points - lines = text.split('\n') - segmented = [] - for line in lines: - line = _clean(line) - line_bare = re.sub(r'^[•\-\*\d\.\)\s]+', '', line).strip() - if len(line_bare) > min_len: - segmented.append(line_bare) - elif len(line) > min_len: - segmented.append(line) - - # Strategy 2: sentences (Vietnamese) - if len(segmented) < 2: - sents = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9À-ỸĐ])', text) - segmented = [s for s in sents if len(_clean(s)) > min_len] - - # Strategy 3: character chunks - if not segmented: - words = text.split() - for i in range(0, min(len(words), max_segments * 20), 20): - chunk = ' '.join(words[i:i+20]) - if len(chunk) > min_len: - segmented.append(chunk) - - # Strategy 4: fallback - if not segmented: - segmented = [text[:300]] - - return segmented[:max_segments] - - -# ===== SHORT VIDEO GENERATOR ===== -def _gen_short_core(post, work_dir): - """Core short generation - returns video path or None.""" - post_id = post.get('id', '') - text = post.get('text', '') or post.get('title', '') - - if not post_id or len(text) < 100: - _log.error(f"Invalid post: id={post_id}, text_len={len(text)}") - return None - - segments = _split_into_segments(text, max_segments=10, min_len=30) - if not segments: - _log.error("No segments generated") - return None - - _log.info(f"Generating short: {len(segments)} segments") - - seg_hash = hashlib.md5(('|'.join(segments) + 'nu').encode()).hexdigest()[:8] - suffix = f"_nu_{seg_hash}" - out_mp4 = os.path.join(work_dir, f"{post_id}{suffix}.mp4") - - if os.path.exists(out_mp4): - _log.info(f"Already exists: {out_mp4}") - return out_mp4 - - # Check dependencies - try: - subprocess.run(['ffmpeg', '-version'], capture_output=True, timeout=5) - except Exception as e: - _log.error(f"ffmpeg missing: {e}") - return None - - # Download image - img_path = os.path.join(work_dir, 'bg.jpg') - downloaded = False - try: - img_url = post.get('img', '') - if img_url and img_url.startswith('http'): - r = requests.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=12) - if r.status_code == 200: - with open(img_path, 'wb') as f: - f.write(r.content) - downloaded = True - except Exception as e: - _log.warning(f"Image download: {e}") - - try: - from PIL import Image, ImageDraw - has_pil = True - except: - has_pil = False - _log.warning("PIL not available") - - try: - from gtts import gTTS - has_tts = True - except: - has_tts = False - _log.warning("gTTS not available") - - parts = [] - - for i, seg in enumerate(segments[:10]): - frame = os.path.join(work_dir, f'frame_{i}.jpg') - audio = os.path.join(work_dir, f'audio_{i}.mp3') - part = os.path.join(work_dir, f'part_{i}.mp4') - - # Create frame - try: - if has_pil: - _make_frame(post, seg, img_path, downloaded, frame) - else: - subprocess.run(['ffmpeg', '-y', '-f', 'lavfi', '-i', - 'color=c=black:s=1080x1920:d=1', '-frames:v', '1', frame], - capture_output=True, timeout=20) - except Exception as e: - _log.error(f"Frame error: {e}") - continue - - # Create audio - if has_tts: - try: - tts = _clean(seg)[:300] - gTTS(tts, lang='vi', slow=False).save(audio) - except Exception as e: - _log.warning(f"TTS error: {e}") - audio = None - - # Combine - dur = 10 - try: - cmd = ['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame] - if has_tts and os.path.exists(audio): - cmd += ['-i', audio, '-shortest'] - else: - cmd += ['-f', 'lavfi', '-i', 'anullsrc', '-shortest'] - cmd += ['-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p', - '-c:a', 'aac', '-b:a', '128k', part] - subprocess.run(cmd, capture_output=True, timeout=120) - if os.path.exists(part) and os.path.getsize(part) > 5000: - parts.append(part) - except Exception as e: - _log.error(f"Part combine error: {e}") - - if not parts: - _log.error("No video parts created!") - return None - - # Concatenate - try: - concat = os.path.join(work_dir, 'list.txt') - with open(concat, 'w') as f: - for p in parts: - f.write(f"file '{p}'\n") - subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4], - capture_output=True, timeout=180) - _log.info(f"Short created: {out_mp4}") - return out_mp4 - except Exception as e: - _log.error(f"Concat error: {e}") - return None - - -def _make_frame(post, text, img_path, downloaded, out_path): - """Create video frame with Vietnamese font.""" - from PIL import Image, ImageDraw - _get_vn_fonts() - - W, H = 1080, 1920 - bg = Image.new('RGB', (W, H), (15, 23, 38)) - d = ImageDraw.Draw(bg) - - # Background image - if downloaded and os.path.exists(img_path): - try: - im = Image.open(img_path).convert('RGB') - im = im.resize((W, 760)) - bg.paste(im, (0, 0)) - except: - pass - - # Title - d.rectangle([0, 0, W, 100], fill=(25, 118, 210)) - ttl = post.get('title', '')[:50] - if _VN_FONT_BOLD: - d.text((W//2, 50), ttl, fill='white', font=_VN_FONT_BOLD, anchor='mm') - - # Content - y = 150 - for ln in _wrap_text(d, text[:200], _VN_FONT_REG, 80, 920, 10): - d.text((80, y), ln, fill='white', font=_VN_FONT_REG) - y += 55 - - bg.save(out_path, quality=85) - - -def _wrap_text(draw, text, font, x, max_w, max_lines): - """Word wrap text.""" - words = text.split() - lines = [] - cur = [] - for w in words: - test = ' '.join(cur + [w]) - try: - w_px = draw.textbbox((0, 0), test, font=font)[2] - except: - w_px = len(test) * 22 - if w_px <= max_w: - cur.append(w) - else: - if cur: - lines.append(' '.join(cur)) - cur = [w] - if len(lines) >= max_lines: - break - if cur and len(lines) < max_lines: - lines.append(' '.join(cur)) - return lines - - -def _gen_short_sync(post) -> str: - """Sync wrapper - returns video URL.""" - work = os.path.join(SHORTS_DIR, f"work_{post.get('id', int(time.time()))}") - os.makedirs(work, exist_ok=True) - result = _gen_short_core(post, work) - if result: - # Update wall - try: - wall = base._load_ai_wall() - for i, p in enumerate(wall): - if str(p.get('id')) == str(post.get('id')): - p['video'] = f'/api/ai/short-file/{post.get("id")}_nu_{hashlib.md5(str(post).encode()).hexdigest()[:8]}' - wall[i] = p - break - base._save_ai_wall(wall) - # Notify SSE for auto-update - try: - from auto_update_sse import notify_new_short - notify_new_short(post) - except: - pass - except Exception as e: - _log.warning(f"Wall update: {e}") - return result - return '' - - -# ===== REGISTER ENDPOINTS - MUST BE AT MODULE LEVEL ===== -@app.post('/api/ai/short/{post_id}') -async def api_short_generate(post_id: str, request: Request): - _log.info(f"POST /api/ai/short/{post_id}") - wall = base._load_ai_wall() - post = next((p for p in wall if str(p.get('id')) == str(post_id)), None) - if not post: - return JSONResponse({'error': 'Post not found in wall'}, status_code=404) - - if post.get('video'): - return JSONResponse({'post': post, 'video': post['video'], 'status': 'done'}) - - loop = asyncio.get_event_loop() - result = await loop.run_in_executor(None, _gen_short_sync, post) - - if result: - # Get the video URL from wall (updated in _gen_short_sync) - wall = base._load_ai_wall() - post = next((p for p in wall if str(p.get('id')) == str(post_id)), post) - return JSONResponse({'post': post, 'video': post.get('video'), 'status': 'done'}) - return JSONResponse({'error': 'Video generation failed'}, status_code=500) - - -@app.get('/api/ai/short-file/{file_id:path}') -async def api_short_file(file_id: str): - safe = re.sub(r'[^\w\-.]', '_', file_id)[:100] - for fname in os.listdir(SHORTS_DIR) if os.path.isdir(SHORTS_DIR) else []: - if fname.endswith('.mp4') and safe in fname: - return FileResponse(os.path.join(SHORTS_DIR, fname), media_type='video/mp4') - return JSONResponse({'error': 'Not found'}, status_code=404) - - -# ===== SSE ENDPOINT FOR AUTO-UPDATE ===== -try: - from auto_update_sse import sse_events as _sse_handler - app.add_api_route('/api/events', _sse_handler, methods=['GET']) - _log.info("SSE endpoint registered at /api/events") -except Exception as e: - _log.warning(f"SSE route not loaded: {e}") - - -# Log startup -_log.info("Short video endpoints registered") \ No newline at end of file diff --git a/ai_runtime_patch_fast.py b/ai_runtime_patch_fast.py index e08d425c45bba58bd73cb1ed98f7a4dbb7828b43..126cc9a14012fabb8b4f72064810a56a1c663802 100644 --- a/ai_runtime_patch_fast.py +++ b/ai_runtime_patch_fast.py @@ -1,5 +1,5 @@ """Final patch v2: fix topic rewrite, remove duplicate short slide, full short interaction buttons.""" -import re, threading, time, json, os, asyncio, requests +import re, threading, time, json, os, asyncio import ai_runtime_final6 as f6 from ai_runtime_final6 import app, rt, f5, HTMLResponse, JSONResponse, Request, Query import html as html_lib @@ -121,69 +121,6 @@ async def _tp(request:Request): post=f5.base.make_post(topic,text,img,'','topic_focused',sources=[s for s in src if s.get('url')]);post['images']=[img];post['source_details']=det ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post}) -# ===== M3U IPTV Channels (FPT Play Bóng Đá live streams) ===== -_M3U_URL = "https://raw.githubusercontent.com/Love4vn/Stalker2M3U/refs/heads/1/live_schedule_Optimize.m3u" -_m3u_cache = {"t": 0, "d": []} - -def _parse_m3u(): - """Fetch & parse the M3U playlist. Returns list of channel dicts.""" - r = requests.get(_M3U_URL, headers={"User-Agent": "Mozilla/5.0"}, timeout=20) - if r.status_code != 200: - return [] - lines = r.text.splitlines() - out = [] - cur = {} - for line in lines: - line = line.strip() - if line.startswith("#EXTINF"): - t_match = re.search(r',(.+)$', line) - cur = { - "title": t_match.group(1).strip() if t_match else "Channel", - "id": "", - "logo": "", - "group": "", - "url": "", - "vlcopts": {}, - } - for attr_match in re.finditer(r'(\w+)="([^"]*)"', line): - k, v = attr_match.group(1), attr_match.group(2) - if k == "tvg-id": - cur["id"] = v - elif k == "tvg-logo": - cur["logo"] = v - elif k == "group-title": - cur["group"] = v - elif line.startswith("#EXTVLCOPT:"): - key_part = line[len("#EXTVLCOPT:"):] - if "=" in key_part: - k, v = key_part.split("=", 1) - cur.setdefault("vlcopts", {})[k.strip()] = v.strip() - elif line and not line.startswith("#") and cur: - cur["url"] = line - out.append(cur) - cur = {} - # Deduplicate by URL (same channel may have multiple stalker entries) - seen = set() - deduped = [] - for c in out: - if c["url"] not in seen: - seen.add(c["url"]) - deduped.append(c) - return deduped - -@app.get('/api/m3u/channels') -def api_m3u_channels(refresh: int = Query(default=0)): - n = int(time.time()) - if not refresh and _m3u_cache["d"] and n - _m3u_cache["t"] < 300: - return JSONResponse({"channels": _m3u_cache["d"], "updated": _m3u_cache["t"]}) - try: - channels = _parse_m3u() - _m3u_cache["t"] = n - _m3u_cache["d"] = channels - return JSONResponse({"channels": channels, "updated": n}) - except Exception as e: - return JSONResponse({"channels": _m3u_cache["d"], "updated": _m3u_cache["t"], "error": str(e)}) - PATCH_INJECT=r'''
''' diff --git a/ai_runtime_patch_final.py b/ai_runtime_patch_final.py deleted file mode 100644 index 0512ad0ef58446a2f791f8f85e0457950cdd54d3..0000000000000000000000000000000000000000 --- a/ai_runtime_patch_final.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Final patch: homepage fix + AI topics at top + SSE auto-update""" -import re, json, time -from fastapi.responses import HTMLResponse, JSONResponse -from fastapi import Query - -# Import chain - must be after ai_runtime_final6 -try: - import ai_runtime_final6 as f6 - from ai_runtime_final6 import app, f5 - from main import rt -except Exception as e: - print(f"[ERROR] f6 import: {e}") - f6 = None - f5 = None - rt = None - -PATCH_CSS_JS = r''' - -
- -''' - -# Register route if possible -if f6 and app: - try: - # Remove duplicate / route to avoid conflict - original_routes = [r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))] - app.router.routes = original_routes - - @app.get('/') - async def patch_homepage(): - html = f5.f4.f3.f2.f1._load_index_html() if f5 else "" - body = "" - if hasattr(rt,'old') and hasattr(rt.old,'PATCH_INJECT'): - body += getattr(rt.old,'PATCH_INJECT','') - if f5: - body += getattr(f5.f4.f3.f2.f1,'FINAL_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5.f4.f3,'FINAL3_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5.f4,'FINAL4_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5,'FINAL5_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f6,'FINAL6_INJECT','') if f6 else '' - body += getattr(f6,'FINAL6_FAST_HOME_INJECT','') if f6 else '' - body += getattr(f6,'FINAL6E_INJECT','') if f6 else '' - body += PATCH_CSS_JS - if '' in html: - html = html.replace('', body + '\n') - else: - html = html + body - return HTMLResponse(html) - except Exception as e: - print(f"[ERROR] register route: {e}") \ No newline at end of file diff --git a/ai_short_v2.py b/ai_short_v2.py deleted file mode 100644 index 675704f10853a311f3d9ec2f2761012140901c6a..0000000000000000000000000000000000000000 --- a/ai_short_v2.py +++ /dev/null @@ -1,2083 +0,0 @@ -"""VNEWS Short AI v2 — Short creator with TikTok background music, uploaded audio, -uploaded video/image background, and 'recreate from designed slides' (image-only, -reusing previous short audio, NO text overlays) mode. - -Registered by app_v2_entry.py (import ai_short_v2). Uses the SAME wall store -(WALL_FILE) as the wall endpoints so posts created by the designer survive and -can be re-shorted purely from designed images. -""" -import os -import re -import json -import time -import uuid -import hashlib -import subprocess -import threading - -import requests -from urllib.parse import quote as urllib_quote -from fastapi import Request, UploadFile, File, Query -from fastapi.responses import JSONResponse, FileResponse, Response, StreamingResponse - -try: - import yt_dlp -except Exception: # pragma: no cover - yt_dlp = None - -try: - from PIL import Image, ImageDraw, ImageFont -except Exception: # pragma: no cover - Image = ImageDraw = ImageFont = None - -try: - from main import app -except Exception: # pragma: no cover - from fastapi import FastAPI - app = FastAPI() - -DATA_DIR = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -WALL_FILE = os.path.join(DATA_DIR, "wall_posts.json") -SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") -UPLOAD_DIR = os.path.join(DATA_DIR, "short_uploads") -WALL_IMG_DIR = os.path.join(DATA_DIR, "wall_imgs") -os.makedirs(SHORTS_DIR, exist_ok=True) -os.makedirs(UPLOAD_DIR, exist_ok=True) - -_wl_lock = threading.Lock() - -UA_HEADERS = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " - "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", - "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8", -} - -# --------------------------------------------------------------------------- -# Video scraping (YouTube / TikTok / news sites) via yt-dlp + oEmbed fallback -# --------------------------------------------------------------------------- -_SCRAPE_CACHE = {} # url -> {ok, ...} (in-memory, TTL 30 min) -_SCRAPE_TTL = 30 * 60 - -YTDLP_OPTS = { - "format": "best[height<=720][ext=mp4]/best[height<=720]/best", - "quiet": True, - "no_warnings": True, - "noplaylist": True, - "socket_timeout": 30, - "retries": 5, - "fragment_retries": 5, - "ignoreerrors": False, - "extractor_args": {"youtube": {"player_client": ["tv", "ios", "mweb"]}}, - "http_headers": UA_HEADERS, -} - - -# --------------------------------------------------------------------------- -# YouTube cookies (bypasses the "Sign in to confirm you're not a bot" block). -# Sources, in priority order: -# 1. YT_COOKIES env var (HF Space secret — raw Netscape-format cookies.txt) -# 2. /app/cookies.txt (a cookies.txt file baked into the repo/runtime) -# yt-dlp reads a Netscape cookies.txt via the 'cookiefile' option. -# --------------------------------------------------------------------------- -_cookie_file = None - - -def _ensure_cookies(): - """Materialise a cookies.txt (Netscape format) for yt-dlp if any cookie - source is available. Returns the cookiefile path or None.""" - global _cookie_file - if _cookie_file and os.path.exists(_cookie_file): - return _cookie_file - content = None - # 1. HF Space secret YT_COOKIES (raw cookies.txt content) - secret = os.environ.get("YT_COOKIES", "").strip() - if secret and ("# Netscape" in secret or "#HTTP" in secret or "youtube.com" in secret or "\tTRUE" in secret): - content = secret - # 2. baked-in file - if not content: - for p in ("/app/cookies.txt", "cookies.txt"): - if os.path.exists(p): - content = open(p, encoding="utf-8", errors="ignore").read() - break - if not content: - _cookie_file = None - return None - try: - path = os.path.join(DATA_DIR, "yt_cookies.txt") - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(content) - _cookie_file = path - return path - except Exception: - return None - - -def _ytdlp_opts(): - """YTDLP opts + cookiefile (only when cookies are available).""" - opts = dict(YTDLP_OPTS) - cf = _ensure_cookies() - if cf: - opts["cookiefile"] = cf - # also add "cookiesfrombrowser" fallback? No — datacenter IPs can't read - # a local browser. cookiefile is the reliable path. - return opts - - -def _oembed_probe(url): - """Cheap metadata fallback for TikTok/Facebook/Instagram/YouTube (no direct URL).""" - try: - host = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower() - api = None - if "tiktok" in host: - api = "https://www.tiktok.com/oembed?url=" + urllib_quote(url, safe="") - elif "facebook" in host or "fb.watch" in host: - api = "https://www.facebook.com/plugins/video/oembed.json?url=" + urllib_quote(url, safe="") - elif "youtube.com" in host or "youtu.be" in host: - api = "https://www.youtube.com/oembed?url=" + urllib_quote(url, safe="") + "&format=json" - if not api: - return None - # Facebook oEmbed often times out from datacenter IPs; use a shorter timeout - _timeout = 8 if ("facebook" in host or "fb.watch" in host) else 12 - j = {} - try: - r = requests.get(api, headers=UA_HEADERS, timeout=_timeout) - if r.status_code == 200: - j = r.json() or {} - except Exception: - j = {} - # YouTube: youtube.com/oembed is often SNI-blocked from datacenter IPs. - # Fall back to _yt_meta (noembed.com cascade) which reliably returns - # title+thumbnail+description from restricted networks. - yt_meta = None - if "youtube.com" in host or "youtu.be" in host: - yt_meta = _yt_meta(url) - title = ((j.get("title") or "") or (yt_meta or {}).get("title") or "").strip()[:200] - thumb = ((j.get("thumbnail_url") or "") or (yt_meta or {}).get("thumbnail") or "").strip() - desc = (yt_meta or {}).get("description") or "" - if "youtube.com" in host or "youtu.be" in host: - if not desc: - desc = (yt_meta or {}).get("description") or "" - embed_url = _oembed_embed_url(url) - # oEmbed providers (notably TikTok short links like vm.tiktok.com) don't - # expose the video ID in the URL, but the `html` field contains the - # canonical `:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',postId:'',extraBtn:``})});h+='';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -async function openYTShortsFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đã xóa Shorts Dân trí/SKĐS
';} -async function openShortAIFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');if(!_wallPosts||!_wallPosts.length){el.innerHTML='
Không có Short AI
';return}const aiPosts=_wallPosts.filter(p=>p.video);if(!aiPosts.length||idx>=aiPosts.length){el.innerHTML='
Không có Short AI
';return}const ordered=aiPosts.slice(idx).concat(aiPosts.slice(0,idx));let h=`
`;ordered.forEach((p,i)=>{const baseIdx=_wallPosts.indexOf(p);const vtag=p.video?``:'';h+=buildTikTokSlide({vtag,title:p.title,badge:'Short AI',badgeClass:'badge-ai',videoId:p.id||'ai-'+i,idx:i,total:ordered.length,shareUrl:p.video||'',postId:p.id||'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -function readWallPost(idx){const p=_wallPosts&&_wallPosts[idx];if(!p)return;if(p.slides&&p.slides.length){readSlidePost(idx);return}readArticle(p.url||'','','',p.title,p.text);} -/** Show rewrite slide viewer - vertical slides with text+image */ -function readSlidePost(idx){const p=_wallPosts[idx];if(!p||!p.slides)return;showView('view-article');const el=document.getElementById('view-article');let h=`
`;p.slides.forEach((s,i)=>{h+=`
Slide ${s.index||i+1}/${p.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
`;el.innerHTML=h;} - -/** Slide Designer Modal - design a slide image with high-contrast text on background */ -function designerGetRatio(){const v=document.getElementById('designer-ratio')?.value||'3:4';const m=v.split(':');return m.length===2?{w:parseInt(m[0]),h:parseInt(m[1])}:1;} -function designerGetLayout(){return document.getElementById('designer-layout')?.value||'solid';} -function designerDebounce(fn,d){clearTimeout(fn._t);fn._t=setTimeout(fn,d);} -function openSlideDesigner(idx){ - designerSlideIdx=idx; - const p=_wallPosts[idx];if(!p||!p.slides)return; - const overlay=document.createElement('div');overlay.id='slide-designer-overlay';overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00'].forEach(c=>{h+=``;}); - h+='
'; - h+='
'; - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h;document.body.appendChild(overlay); - document.getElementById('designer-slide-select').addEventListener('change',function(){updateDesignerText(this.value);previewDesignerSlide();}); - document.getElementById('designer-preview-btn').addEventListener('click',function(){previewDesignerSlide();}); - document.getElementById('designer-save-btn').addEventListener('click',function(){saveDesignerSlide(p.title,(p.id||''),idx);}); - ['change','input'].forEach(function(evt){ - const txt=document.getElementById('designer-text');if(txt)txt.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const bg=document.getElementById('designer-bg-url');if(bg)bg.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const ratio=document.getElementById('designer-ratio');if(ratio)ratio.addEventListener(evt,function(){previewDesignerSlide();}); - const layout=document.getElementById('designer-layout');if(layout)layout.addEventListener(evt,function(){previewDesignerSlide();}); - }); - previewDesignerSlide(); -} -function updateDesignerText(slideIdx){const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return;const s=p.slides[parseInt(slideIdx)];if(s)document.getElementById('designer-text').value=s.text||'';document.getElementById('designer-bg-url').value=s.image||p.img||'';designerBgDataUrl=null;} -function handleDesignerBgFile(input){ - const file=input.files&&input.files[0];if(!file)return; - const reader=new FileReader(); - reader.onload=function(e){designerBgDataUrl=e.target.result;document.getElementById('designer-bg-url').value='[uploaded]';}; - reader.readAsDataURL(file); -} -function previewDesignerSlide(){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const previewArea=document.getElementById('designer-preview-area');if(!previewArea)return; - previewArea.style.display='block';previewArea.innerHTML='
⏳ Đang tạo xem trưởng...
'; - const canvas=document.createElement('canvas'); - const vw=Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540); - const maxW=Math.min(540, Math.floor(vw*0.9)); - canvas.width=maxW;canvas.height=Math.round(maxW*ratio.h/ratio.w); - canvas.style.maxWidth='100%';canvas.style.width='100%';canvas.style.height='auto'; - canvas.style.borderRadius='12px';canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; - canvas.style.display='block';canvas.style.margin='0 auto'; - const ctx=canvas.getContext('2d');const img=new Image();img.crossOrigin='anonymous'; - function drawLayout(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(canvas.width/2,canvas.height/2,0,canvas.width/2,canvas.height/2,Math.max(canvas.width,canvas.height)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,canvas.width,canvas.height);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,canvas.width,canvas.height/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,canvas.height/2,canvas.width,canvas.height/2);} - else if(layout==='spotlight'){const cx=canvas.width/2,cy=canvas.height/2,r=Math.max(canvas.width,canvas.height)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(canvas.width,0);ctx.lineTo(0,canvas.height);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);} - } - function drawText(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(canvas.width*28/540)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(canvas.width*0.82); - const words=text.split(' ');let line='';let y=Math.round(canvas.height/2); - const fontSize=Math.round(canvas.width*28/540);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),canvas.width/2,y);y+=lineHeight;line=words[i];}else{line=test;}} - ctx.fillText(line.trim(),canvas.width/2,y); - } - function renderAll(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,canvas.width,canvas.height); - drawLayout(); - drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(canvas.width/iw,canvas.height/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(canvas.width-dw)/2,dy=(canvas.height-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayout();drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - }; - img.onerror=function(){renderAll();}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{renderAll();} -} -async function saveDesignerSlide(title,postId,idx){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[idx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const statusEl=document.getElementById('designer-status');if(statusEl)statusEl.textContent='⏳ Đang tạo ảnh...'; - const FINAL_W=ratio.w>=ratio.h?1800:1350; - const FINAL_H=Math.round(FINAL_W*ratio.h/ratio.w); - const canvas=document.createElement('canvas');canvas.width=FINAL_W;canvas.height=FINAL_H; - const ctx=canvas.getContext('2d'); - const img=new Image();img.crossOrigin='anonymous'; - function drawLayoutF(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(FINAL_W/2,FINAL_H/2,0,FINAL_W/2,FINAL_H/2,Math.max(FINAL_W,FINAL_H)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,FINAL_W,FINAL_H);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,FINAL_W,FINAL_H/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,FINAL_H/2,FINAL_W,FINAL_H/2);} - else if(layout==='spotlight'){const cx=FINAL_W/2,cy=FINAL_H/2,r=Math.max(FINAL_W,FINAL_H)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(FINAL_W,0);ctx.lineTo(0,FINAL_H);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);} - } - function drawTextF(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(FINAL_W*48/1080)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(FINAL_W*0.82);const words=text.split(' ');let line='';let y=Math.round(FINAL_H/2); - const fontSize=Math.round(FINAL_W*48/1080);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),FINAL_W/2,y);y+=lineHeight;line=words[i];}else{line=test;}}ctx.fillText(line.trim(),FINAL_W/2,y); - } - function render(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(FINAL_W/iw,FINAL_H/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(FINAL_W-dw)/2,dy=(FINAL_H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - }; - img.onerror=function(){if(statusEl)statusEl.textContent='⚠️ Không tải được ảnh nền, dùng nền mặc định';ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H);drawLayoutF();drawTextF();canvas.toBlob(function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - fetch('/api/wall/img',{method:'POST',body:formData}).then(r=>r.json()).then(j=>{ - if(j.ok){s.image=j.url;const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}).then(r=>r.json()).then(wj=>{if(wj.post)prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');document.getElementById('slide-designer-overlay').remove();});} - }).catch(e=>{if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);}); - },'image/png');}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{render();} -} - -function readNewsTab(tab){loadNewsTab();} -function loadNewsTab(){const el=document.getElementById('view-cat');if(!el)return;el.innerHTML='
Đang tải tin tức...
';fetch('/api/homepage').then(r=>r.json()).then(articles=>{if(!articles||!articles.length){el.innerHTML='
Không có tin
';return}let h='
';articles.forEach(a=>{const src=a.source||'vne';const badge=a.group||a.source||'';h+=`
${a.img?``:''}
${esc(badge)}
${esc(a.title)}
`;});h+='
';el.innerHTML=h;}).catch(()=>{el.innerHTML='
Lỗi tải
';});} - -function readArticle(url,title,img,presetTitle,presetText){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';if(presetTitle){el.innerHTML=`

${esc(presetTitle)}

${presetText?`
${esc(presetText)}
`:''}
`;return;}if(!url)return;fetch('/api/article?url='+encodeURIComponent(url)).then(r=>r.json()).then(d=>{let h=`
`;if(d.title)h+=`

${esc(d.title)}

`;if(d.summary)h+=`
${esc(d.summary)}
`;if(d.body)d.body.forEach(b=>{if(b.type==='p')h+=`

${esc(b.text)}

`;else if(b.type==='heading')h+=`

${esc(b.text)}

`;else if(b.type==='img'&&b.src)h+=``;});h+=`
`;el.innerHTML=h;}).catch(()=>{el.innerHTML=`

Không thể tải bài viết

`;});} -async function rewriteSlide(url){if(!url)return;const btn=document.querySelector('.article-actions .primary')||event?.target;if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo slides...';}toast('⏳ Đang tạo slide rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã tạo slide! Đang tạo Short AI...');if(btn)btn.textContent='✅ Đang tạo Short AI...';if(j.post){j.post.slides=j.slides||[];prependWallPost(j.post);}// Show slides immediately if available -if(j.slides && j.slides.length){showView('view-article');const el=document.getElementById('view-article');let h=`
`;j.slides.forEach(s=>{h+=`
Slide ${s.index}/${j.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
⏳ Đang tạo video Short AI...
`;el.innerHTML=h;} -const postId=j.post&&j.post.id;if(postId){setTimeout(async()=>{const sr=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'vi-VN-HoaiMyNeural',emotion:'neutral',speed:1.2})});const sj=await sr.json();if(sr.ok&&sj.video&&typeof _wallPosts!=='undefined'){const p=_wallPosts.find(x=>String(x.id)===String(postId));if(p){p.video=sj.video;const itemId='wall-item-'+postId;const el2=document.getElementById(itemId);if(el2){const idx=_wallPosts.indexOf(p);el2.insertAdjacentHTML('afterend',makeWallItem(p,idx));el2.remove();}}toast('✅ Short AI đã sẵn sàng!');const statusEl=document.getElementById('short-ai-status');if(statusEl)statusEl.innerHTML='✅ Short AI đẵn sàng! ';}},500);}if(btn)btn.textContent='✅ Hoàn tất';}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Slide Rewrite AI';}}} - -function downloadVideo(url, title){ - var a = document.createElement('a'); - a.href = url; - a.download = (title||'video').toString().replace(/[^a-zA-Z0-9_\-\p{L}]/gu,'_').substring(0,60)+'.mp4'; - a.target = '_blank'; - a.rel = 'noopener'; - a.style.display = 'none'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - toast('📥 Đang tải video xuống...'); -} - -// ===== PERSONAL OPINION POST: Viết bài dựa trên quan điểm cá nhân + tin HOT ===== -async function openPersonalPostPreview() { - const opinion = document.getElementById('opinion-input')?.value.trim(); - if (!opinion || opinion.length < 10) { - alert('Vui lòng nhập quan điểm cá nhân (ít nhất 10 ký tự)'); - return; - } - - // Get selected hot topics from UI (if any) - const selectedTopics = []; - if (window._htTopic) { - selectedTopics.push(window._htTopic); - } - - // Get selected sources from hashtag view - const selectedSources = []; - document.querySelectorAll('.hashtag-src-item.selected').forEach(el => { - const idx = parseInt(el.dataset.idx || '0'); - // Would need source tracking - }); - - const btn = event?.target; - const origText = btn ? btn.textContent : ''; - if (btn) { btn.disabled = true; btn.textContent = '⏳ Đang tạo preview...'; } - - try { - const resp = await fetch('/api/personal_post/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: opinion, - selected_topics: selectedTopics, - selected_sources: selectedSources - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi tạo preview'); - - showPersonalPostModal(data.preview, opinion, selectedTopics, selectedSources); - } catch (e) { - toast('❌ ' + e.message); - } finally { - if (btn) { btn.disabled = false; btn.textContent = origText; } - } -} - -function showPersonalPostModal(preview, originalOpinion, selectedTopics, selectedSources) { - // Remove existing modal - const existing = document.getElementById('personal-post-modal'); - if (existing) existing.remove(); - - const modal = document.createElement('div'); - modal.id = 'personal-post-modal'; - modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - - // Each slide renders EXACTLY like the designer's final PNG (same ratio, - // same bg draw, same text draw) — preview = pixel-identical to wall post image. - const slidesHtml = (preview.slides || []).map((s, i) => { - const ratio = {w:3, h:4}; // preview always 3:4 (same as designer final) - const slideStyle = 'width:100%;max-width:280px;margin:0 auto;display:block;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.5)'; - return '
' - + '
Slide ' + (i+1) + '
' - + '' - + '' - + '
'; - }).join(''); - - // Background image source: uploaded data-URL (set later) or slide.image / first source image. - // We keep a small state object so text edits re-render live. - window._pvState = { slides: (preview.slides||[]).map(function(s,i){ - var bg = s.image || (preview.images && preview.images[0]) || ''; - return { text: s.text||'', bg: bg }; - }), ratio: 3/4, layout: 'solid', filter: 'none', glow: 'white', pos: 'bottom', color: '#ffffff' }; - - const sourcesHtml = (preview.sources || []).map((s, i) => { - const imgSrc = (preview.images && preview.images[i+1]) ? preview.images[i+1] : ''; - return '
' - + '
' - + (imgSrc ? '' : '') - + '
' - + '
' + (s.title || '') + '
' - + '' - + '
'; - }).join(''); - - modal.innerHTML = '
' - + '
' - + '

📝 Xem trước bài quan điểm cá nhân

' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '
' - + '' - + '' - + '
' - + '
' + slidesHtml + '
' - + '
' - + '
' - + '' - + '
' - + (sourcesHtml || '
Không có nguồn tin
') - + '
' - + '
' - + '' - + '' - + '
'; - - document.body.appendChild(modal); - - // draw every slide preview canvas - previewRedrawAllSlides(); - - // text edits re-render live - modal.querySelectorAll('.preview-slide-text').forEach(ta => { - ta.addEventListener('input', function(){ - const idx = parseInt(this.dataset.idx || '0', 10); - if(window._pvState && window._pvState.slides[idx]) window._pvState.slides[idx].text = this.value; - previewDrawSlide(idx); - }); - }); - - // Store preview data for publishing - window._personalPostPreview = preview; - window._personalPostOpinion = originalOpinion; -} - -/* Live-edit slide preview canvas (exact same rendering style as designer output) */ -function previewDrawSlide(idx){ - const canvas = document.querySelector('.preview-slide-canvas[data-idx="'+idx+'"]'); - if(!canvas || !window._pvState) return; - const st = window._pvState.slides[idx]; - if(!st) return; - const W = 600, H = Math.round(W * window._pvState.ratio); // 3:4 -> 800 - canvas.width = W; canvas.height = H; - const ctx = canvas.getContext('2d'); - const opts = { text: st.text, pos: window._pvState.pos, glow: window._pvState.glow, - color: window._pvState.color, layout: window._pvState.layout, - filter: window._pvState.filter, bgUrl: st.bg }; - function draw(img){ - // base dark - ctx.fillStyle='#141414'; ctx.fillRect(0,0,W,H); - if(img){ - ctx.save(); - let f=''; - if(opts.filter==='grayscale') f='grayscale(1)'; - else if(opts.filter==='sepia') f='sepia(0.85)'; - else if(opts.filter==='saturate') f='saturate(2.4)'; - else if(opts.filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(opts.filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(opts.filter==='invert') f='invert(1)'; - else if(opts.filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - ctx.drawImage(img,0,0,iw,ih,(W-dw)/2,(H-dh)/2,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // solid overlay like designer - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - drawPreviewText(ctx,W,H,opts); - } - const bgSrc = (typeof _proxyImg==='function') ? _proxyImg(st.bg||'') : (st.bg || ''); - if(bgSrc){ - const im = new Image(); im.crossOrigin='anonymous'; - im.onload = function(){ draw(im); }; - im.onerror = function(){ draw(null); }; - im.src = bgSrc; - } else draw(null); -} -function drawPreviewText(ctx,W,H,opts){ - const text = opts.text || ''; - if(!text.trim()) return; - const fs = Math.min(52, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } - }); - if(line) lines.push(line.trim()); - const lh=Math.round(fs*1.25); - const blockH=lines.length*lh; - let y; - if(opts.pos==='top') y=Math.round(H*0.14)+lh/2; - else if(opts.pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2; - else y=Math.round(H/2)-blockH/2+lh/2; - if(opts.glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); } - else if(opts.glow==='color'){ ctx.shadowColor=opts.color; ctx.shadowBlur=Math.max(10,fs*0.6); } - else if(opts.glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); } - ctx.fillStyle=opts.color; - lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); }); - ctx.shadowBlur=0; -} -function previewRedrawAllSlides(){ - if(!window._pvState) return; - window._pvState.slides.forEach(function(_, i){ previewDrawSlide(i); }); -} -function openPreviewDesigner(){ - // opens the real slide designer on the FIRST preview slide as a background. - // The designer modal already renders canvas + uploads PNGs; we reuse it by - // temporarily creating a wall-post-like object from the preview slides. - if(!window._personalPostPreview || !window._pvState) return; - const slides = window._pvState.slides.map(function(s,i){ - return { text: s.text, image: s.bg, index: i+1 }; - }); - const fakePost = { - id: 'preview-fake', title: document.getElementById('preview-title')?.value || 'Bài quan điểm', - slides: slides, kind: 'personal_opinion', img: slides[0]?.image||'', url: '', video: '' - }; - if(typeof openSlideDesigner === 'function'){ - // designer expects index into _wallPosts; temporarily append so designer works - const existed = _wallPosts && _wallPosts.some(p => p.id === 'preview-fake'); - if(!existed && Array.isArray(_wallPosts)) _wallPosts.unshift(fakePost); - const idx = _wallPosts.findIndex(p => p.id === 'preview-fake'); - openSlideDesigner(idx >= 0 ? idx : 0); - // the fake post is only a designer context; the designer's own save posts - // the designed slides directly to the wall. Remove the fake entry on close. - setTimeout(function(){ - const ov = document.getElementById('slide-designer-overlay'); - if(!ov && Array.isArray(_wallPosts)){ - _wallPosts = _wallPosts.filter(p => p.id !== 'preview-fake'); - } - }, 30000); - } else { - toast('Không có công cụ thiết kế!'); - } -} - -function toggleSourceSelection(el, idx) { - const checkbox = el.querySelector('.source-checkbox'); - checkbox.checked = !checkbox.checked; - el.style.border = checkbox.checked ? '1px solid #2d8659' : '1px solid transparent'; - el.style.background = checkbox.checked ? '#1a2a1f' : '#202020'; -} - -async function publishPersonalPostFromModal() { - const title = document.getElementById('preview-title')?.value.trim(); - if (!title) { - alert('Vui lòng nhập tiêu đề'); - return; - } - - // Collect edited slides (text + designed/bg image from _pvState) - const slides = []; - if (window._pvState && window._pvState.slides) { - window._pvState.slides.forEach((s, i) => { - const text = (s.text || '').trim(); - if (text) slides.push({ text, image: s.bg || '', index: slides.length + 1 }); - }); - } else { - document.querySelectorAll('.preview-slide-text').forEach(ta => { - const text = ta.value.trim(); - if (text) slides.push({ text, image: '', index: slides.length + 1 }); - }); - } - - // Collect selected sources - const sources = []; - document.querySelectorAll('[data-source-idx]').forEach((el, i) => { - const checkbox = el.querySelector('.source-checkbox'); - if (checkbox.checked && window._personalPostPreview?.sources?.[i]) { - sources.push(window._personalPostPreview.sources[i]); - } - }); - - const btn = event.target; - const origText = btn.textContent; - btn.disabled = true; - btn.textContent = '⏳ Đang đăng...'; - - try { - const resp = await fetch('/api/personal_post', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: window._personalPostOpinion, - selected_topics: [], - selected_sources: sources, - custom_title: title, - custom_slides: slides - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi đăng bài'); - - toast('✅ Đã đăng bài quan điểm lên Tường AI!'); - - // Prepend to wall - if (data.post && typeof prependWallPost === 'function') { - prependWallPost(data.post); - } - - // Close modal - document.getElementById('personal-post-modal')?.remove(); - - // Clear opinion input - document.getElementById('opinion-input').value = ''; - } catch (e) { - toast('❌ ' + e.message); - } finally { - btn.disabled = false; - btn.textContent = origText; - } -} - diff --git a/app_v2_entry.py b/app_v2_entry.py index af6bed7af015ed23595fb34226a06875f09935d0..3cb3f338bb5171bdfb005eedd58e9bd25beebd16 100644 --- a/app_v2_entry.py +++ b/app_v2_entry.py @@ -12,12 +12,7 @@ try: except Exception as e: print(f"[WARN] ai_patch import failed: {e}") -try: - import ai_short_v2 # Short AI v2: TikTok music, uploaded audio/video/img, recreate from slides -except Exception as e: - print(f"[WARN] ai_short_v2 import failed: {e}") - -from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response, StreamingResponse +from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response from fastapi.staticfiles import StaticFiles from starlette.routing import Mount from fastapi import Query, Request, UploadFile, File, Form @@ -26,35 +21,16 @@ from bs4 import BeautifulSoup import re, html as html_lib, json, threading, time, uuid from concurrent.futures import ThreadPoolExecutor, as_completed from urllib.parse import quote -import asyncio HL_LEAGUES['friendly'] = {"path": "giai-khac/friendly", "name": "Giao hữu", "emoji": "🤝"} STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static') -SPACE = "https://bep40-vnews.hf.space" # SEO URL base for share links app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)=='/' and hasattr(r,'methods') and 'GET' in getattr(r,'methods',set()))] app.routes[:]=[r for r in app.routes if not isinstance(r, Mount)] app.router.routes=[r for r in app.router.routes if not isinstance(r, Mount)] def _clean(s): return re.sub(r"\s+"," ",html_lib.unescape(str(s or""))).strip() -def _ensure_sentence_complete(text): - """Ensure text ends with complete sentence (ends with . ! or ?). Trim if cut mid-sentence.""" - text = _clean(text) - if not text: - return text - # Find last sentence ending - for end_char in ['.', '!', '?']: - last_pos = text.rfind(end_char) - if last_pos > len(text) * 0.5: # Keep if ending is in latter half - return text[:last_pos + 1].strip() - # If no ending found, try to find last complete sentence - sentences = re.split(r'(?<=[.!?])\s+', text) - complete = [s.strip() for s in sentences if s.strip() and len(s.strip()) > 20] - if complete[:-1]: # Return all but last incomplete - return ' '.join(complete[:-1]) - return text[:150] + '.' if len(text) > 150 else text - # Cache for match details (5 min TTL) _match_cache = {} @@ -231,7 +207,7 @@ _STOP=set('và của các những một được trong với cho tại sau trư def _has_kw(topic,title): tl=topic.lower();tt=(title or'').lower() if tl in tt:return True - words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',tl) if len(w)>2 and w.lower() not in _STOP] + words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',tl) if len(w)>2 and w not in _STOP] if not words:return True return any(w in tt for w in words) @@ -351,7 +327,7 @@ def _search_all(topic,limit=36): if i2 and w.lower() not in _STOP] - if len(words)<2:continue - for n in(3,4,2): - for i in range(max(0,len(words)-n+1)): - phrase=' '.join(words[i:i+n]) - if 8<=len(phrase)<=45:key=phrase.lower();freq[key]=freq.get(key,0)+1;display[key]=phrase + feeds=['https://vnexpress.net/rss/tin-moi-nhat.rss','https://dantri.com.vn/rss/home.rss','https://vietnamnet.vn/rss/tin-moi-nhat.rss','https://thanhnien.vn/rss/home.rss','https://tuoitre.vn/rss/tin-moi-nhat.rss','https://genk.vn/rss','https://vnexpress.net/rss/the-thao.rss','https://thethaovanhoa.vn/rss/tin-nong.rss'] + for feed_url in feeds: + try: + r=req.get(feed_url,headers={'User-Agent':'Mozilla/5.0'},timeout=6);r.encoding='utf-8';soup=BeautifulSoup(r.text,'xml') + for item in soup.find_all('item')[:12]: + title=_clean(item.find('title').get_text() if item.find('title') else '') + if not title:continue + title=re.sub(r'\s*[-|].*$','',title);words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',title) if len(w)>2 and w.lower() not in _STOP] + if len(words)<2:continue + for n in(3,4,2): + for i in range(max(0,len(words)-n+1)): + phrase=' '.join(words[i:i+n]) + if 8<=len(phrase)<=45:key=phrase.lower();freq[key]=freq.get(key,0)+1;display[key]=phrase + except:continue ranked=sorted(freq.items(),key=lambda x:x[1],reverse=True);topics=[];seen=set() for key,count in ranked: is_dup=any(len(set(e.split())&set(key.split()))/max(len(set(e.split())),len(set(key.split())),1)>0.6 for e in seen) @@ -539,206 +500,11 @@ def _ht(topic:str=Query(...),page:int=Query(default=0)): items=_search_all(topic,36);per_page=8;start=page*per_page;end=start+per_page return JSONResponse({'sources':items[start:end],'topic':topic,'page':page,'has_more':end - - - - -{_clean(safe_title)} - - - - - - - -''' - for s in slides: - img_src = s.get('image', '') - if img_src and ('cdnphoto.dantri' in img_src or 'refooty' in img_src or 'vnexpress' in img_src or 'vcdn' in img_src): - img_tag = f'' - else: - img_tag = f'' if img_src else '' - h += f'
Slide {s.get("index",1)}/{len(slides)}
{img_tag}

{_clean(s.get("text",""))}

' - h += '' - return HTMLResponse(h) - -def _render_video_page(post, safe_title, safe_img, safe_url): - video_url = post.get('video', '') - # Use text for description if available - description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026" - - # Build canonical URL preserving original query format if url was provided - if safe_url and safe_url != '/': - canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}" - else: - canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}" - - h = f''' - - - - -{_clean(safe_title)} - - - - - - - - - - -
- -
{_clean(safe_title)}
-
-''' - return HTMLResponse(h) - -@app.get('/s/{slug}') -async def _sh_slug(slug: str, request: Request, url: str = '', title: str = '', img: str = ''): - """SEO-friendly share endpoint with slug in URL path. - Shows slide content when slug matches a wall post ID, otherwise redirects. - """ - safe_title = _clean(title) if title else 'VNEWS - Tin tức' - safe_img = _clean(img) if img else '' - safe_url = _clean(url) if url else '/' - - # Try to find post by slug (post ID) - post = None - try: - if slug and len(slug) > 5: # Likely a post ID - posts = _load_wall_posts() - for p in posts: - if p.get('id') == slug: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - except: - pass - - if post and post.get('slides'): - return _render_slides_page(post, safe_title, safe_img, safe_url) - - if post and post.get('video'): - return _render_video_page(post, safe_title, safe_img, safe_url) - - # Otherwise redirect - return HTMLResponse(f''' - - - - -{_clean(safe_title)} - - - - - - -''') - @app.get('/s') -async def _sh(url:str='',title:str='',img:str='',post_id:str=''): - safe_title = _clean(title) if title else 'VNEWS - Tin tức' - safe_img = _clean(img) if img else '' - safe_url = _clean(url) if url else '/' - - # Try to find wall post by post_id or URL (prioritize posts with slides/video) - post = None - try: - posts = _load_wall_posts() - if post_id: - for p in posts: - if p.get('id') == post_id: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - elif url: - # Find matching URL - prioritize posts with slides or video - for p in posts: - if p.get('url') == url and p.get('slides'): - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - if not post: - # Fallback: find any matching URL - for p in posts: - if p.get('url') == url: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - except: - pass - - if post and post.get('slides'): - return _render_slides_page(post, safe_title, safe_img, safe_url) - - if post and post.get('video'): - return _render_video_page(post, safe_title, safe_img, safe_url) - - # Fallback: redirect to original URL - return HTMLResponse(f''' - - - - -{safe_title} - - - - - - -''') +async def _sh(url:str='',title:str='',img:str=''):return HTMLResponse(f'') from wc2026_scraper import scrape_summary,scrape_fixtures,scrape_standings,scrape_stats,scrape_wc_news,scrape_road_to_wc,get_wc2026_all,scrape_history,scrape_h2h,scrape_lineups,scrape_match_detail @@ -881,273 +647,15 @@ async def _pc(request:Request): def _load_wall_posts(): with _wl_lock: - posts = _lj(WALL_FILE) - if not isinstance(posts, list): - posts = [] - return posts + return _lj(WALL_FILE) def _save_wall_posts(posts): with _wl_lock: _sj(WALL_FILE, posts) -def _post_has_valid_image(p): - """A wall post is considered to have a 'valid' (non-placeholder) image if - at least one of the following is a real, non-placeholder URL: - - p.img (main thumbnail) - - p.short_thumb (generated by Short AI / oEmbed fallback) - - p.images[] (fallback image list) - - p.slides[].image (designed slide images) - - Auto posts that failed metadata enrichment — e.g. pollinations.ai - AI-generated placeholder images, vnexpress logo placeholders, or empty/None - fields — are flagged as having NO valid image so they can be filtered out - of the wall (they show the wrong picture vs the original article).""" - PLACEHOLDER_MARKERS = ( - "pollinations.ai", # AI-generated editorial illustration placeholder - "logo_default.jpg", # vnexpress placeholder logo - "logo.png", - "/logo", - "placeholder", - "no-image", - "blank", - ) - - def _is_placeholder(url): - if not url or not isinstance(url, str): - return True - u = url.strip().lower() - if not u or u.startswith(("about:blank", "data:")): - return True - return any(m in u for m in PLACEHOLDER_MARKERS) - - def _is_real(url): - return bool(url) and not _is_placeholder(url) - - img = p.get("img") - if _is_real(img): - return True - thumb = p.get("short_thumb") - if _is_real(thumb): - return True - images = p.get("images") or [] - if any(_is_real(x) for x in images): - return True - slides = p.get("slides") or [] - if any(_is_real(s.get("image")) for s in slides if isinstance(s, dict)): - return True - return False - -def _post_has_slide_info(p): - """True if the post has usable slide/rewrite AI content: - - designed slides with text+image, OR - - a generated short video (/api/ai/short-file/) with a real thumbnail, OR - - an oEmbed iframe (YouTube/TikTok/Facebook embed) with a real thumbnail - (Short HOT fallback case — embeddable, viewable as a slide).""" - slides = p.get("slides") or [] - if any((s.get("image") or "").strip() and (s.get("text") or "").strip() for s in slides if isinstance(s, dict)): - return True - # Generated short video with a real thumbnail - vid = (p.get("video") or "").strip() - if vid and "api/ai/short-file/" in vid and (p.get("short_thumb") or "").strip(): - return True - # oEmbed iframe (YouTube/TikTok/FB) with a valid image -> viewable embed slide - if vid and ("youtube.com/embed" in vid or "tiktok.com/embed" in vid or - "facebook.com/plugins" in vid or "instagram.com" in vid or - "twitter.com" in vid or "x.com" in vid or "player.vimeo" in vid): - if _post_has_valid_image(p): - return True - return False - -def _is_auto_post(p): - """Auto-generated wall posts: Short HOT, oEmbed fallback, FPT auto, - slide-rewrite AI (auto_rewrite), topic auto-summary (topic_article), or - posts with no meaningful source / created by the AI pipeline.""" - kind = (p.get("kind") or "").strip().lower() - source = (p.get("source") or "").strip().lower() - return kind in ("hot_short", "slide_summary", "auto_rewrite", "topic_article", "summary") or \ - source in ("hot_short", "fptplay", "ai", "auto_rewrite", "topic_article") - -def _created_ts(p): - """Best-effort creation timestamp. Posts created by the AI pipeline often - store `created` as a millisecond epoch; some older posts (auto_rewrite) - omit it and instead embed the timestamp in the `id` (Unix ms). Fall back - to 0 so sorting never crashes.""" - for field in ("created", "ts"): - v = p.get(field) - if v is not None: - try: - return int(v) - except (ValueError, TypeError): - pass - # try to derive from id (numeric prefix = Unix ms timestamp) - pid = str(p.get("id", "")).strip() - if pid.isdigit() and len(pid) >= 12: - try: - return int(pid) - except (ValueError, TypeError): - pass - return 0 - -def _wall_posts_for_view(): - """Apply the user-facing wall filtering + sorting: - 1) Hide auto-generated posts that have a wrong/placeholder image (no - valid image at all — pollinations.ai, vnexpress logo, empty) or have - no slide-AI content (no slides / no short-video / no embed). These - are the 'bài đăng tự động bị sai ảnh / ko có thông tin slide AI' that - don't match the original article. This filter is VIEW-ONLY — it does - NOT delete from the persistent store. - 2) Sort newest-first by creation timestamp, mixing all sources (FPT, - slide rewrite AI, etc.) without source separation.""" - posts = _load_wall_posts() - if not posts: - return [] - filtered = [] - for p in posts: - if not isinstance(p, dict): - continue - if _is_auto_post(p) and not (_post_has_valid_image(p) and _post_has_slide_info(p)): - # auto post with a wrong/placeholder/missing image or no slide AI - # content -> hide from the wall (non-destructive) - continue - filtered.append(p) - filtered.sort(key=_created_ts, reverse=True) - return filtered - -@app.get("/api/ai/wall") -def api_ai_wall(): - return JSONResponse({"posts": _wall_posts_for_view()}) - - -# ===== YOUTUBE RSS FEED PROXY (avoids browser CORS) ===== -_YT_FEED_CACHE = {} -_YT_FEED_TTL = 600 # 10 minutes - - -def _fetch_youtube_rss_feed(channel_id: str = "UC4LvrpNXujjbGOS4RDvr41g"): - """Fetch & parse the YouTube RSS feed server-side. - - The browser cannot reach youtube.com directly (CORS / network block). - We try two sources in order: - 1) Direct feed XML (works if the server has outbound YouTube access) - 2) rss2json.com proxy (always works — it fetches the feed server-side) - Cached for _YT_FEED_TTL seconds.""" - now = time.time() - cached = _YT_FEED_CACHE.get(channel_id) - if cached and now - cached.get('_ts', 0) < _YT_FEED_TTL: - return cached.get('videos', []) - out = [] - try: - # Attempt 1: direct YouTube RSS - feed_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}" - try: - r = req.get(feed_url, headers=HEADERS, timeout=10) - if r.status_code == 200 and r.text.strip(): - soup = BeautifulSoup(r.text, 'xml') - for e in soup.find_all('entry'): - out.extend(_parse_yt_entry(e)) - except Exception as ex2: - print(f"[yt-feed] direct fetch failed, trying rss2json: {ex2}") - # Attempt 2: rss2json proxy (fallback / always) - if not out: - rss2json_url = f"https://api.rss2json.com/v1/api.json?rss_url={feed_url}" - r2 = req.get(rss2json_url, headers=HEADERS, timeout=15) - if r2.status_code == 200: - data = r2.json() - if data.get('status') == 'ok': - for item in data.get('items', []): - vid_m = re.search(r'([a-zA-Z0-9_-]{11})', item.get('id', '')) - if not vid_m: - continue - vid = vid_m.group(1) - title = item.get('title', 'Video') or 'Video' - # prefer the youtube watch URL, fallback to item link - link = item.get('link', '') - if '/watch' not in link: - link = f'https://www.youtube.com/watch?v={vid}' - # thumbnail: prefer media:thumbnail, fallback to youtube hqdefault - thumb = item.get('thumbnail', f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg') - published = item.get('pubDate', '') - out.append({ - 'id': 'yt-' + vid, - 'videoId': vid, - 'title': title.strip()[:200], - 'link': link, - 'img': thumb, - 'published': published, - 'source': 'yt-feed' - }) - if out: - _YT_FEED_CACHE[channel_id] = {'_ts': now, 'videos': out} - return out - except Exception as ex: - print(f"[yt-feed] server error: {ex}") - return [] - - -def _parse_yt_entry(e): - """Parse a single YouTube RSS element into a video dict.""" - out = [] - try: - id_el = e.find('id') - if not id_el: - return out - vid_m = re.search(r'([a-zA-Z0-9_-]{11})', id_el.get_text('')) - if not vid_m: - return out - vid = vid_m.group(1) - title_el = e.find('title') - title = title_el.get_text('') if title_el else 'Video' - link_el = e.find('link', {'rel': 'alternate'}) - link = link_el.get('href') if link_el else f'https://www.youtube.com/watch?v={vid}' - pub_el = e.find('published') - published = pub_el.get_text('') if pub_el else '' - ns = {'media': 'http://search.yahoo.com/mrss/'} - thumb_el = e.find('media:thumbnail', ns) - thumb_url = thumb_el.get('url') if thumb_el else f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg' - out.append({ - 'id': 'yt-' + vid, - 'videoId': vid, - 'title': title.strip()[:200], - 'link': link, - 'img': thumb_url, - 'published': published, - 'source': 'yt-feed' - }) - except Exception as ex: - print(f"[yt-feed] parse entry error: {ex}") - return out - - -@app.get("/api/yt/feed") -def api_yt_feed(channel_id: str = Query(default="UC4LvrpNXujjbGOS4RDvr41g")): - """Server-side YouTube RSS feed fetcher — avoids browser CORS. - Returns parsed feed videos as JSON for the Tường AI wall.""" - videos = _fetch_youtube_rss_feed(channel_id) - return JSONResponse({"videos": videos, "count": len(videos)}) -@app.post("/api/ai/short/{post_id}") -def api_ai_short(post_id: str): - """Generate a short video for a wall post. - Returns clear JSON error when video not available yet. - """ - post_id_s = str(post_id) - posts = _load_wall_posts() - if not isinstance(posts, list): - posts = [] - post = None - for p in posts: - pid = str(p.get("id", "")) - if pid == post_id_s or pid.startswith(post_id_s): - post = p - break - if not post: - return JSONResponse({"error": "Không tìm thấy bài viết", "post_id": post_id}, status_code=404) - if post.get("video"): - return JSONResponse({"video": post["video"], "post": post}) - return JSONResponse({"error": "Chưa có video cho bài này. Vui lòng upload video trước."}, status_code=409) - @app.get('/api/wall') def api_wall(): - posts = _wall_posts_for_view() + posts = _load_wall_posts() if not posts: return JSONResponse({"posts": []}) return JSONResponse({"posts": posts}) @@ -1215,66 +723,22 @@ async def api_wall_post(request: Request): text = body.get('text', '') or '' img = body.get('img', None) source = body.get('source', 'user') or 'user' - incoming_id = body.get('id') or '' # allow client to (re)publish an existing post by id post_id = str(uuid.uuid4())[:12] - # Preserve slide-design post fields (slides, kind, url, images, video, voice, etc.) - # so that "Thiết kế ảnh" -> "Đăng lên Tường AI" keeps the selected slides. - slides = body.get('slides') - kind = body.get('kind') or 'user' - post_url = body.get('url') or '' - images = body.get('images') or [] - video = body.get('video') - voice = body.get('voice') or '' - emotion = body.get('emotion') or '' - language = body.get('language') or '' post = { "id": post_id, "title": title[:200], "text": text[:2000], "source": source, - "video": video, + "video": None, "img": img, - "images": images[:10], - "url": post_url, - "kind": kind, - "slides": slides if slides is not None else None, - "voice": voice, - "emotion": emotion, - "language": language, + "images": [], "created": int(time.time()), "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()), } - # Remove keys with None so the JSON stays lean (but keep structure) - post = {k: v for k, v in post.items() if v is not None} posts = _load_wall_posts() if not isinstance(posts, list): posts = [] - # If the client re-publishes (e.g. designer "Lưu & Đăng lên Tường AI" sends - # the original post id), update that post in place instead of creating a - # duplicate. This keeps the homepage wall clean (no duplicate slide posts). - updated = False - if incoming_id: - for _p in posts: - if str(_p.get('id')) == str(incoming_id): - # Merge new fields into the existing post, but PRESERVE the - # original id (and created timestamp) so the post identity is - # stable and no duplicate is created. - preserve_id = _p.get('id') - preserve_created = _p.get('created') - preserve_created_str = _p.get('created_str') - _p.update(post) - _p['id'] = preserve_id - if preserve_created is not None: _p['created'] = preserve_created - if preserve_created_str is not None: _p['created_str'] = preserve_created_str - updated = True - post = _p # return the merged post (with stable id) to the client - break - if not updated: - posts.insert(0, post) - else: - # Move the updated post to the top so it re-appears at the top of the wall. - posts = [p for p in posts if str(p.get('id')) != str(incoming_id)] - posts.insert(0, post) + posts.insert(0, post) posts = posts[:200] _save_wall_posts(posts) return JSONResponse({"post": post, "ok": True}) @@ -1290,57 +754,6 @@ def api_wall_video(filename: str): media_type = 'video/mp4' if ext == '.mp4' else 'video/webm' return FileResponse(video_path, media_type=media_type) -WALL_IMG_DIR = os.path.join(DATA_DIR, 'wall_imgs') -os.makedirs(WALL_IMG_DIR, exist_ok=True) - -@app.post('/api/wall/img') -async def api_wall_img(request: Request): - """Upload a designed slide image (PNG) and return a served URL.""" - global WALL_IMG_DIR - try: - form = await request.form() - f = form.get('file') - if not f or not hasattr(f, 'filename') or not f.filename: - return JSONResponse({"error": "Thiếu file ảnh"}, status_code=400) - ext = os.path.splitext(f.filename)[1].lower() - if ext not in ('.png', '.jpg', '.jpeg', '.webp'): - ext = '.png' - img_id = str(uuid.uuid4())[:12] - fname = f"wallimg_{img_id}{ext}" - fpath = os.path.join(WALL_IMG_DIR, fname) - content = await f.read() - if not content: - return JSONResponse({"error": "File rỗng"}, status_code=400) - if len(content) > 15 * 1024 * 1024: - return JSONResponse({"error": "Ảnh quá lớn (>15MB)"}, status_code=400) - with open(fpath, 'wb') as fh: - fh.write(content) - post_id = (form.get('post_id') or '').strip() - if post_id: - posts = _load_wall_posts() - if isinstance(posts, list): - for p in posts: - if str(p.get('id')) == str(post_id): - p['img'] = f"/api/wall/img/{fname}" - break - _save_wall_posts(posts) - url = f"/api/wall/img/{fname}" - return JSONResponse({"ok": True, "url": url, "img_id": img_id}) - except Exception as e: - return JSONResponse({"error": f"Lỗi upload ảnh: {str(e)[:150]}"}, status_code=500) - - -@app.get('/api/wall/img/{fname}') -def api_wall_img_file(fname: str): - if '..' in fname or '/' in fname: - return Response(status_code=403) - img_path = os.path.join(WALL_IMG_DIR, fname) - if not os.path.exists(img_path): - return Response(status_code=404) - ext = os.path.splitext(fname)[1].lower() - media_type = 'image/png' if ext == '.png' else ('image/jpeg' if ext in ('.jpg', '.jpeg') else 'image/webp') - return FileResponse(img_path, media_type=media_type) - @app.delete('/api/wall/{post_id}') def api_wall_delete(post_id: str): posts = _load_wall_posts() @@ -1358,41 +771,6 @@ def api_wall_delete(post_id: str): return JSONResponse({"ok": True}) return JSONResponse({"error": "Post not found"}, status_code=404) -@app.post('/api/wall/cleanup') -def api_wall_cleanup(): - """Permanently remove auto-generated wall posts that are completely - unrecoverable (no valid image, no video, no slides, no embed — i.e. a - post that can never be displayed), and sort the remaining posts - newest-first. Returns the number of removed posts and the new count. - - NOTE: Conservative — auto posts that HAVE a valid image or a video/embed - are preserved (they remain visible at view time via - _wall_posts_for_view). Only use this to purge genuine garbage.""" - posts = _load_wall_posts() - if not isinstance(posts, list): - return JSONResponse({"error": "No posts"}, status_code=404) - before = len(posts) - kept = [] - removed = [] - for p in posts: - if not isinstance(p, dict): - removed.append(str(p)) - continue - if _is_auto_post(p) and not _post_has_valid_image(p) and not _post_has_slide_info(p) and not (p.get("video") or "").strip(): - removed.append(p.get('id', '?')) - else: - kept.append(p) - # sort newest-first - kept.sort(key=_created_ts, reverse=True) - _save_wall_posts(kept) - return JSONResponse({ - "ok": True, - "before": before, - "removed_count": before - len(kept), - "removed_ids": removed, - "after": len(kept), - }) - # ===== LANGUAGE & EMOTION DETECTION ===== import random as _random2 from urllib.parse import quote as _quote2 @@ -1510,142 +888,55 @@ def detect_language_and_emotion(title, text): emotion = detect_emotion(combined, lang) return lang, emotion -# Voice selection based on language and emotion (using MultilingualNeural voices) +# Voice selection based on language and emotion VOICE_BY_LANG_EMOTION = { 'vietnamese': { - 'happy': ('vi-VN-HoaiMyNeural', 'vui'), - 'sad': ('vi-VN-NamMinhNeural', 'buồn'), - 'excited': ('vi-VN-HoaiMyNeural', 'hào hứng'), - 'humorous': ('vi-VN-HoaiMyNeural', 'vui'), - 'serious': ('vi-VN-NamMinhNeural', 'nghiêm túc'), - 'neutral': ('vi-VN-HoaiMyNeural', 'trung_tinh'), + 'happy': ('hoaimy', 'vui'), + 'sad': ('namminh', 'buồn'), + 'excited': ('hoaimy', 'hào hứng'), + 'humorous': ('hoaimy', 'vui'), + 'serious': ('namminh', 'nghiêm túc'), + 'neutral': ('hoaimy', 'trung_tinh'), }, 'portuguese': { - 'happy': ('pt-BR-ThalitaMultilingualNeural', 'feliz'), - 'sad': ('pt-BR-ThalitaMultilingualNeural', 'triste'), - 'excited': ('pt-BR-ThalitaMultilingualNeural', 'animado'), - 'humorous': ('pt-BR-ThalitaMultilingualNeural', 'engraçado'), - 'serious': ('pt-BR-ThalitaMultilingualNeural', 'sério'), - 'neutral': ('pt-BR-ThalitaMultilingualNeural', 'neutro'), + 'happy': ('pt_thalita', 'feliz'), + 'sad': ('thalita', 'triste'), + 'excited': ('pt_francisco', 'animado'), + 'humorous': ('pt_thalita', 'engraçado'), + 'serious': ('thalita', 'sério'), + 'neutral': ('pt_thalita', 'neutro'), }, 'english': { - 'happy': ('en-US-AndrewMultilingualNeural', 'happy'), - 'sad': ('en-AU-WilliamMultilingualNeural', 'sad'), - 'excited': ('en-US-AndrewMultilingualNeural', 'excited'), - 'humorous': ('en-US-AndrewMultilingualNeural', 'funny'), - 'serious': ('en-AU-WilliamMultilingualNeural', 'serious'), - 'neutral': ('en-US-AndrewMultilingualNeural', 'neutral'), + 'happy': ('jenny', 'happy'), + 'sad': ('jenny', 'sad'), + 'excited': ('andrew', 'excited'), + 'humorous': ('jenny', 'funny'), + 'serious': ('andrew', 'serious'), + 'neutral': ('jenny', 'neutral'), }, - 'french': { - 'happy': ('fr-FR-VivienneMultilingualNeural', 'heureux'), - 'sad': ('fr-FR-RemyMultilingualNeural', 'triste'), - 'excited': ('fr-FR-VivienneMultilingualNeural', 'excité'), - 'humorous': ('fr-FR-VivienneMultilingualNeural', 'drôle'), - 'serious': ('fr-FR-RemyMultilingualNeural', 'sérieux'), - 'neutral': ('fr-FR-VivienneMultilingualNeural', 'neutre'), - }, - 'german': { - 'happy': ('de-DE-SeraphinaMultilingualNeural', 'glücklich'), - 'sad': ('de-DE-FlorianMultilingualNeural', 'traurig'), - 'excited': ('de-DE-SeraphinaMultilingualNeural', 'aufgeregt'), - 'humorous': ('de-DE-SeraphinaMultilingualNeural', 'lustig'), - 'serious': ('de-DE-FlorianMultilingualNeural', 'ernst'), - 'neutral': ('de-DE-SeraphinaMultilingualNeural', 'neutral'), - }, - 'korean': { - 'happy': ('ko-KR-HyunsuMultilingualNeural', '행복'), - 'sad': ('ko-KR-HyunsuMultilingualNeural', '슬픔'), - 'excited': ('ko-KR-HyunsuMultilingualNeural', '흥분'), - 'humorous': ('ko-KR-HyunsuMultilingualNeural', '유쾌'), - 'serious': ('ko-KR-HyunsuMultilingualNeural', '진지'), - 'neutral': ('ko-KR-HyunsuMultilingualNeural', '중립'), - }, - 'italian': { - 'happy': ('it-IT-GiuseppeMultilingualNeural', 'felice'), - 'sad': ('it-IT-GiuseppeMultilingualNeural', 'triste'), - 'excited': ('it-IT-GiuseppeMultilingualNeural', 'emozionato'), - 'humorous': ('it-IT-GiuseppeMultilingualNeural', 'divertente'), - 'serious': ('it-IT-GiuseppeMultilingualNeural', 'serio'), - 'neutral': ('it-IT-GiuseppeMultilingualNeural', 'neutro'), + 'spanish': { + 'happy': ('ela', 'feliz'), + 'sad': ('es_carlos', 'triste'), + 'excited': ('ela', 'emocionado'), + 'humorous': ('ela', 'gracioso'), + 'serious': ('es_carlos', 'serio'), + 'neutral': ('ela', 'neutro'), }, } -# All valid voice IDs (new MultilingualNeural format) -VALID_VOICES = { - 'vi-VN-HoaiMyNeural', 'vi-VN-NamMinhNeural', - 'en-US-AndrewMultilingualNeural', 'en-AU-WilliamMultilingualNeural', - 'pt-BR-ThalitaMultilingualNeural', - 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural', - 'de-DE-SeraphinaMultilingualNeural', 'de-DE-FlorianMultilingualNeural', - 'ko-KR-HyunsuMultilingualNeural', - 'it-IT-GiuseppeMultilingualNeural', -} - def get_voice_for_content(title, text, preferred_voice=None): """Get appropriate voice based on content language and emotion.""" - # Accept the new MultilingualNeural voices directly - if preferred_voice and preferred_voice in VALID_VOICES: + if preferred_voice and preferred_voice in ('hoaimy', 'namminh', 'andrew', 'jenny', 'thalita', 'pt_thalita', 'pt_francisco', 'ela', 'es_carlos', 'denise', 'katja', 'nanami', 'sunhee', 'xiaochen'): return preferred_voice - # Also accept old shorthand voice IDs and map them to new format - old_voice_map = { - 'hoaimy': 'vi-VN-HoaiMyNeural', - 'namminh': 'vi-VN-NamMinhNeural', - 'andrew': 'en-US-AndrewMultilingualNeural', - 'jenny': 'en-US-AndrewMultilingualNeural', - 'thalita': 'pt-BR-ThalitaMultilingualNeural', - 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural', - 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural', - 'ela': 'en-US-AndrewMultilingualNeural', - 'es_carlos': 'en-US-AndrewMultilingualNeural', - 'denise': 'fr-FR-VivienneMultilingualNeural', - 'katja': 'de-DE-SeraphinaMultilingualNeural', - 'nanami': 'en-US-AndrewMultilingualNeural', - 'sunhee': 'ko-KR-HyunsuMultilingualNeural', - 'xiaochen': 'en-US-AndrewMultilingualNeural', - } - if preferred_voice and preferred_voice in old_voice_map: - return old_voice_map[preferred_voice] - lang, emotion = detect_language_and_emotion(title, text) lang_map = VOICE_BY_LANG_EMOTION.get(lang, VOICE_BY_LANG_EMOTION['vietnamese']) voice, _ = lang_map.get(emotion, lang_map['neutral']) return voice -def _is_relevant_image(img_url, title, text): - """Check if an image is relevant to the article content.""" - if not img_url: - return False - skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif', - 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite', - 'advertisement', 'ad-banner', 'sponsored', 'banner-ads'] - img_lower = img_url.lower() - for p in skip_patterns: - if p in img_lower: - return False - if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']): - return False - return True - - -def _filter_relevant_images(images, title, text, max_images=8): - """Filter and rank images by relevance to article content.""" - if not images: - return [] - seen = set() - relevant = [] - for img in images: - if img in seen: - continue - seen.add(img) - if _is_relevant_image(img, title, text): - relevant.append(img) - return relevant[:max_images] - - def _scrape_article_for_rewrite(url): - """Scrape article: extract title, paragraphs, RELEVANT images, OG image.""" + """Scrape article: extract title, paragraphs, images, OG image.""" try: r = req.get(url, headers=_UA_RW, timeout=15, allow_redirects=True) r.encoding = 'utf-8' @@ -1668,10 +959,10 @@ def _scrape_article_for_rewrite(url): if not block: block = soup.body or soup paragraphs = [] - all_images = [] + images = [] seen_imgs = set() if og_img and og_img not in seen_imgs: - all_images.append(og_img) + images.append(og_img) seen_imgs.add(og_img) for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True): if el.name == 'p': @@ -1686,65 +977,29 @@ def _scrape_article_for_rewrite(url): if src.startswith('//'): src = 'https:' + src if src not in seen_imgs: - all_images.append(src) + images.append(src) seen_imgs.add(src) - # Filter to relevant images only - relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5])) - return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img} + return {'title': _clean(title), 'paragraphs': paragraphs, 'images': images, 'og_img': og_img} except Exception: return None def _extract_key_points_rw(paragraphs, max_points=5): - r"""Extract key points from paragraphs - extracts ALL sentences, not just first one. - - Fixes: Original regex `^(.+?[.!?])\s` only captured first sentence per paragraph. - Now splits on all sentence boundaries and takes valid sentences until max_points. - """ + """Extract key points from paragraphs.""" points = [] - for p in paragraphs: if len(points) >= max_points: break - - p = _clean(p) - if not p: + m = re.match(r'^(.+?[.!?])\s', p) + if m: + sentence = m.group(1) + else: + sentence = p[:150] + ('.' if not p.endswith('.') else '') + if len(sentence) < 30: continue - - # Split paragraph into sentences using Vietnamese + English punctuation - sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p) - sentences = [s.strip() for s in sentences if s.strip()] - - for sentence in sentences: - if len(points) >= max_points: - break - - # Clean sentence - remove extra whitespace - sentence = _clean(sentence) - - if len(sentence) < 30: - continue - - # Check for duplicates - if any(sentence[:60] in existing for existing in points): - continue - - # Ensure sentence ends with punctuation - if not sentence.endswith(('.', '!', '?')): - sentence = sentence + '.' - - points.append(sentence) - - # If no valid sentences found, take chunks from raw text - if not points: - raw = '\n'.join(paragraphs) - for i in range(0, min(len(raw), max_points * 300), 280): - chunk = _clean(raw[i:i+280]) - if len(chunk) >= 30 and chunk not in points: - points.append(chunk + ('.' if not chunk.endswith('.') else '')) - if len(points) >= max_points: - break - + if any(sentence[:50] in existing for existing in points): + continue + points.append(sentence) return points @@ -1754,7 +1009,6 @@ async def api_rewrite_slide(request: Request): body = await request.json() url = _clean(body.get("url", "")) context = body.get("context", "") - preferred_voice = body.get("voice", "") # Accept custom voice selection if not url and not context: return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400) data = None @@ -1765,7 +1019,7 @@ async def api_rewrite_slide(request: Request): data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''} if not data or not data.get('paragraphs'): return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422) - points = _extract_key_points_rw(data['paragraphs'], max_points=12) + points = _extract_key_points_rw(data['paragraphs'], max_points=6) if not points: return JSONResponse({"error": "Không tìm được ý chính"}, status_code=422) images = data.get('images', []) @@ -1779,8 +1033,7 @@ async def api_rewrite_slide(request: Request): # Auto-detect language and emotion lang, emotion = detect_language_and_emotion(data['title'], summary_text) - # Use preferred voice if provided, otherwise auto-detect - voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], summary_text) + voice = get_voice_for_content(data['title'], summary_text) post = { "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), @@ -1809,7 +1062,6 @@ async def api_rewrite_share(request: Request): body = await request.json() url = _clean(body.get("url", "")) ctx = _clean(body.get("context", "")) - preferred_voice = body.get("voice", "") # Accept custom voice selection if not url and not ctx: return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400) data = None @@ -1842,14 +1094,14 @@ async def api_rewrite_share(request: Request): except Exception: pass if not ai_text or len(ai_text) < 80: - key_pts = _extract_key_points_rw(data['paragraphs'], max_points=12) + key_pts = _extract_key_points_rw(data['paragraphs'], max_points=6) if key_pts: ai_text = '\n\n'.join([f"• {p}" for p in key_pts]) else: ai_text = f"Tóm tắt: {data['title']}\n\n{raw_text[:1200]}\n\nNguồn: {domain}" # Build slides from key points (FIX: include slides in rewrite_share too!) - points = _extract_key_points_rw(data['paragraphs'], max_points=12) + points = _extract_key_points_rw(data['paragraphs'], max_points=6) images = data.get('images', []) slides = [] for i, point in enumerate(points): @@ -1860,8 +1112,7 @@ async def api_rewrite_share(request: Request): # Auto-detect language and emotion lang, emotion = detect_language_and_emotion(data['title'], ai_text) - # Use preferred voice if provided, otherwise auto-detect - voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], ai_text) + voice = get_voice_for_content(data['title'], ai_text) post = { "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), @@ -1896,513 +1147,6 @@ async def api_url_wall(request: Request): return await api_rewrite_share(request) -# ===== PERSONAL OPINION POST v2: AI tổng hợp bài viết từ quan điểm + nguồn tin HOT ===== - -# ===== KEYWORD EXTRACTION FROM OPINION ===== -_STOP_WORDS_EX = set(""" -và của các những một được trong với cho tại sau trước khi không người -việt nam hôm nay mới nhất nóng tin tức cập nhật theo từ đến là có thì -này đã để về lại nên cũng rất như vì do nếu sẽ nếu thế nhưng mà vẫn -đang vào ra hơn đây đó nào cả cùng đã từng hãy còn chỉ cũng đều khiến -được đã bị bởi qua những lúc cái gì cô chú bác anh chị em bạn tôi mình -ông bà thầy vì vậy chính phải ấy đấy đâu đó thôi nhé đấy ạ nhỉ -ngày tháng năm giờ phút giây tuần tháng quý -""".strip().split()) - -def _extract_keywords_from_opinion(text, max_keywords=5): - """Extract meaningful keywords from user's opinion for news search.""" - if not text: - return [] - text = text.lower() - text = re.sub(r'https?://\S+', '', text) - text = re.sub(r'[^\w\sÀ-ỹ]', ' ', text) - text = re.sub(r'\s+', ' ', text).strip() - words = [w for w in text.split() if len(w) > 2 and w not in _STOP_WORDS_EX] - word_scores = {} - for w in words: - word_scores[w] = word_scores.get(w, 0) + 1 - sorted_words = sorted(word_scores.items(), key=lambda x: -x[1]) - top_words = [w for w, s in sorted_words[:max_keywords]] - phrases = [] - for i in range(len(words) - 1): - phrase = words[i] + ' ' + words[i + 1] - if len(phrase) > 5: - phrases.append(phrase) - phrase_scores = {} - for p in phrases: - phrase_scores[p] = phrase_scores.get(p, 0) + 1 - sorted_phrases = sorted(phrase_scores.items(), key=lambda x: -x[1]) - top_phrases = [p for p, s in sorted_phrases[:3]] - result = [] - for p in top_phrases: - if p not in result: - result.append(p) - for w in top_words: - if w not in result: - result.append(w) - return result[:max_keywords] - - -@app.post("/api/personal_post/preview") -async def api_personal_post_preview(request: Request): - """Preview personal post: fetch full articles, let AI compose logical article with images.""" - body = await request.json() - opinion = _clean(body.get("opinion", "")) - selected_topics = body.get("selected_topics", []) or [] - selected_sources = body.get("selected_sources", []) or [] - - if not opinion or len(opinion) < 10: - return JSONResponse({"error": "Quan điểm cá nhân quá ngắn (cần ít nhất 10 ký tự)"}, status_code=400) - - # Lấy keywords từ QUAN ĐIỂM CÁ NHÂN để tìm nguồn tin chính xác - keywords = _extract_keywords_from_opinion(opinion, max_keywords=5) - if keywords: - selected_topics = keywords[:3] - else: - # Fallback: hot topics - hot = _get_hot_topics() - selected_topics = [t.get("topic", "") for t in hot[:3] if t.get("topic")] - - # Tìm nguồn tin - all_sources = [] - seen_urls = set() - for topic in selected_topics[:3]: - sources = _search_all(topic, limit=5) - for s in sources: - if s.get("url") and s["url"] not in seen_urls: - seen_urls.add(s["url"]) - all_sources.append(s) - if len(all_sources) >= 6: - break - if len(all_sources) >= 6: - break - - for src in selected_sources: - if src.get("url") and src["url"] not in seen_urls: - all_sources.insert(0, src) - - # Scrape nội dung đầy đủ từng nguồn (paragraphs + images) - source_details = [] - source_images = [] - for src in all_sources[:5]: - url = src.get("url", "") - if not url: - continue - try: - art = _scrape_article_for_rewrite(url) - if art: - src_detail = { - "title": art.get("title", src.get("title", "")), - "url": url, - "via": src.get("via", ""), - "paragraphs": art.get("paragraphs", [])[:8], - "images": art.get("images", [])[:3], - "og_image": art.get("og_img", "") - } - source_details.append(src_detail) - # Collect images for proxy - for img in art.get("images", [])[:2]: - if any(x in img for x in ["cdnphoto.dantri", "vnexpress", "vcdn", "refooty"]): - img = "/api/proxy/img?url=" + _quote2(img, safe="") - source_images.append(img) - except: - pass - if len(source_details) >= 5: - break - - # Tạo title từ opinion - opinion_words = re.findall(r"[A-Za-zÀ-ỹ0-9]+", opinion) - title_words = opinion_words[:8] if len(opinion_words) >= 8 else opinion_words[:4] - title = " ".join([w[0].upper() + w[1:] for w in title_words]) if title_words else "Quan điểm cá nhân" - title = title[:80] - - # AI sinh bài viết hoàn chỉnh - ai_text = None - try: - import ai_ext - if hasattr(ai_ext, 'qwen_generate'): - # Build detailed context from source articles - source_context = "" - for i, sd in enumerate(source_details[:5]): - src_title = sd.get("title", "") - src_via = sd.get("via", "") - src_paras = sd.get("paragraphs", []) - source_context += f"\n=== Nguồn {i+1}: {src_title} ({src_via}) ===\n" - for j, p in enumerate(src_paras[:4]): - source_context += f" - {p[:300]}\n" - - prompt = ( - "QUAN ĐIỂM: " + opinion[:500] + "\nNGUỒN: " + source_context[:1000] + "\n\n" - "=== NGUỒN TIN THAM KHẢO ===\n" + source_context + "\n\n" - "=== YÊU CẦU VIẾT BÀI THEO SLIDE ===\n" - "Viết bài thành 5-6 ĐOẠN VĂN NGẮN, mỗi đoạn là 1 SLIDE.\n" - "\n" - "QUAN TRỌNG NHẤT: MỗI SLIDE PHẢI KẾT HỢP QUAN ĐIỂM CÁ NHÂN + NỘI DUNG NGUỒN TIN, KHÔNG PHẢI CHỈ NÓI VỀ NGUỒN TIN.\n" - "\n" - "SLIDE 1 - MỞ ĐẦU:\n" - "- NHIỆN HỮU QUAN ĐIỂM CÁ NHÂN LÊN ĐẦU\n" - "- Giới thiệu chủ đề, nêu rõ quan điểm của bạn (dựa vào QUAN ĐIỂM CÁ NHÂN ở trên)\n" - "- 2-4 câu hoàn chỉnh\n" - "\n" - "SLIDE 2-3-4-5 - PHÂN TÍCH:\n" - "- Mỗi slide: B�Commencer bằng QUAN ĐIỂM CÁ NHÂN, sau đó dẫn chứng từ 1 nguồn tin\n" - "- Ví dụ: \"Theo quan điểm của tôi, đây là vấn đề cần lưu ý. Theo VnExpress...\"\n" - "- Dẫn chứng từ nguồn (ghi rõ tên báo: Theo VnExpress, Theo Thanh Niên...)\n" - "- 2-4 câu hoàn chỉnh mỗi slide\n" - "\n" - "SLIDE 6 - KẾT LUẬN:\n" - "- Tổng kết quan điểm cá nhân, đưa ra nhận định cuối cùng\n" - "- 2-3 câu hoàn chỉnh\n" - "\n" - "Định dạng đầu ra:\n" - "---SLIDE 1---\n" - "[nội dung đoạn văn slide 1]\n" - "---SLIDE 2---\n" - "[nội dung đoạn văn slide 2]\n" - "...v.v...\n" - "\n" - "QUAN TRỌNG:\n" - "- Mỗi slide là 1 đoạn văn HOÀN CHỈNH, 2-4 câu\n" - "- PHẢI KẾT THÚC BẰNG DẤU CHẤM (.) HOẢN TOÀN\n" - "- Kết hợp QUAN ĐIỂM CÁ NHÂN với NỘI DUNG NGUỒN TIN\n" - "- Không gạch đầu dòng, không bullet points\n" - "- Viết liền mạch tự nhiên, giọng văn báo chí\n" - "- Mỗi slide phải khác nhau, không lặp ý\n" - "- Độ dài: 300-600 từ" - ) - ai_text = None # Không dùng AI, để code tự kết hợp opinion + source - except: - pass - - if not ai_text or len(ai_text) < 100: - # Fallback: build article manually - ai_text = "## " + title + "\n\n" - ai_text += opinion + "\n\n" - for i, sd in enumerate(source_details[:5]): - ai_text += "### " + sd.get("title", f"Nguồn {i+1}") + "\n" - for p in sd.get("paragraphs", [])[:3]: - ai_text += p[:250] + "\n" - ai_text += "*Nguồn: " + sd.get("via", "") + "*\n\n" - ai_text += "\n---\n*Bài viết tổng hợp từ quan điểm cá nhân và các nguồn tin liên quan*" - - # Parse slides từ AI output (format: ---SLIDE N--- content) - slides = [] - if ai_text: - # Try to parse the ---SLIDE--- format - pattern = r'---SLIDE\s*(\d+)---\s*\n(.*?)(?=---SLIDE|\Z)' - matches = re.findall(pattern, ai_text, re.DOTALL) - - if matches: - for idx, (num, content) in enumerate(matches): - # Normalize: ensure complete sentences - text = _ensure_sentence_complete(content) - if len(text) > 40: - img = source_images[idx] if idx < len(source_images) else "" - slides.append({"text": text, "image": img, "index": idx + 1}) - - # If we have parsed slides, ensure minimum 3 - if len(slides) < 3: - # Use parsed slides as base, fill remaining from AI text - used_indices = set() - for s in slides: - used_indices.add(s['index'] - 1) - - # Split remaining AI text into more slides - sentences = re.split(r'(?<=[.!?])\s+', ai_text) - current_chunk = "" - next_idx = len(slides) - - for sent in sentences: - sent = _ensure_sentence_complete(sent) - if len(sent) < 20: - continue - - # Skip if this sentence is already in parsed slides - found = False - for slide in slides: - if sent[:50] in slide['text']: - found = True - break - - if found: - continue - - if current_chunk and len(current_chunk + " " + sent) <= 380: - current_chunk += " " + sent - else: - if len(current_chunk) > 50: - img = source_images[next_idx] if next_idx < len(source_images) else "" - slides.append({"text": current_chunk, "image": img, "index": next_idx + 1}) - current_chunk = sent - next_idx += 1 - - # Add final chunk - if len(current_chunk) > 50 and next_idx < 6: - img = source_images[next_idx] if next_idx < len(source_images) else "" - slides.append({"text": current_chunk, "image": img, "index": next_idx + 1}) - - # Ultimate fallback: create slides from opinion + source - if len(slides) < 2: - slides = [] - # Slide 1: opinion - if opinion and len(opinion) > 20: - slides.append({"text": opinion[:450], "image": source_images[0] if source_images else "", "index": 1}) - - # Slide 2-6: from AI text or sources - if ai_text: - sentences = re.split(r'(?<=[.!?])\s+', ai_text) - for i, sent in enumerate(sentences[:5]): - text = _ensure_sentence_complete(_clean(sent)) - if len(text) > 60: - if len(slides) < 6: - img = source_images[len(slides)] if len(slides) < len(source_images) else "" - slides.append({"text": text, "image": img, "index": len(slides) + 1}) - - # Fill remaining with key points from sources - KẾT HỢP VỚI QUAN ĐIỂM CÁ NHÂN - src_idx = len(slides) - while len(slides) < 4 and src_idx < len(source_details): - paragraphs = source_details[src_idx].get("paragraphs", []) - src_title = source_details[src_idx].get("title", "") - src_via = source_details[src_idx].get("via", "") - for p in paragraphs[:2]: - if len(p) > 60 and len(slides) < 6: - # Kết hợp opinion với nội dung source - combined = f"Theo góc nhìn của tôi, {opinion[:100]}... Theo {src_via}: {p[:250]}" - img = source_images[len(slides)] if len(slides) < len(source_images) else "" - slides.append({"text": _ensure_sentence_complete(combined), "image": img, "index": len(slides) + 1}) - break # Mỗi nguồn 1 slide - src_idx += 1 - - # Final fallback: ensure at least 2-3 slides - while len(slides) < 3: - idx = len(slides) - if idx == 0 and opinion: - slides.append({"text": opinion[:400], "image": "", "index": 1}) - elif ai_text: - slides.append({"text": ai_text[idx*300:(idx+1)*300], "image": "", "index": idx + 1}) - else: - slides.append({"text": f"Nguồn tham khảo {idx + 1}", "image": "", "index": idx + 1}) - - preview = { - "title": title, - "text": ai_text, - "opinion": opinion, - "images": source_images[:10], - "sources": source_details[:5], - "slides": slides[:6] # Max 6 slides - } - - return JSONResponse({"preview": preview}) - - -@app.post("/api/personal_post") -async def api_personal_post(request: Request): - """Create and save personal opinion post.""" - body = await request.json() - opinion = _clean(body.get("opinion", "")) - selected_topics = body.get("selected_topics", []) or [] - selected_sources = body.get("selected_sources", []) or [] - custom_title = body.get("custom_title", "") - custom_slides = body.get("custom_slides", []) - - if not opinion or len(opinion) < 10: - return JSONResponse({"error": "Quan điểm cá nhân quá ngắn (cần ít nhất 10 ký tự)"}, status_code=400) - - if not selected_topics: - # Lấy keywords từ QUAN ĐIỂM CÁ NHÂN để tìm nguồn tin chính xác - keywords = _extract_keywords_from_opinion(opinion, max_keywords=5) - if keywords: - selected_topics = keywords[:3] - else: - hot = _get_hot_topics() - selected_topics = [t.get("topic", "") for t in hot[:3] if t.get("topic")] - - all_sources = [] - seen_urls = set() - for topic in selected_topics[:3]: - sources = _search_all(topic, limit=5) - for s in sources: - if s.get("url") and s["url"] not in seen_urls: - seen_urls.add(s["url"]) - all_sources.append(s) - if len(all_sources) >= 6: - break - if len(all_sources) >= 6: - break - - for src in selected_sources: - if src.get("url") and src["url"] not in seen_urls: - all_sources.insert(0, src) - - source_details = [] - source_images = [] - for src in all_sources[:5]: - url = src.get("url", "") - if not url: - continue - try: - art = _scrape_article_for_rewrite(url) - if art: - src_detail = { - "title": art.get("title", src.get("title", "")), - "url": url, - "via": src.get("via", ""), - "paragraphs": art.get("paragraphs", [])[:6], - "images": art.get("images", [])[:2], - "og_image": art.get("og_img", "") - } - source_details.append(src_detail) - for img in art.get("images", [])[:2]: - if any(x in img for x in ["cdnphoto.dantri", "vnexpress", "vcdn", "refooty"]): - img = "/api/proxy/img?url=" + _quote2(img, safe="") - source_images.append(img) - except: - pass - - # Title - if custom_title: - title = custom_title[:80] - else: - opinion_words = re.findall(r"[A-Za-zÀ-ỹ0-9]+", opinion) - title_words = opinion_words[:8] if len(opinion_words) >= 8 else opinion_words[:4] - title = " ".join([w[0].upper() + w[1:] for w in title_words]) if title_words else "Quan điểm cá nhân" - title = title[:80] - - # AI sinh bài - ai_text = None - try: - import ai_ext - if hasattr(ai_ext, 'qwen_generate'): - source_context = "" - for i, sd in enumerate(source_details[:5]): - src_title = sd.get("title", "") - src_via = sd.get("via", "") - src_paras = sd.get("paragraphs", []) - source_context += f"\nNguồn {i+1}: {src_title} ({src_via})\n" - for j, p in enumerate(src_paras[:3]): - source_context += f" - {p[:300]}\n" - prompt = ( - "QUAN ĐIỂM: " + opinion[:500] + "\nNGUỒN: " + source_context[:1000] + "\n\n" - "=== NGUỒN TIN ===\n" + source_context + "\n\n" - "=== YÊU CẦU VIẾT BÀI THEO SLIDE ===\n" - "Viết bài thành 5-6 ĐOẠN VĂN NGẮN, mỗi đoạn là 1 SLIDE.\n" - "\n" - "SLIDE 1 - MỞ ĐẦU: Giới thiệu chủ đề, nêu quan điểm cá nhân (2-4 câu hoàn chỉnh)\n" - "SLIDE 2-3-4-5 - PHÂN TÍCH: Mỗi slide dùng 1 nguồn tin cụ thể, kết hợp quan điểm cá nhân, ghi rõ nguồn (Theo VnExpress...), 2-4 câu hoàn chỉnh, thành 1 đoạn văn hoàn chỉnh\n" - "SLIDE 6 - KẾT LUẬN: Tổng kết quan điểm, nhận định cuối cùng (2-3 câu hoàn chỉnh)\n" - "\n" - "Định dạng:\n" - "---SLIDE 1---\n[đoạn văn hoàn chỉnh kết thúc bằng dấu chấm]\n---SLIDE 2---\n[đoạn văn hoàn chỉnh kết thúc bằng dấu chấm]\n...\n" - "\n" - "QUAN TRỌNG: Mỗi slide là 1 đoạn văn HOÀN CHỈNH, 2-4 câu, PHẢI KẾT THÚC BẰNG DẤU CHẤM (.). Kết hợp QUAN ĐIỂM + NGUỒN TIN. Không gạch đầu dòng. Viết liền mạch. 300-600 từ." - ) - ai_text = None # Không dùng AI, để code tự kết hợp opinion + source - except: - pass - - if not ai_text or len(ai_text) < 100: - ai_text = "## " + title + "\n\n" + opinion + "\n\n" - for i, sd in enumerate(source_details[:5]): - ai_text += "### " + sd.get("title", "") + "\n" - for p in sd.get("paragraphs", [])[:2]: - ai_text += p[:250] + "\n" - ai_text += "\n---\n*Nguồn: " + sd.get("via", "") + "*\n\n" - - # Tạo slides - if custom_slides and len(custom_slides) > 0: - slides = [] - for i, slide in enumerate(custom_slides): - slides.append({ - "text": slide.get("text", ""), - "image": slide.get("image", ""), - "index": i + 1 - }) - else: - slides = [] - # Parse từ AI output (format: ---SLIDE N---) - if ai_text: - pattern = r'---SLIDE\s*(\d+)---\s*\n(.*?)(?=---SLIDE|\Z)' - matches = re.findall(pattern, ai_text, re.DOTALL) - if matches: - for idx, (num, content) in enumerate(matches): - # Normalize: ensure complete sentences - text = _ensure_sentence_complete(content) - if len(text) > 30: - img = source_images[idx] if idx < len(source_images) else "" - slides.append({"text": text, "image": img, "index": idx + 1}) - - # Fallback: split by paragraphs - if len(slides) < 3: - paragraphs = [p.strip() for p in re.split(r'\n\n+', ai_text) if p.strip()] - slides = [] - para_count = 0 - for p in paragraphs: - p = p.strip() - if p.startswith('#') or p.startswith('---') or p.startswith('*Nguồn'): - continue - # Normalize: ensure complete sentences - p_normalized = _ensure_sentence_complete(p) - if len(p_normalized) > 50: - img = source_images[para_count] if para_count < len(source_images) else "" - slides.append({"text": p_normalized, "image": img, "index": para_count + 1}) - para_count += 1 - if para_count >= 6: - break - - if len(slides) < 2: - slides = [] - # Slide 1: QUAN ĐIỂM CÁ NHÂN (BẮT BUỘC) - slides.append({"text": f"Theo quan điểm cá nhân: {opinion[:400]}", "image": source_images[0] if source_images else "", "index": 1}) - - # Slide 2-6: KẾT HỢP QUAN ĐIỂM + SOURCE - for i in range(min(5, len(source_details))): - if len(slides) >= 6: - break - src = source_details[i] - src_via = src.get("via", "") - src_paras = src.get("paragraphs", []) - - src_text = "" - for p in src_paras[:2]: - p = p.strip()[:280] - if len(p) > 50: - src_text = p - break - - if src_text: - combined = f"Theo góc nhìn cá nhân, {opinion[:60]}. Theo {src_via}: {src_text}" - img = source_images[len(slides)] if len(slides) < len(source_images) else (source_images[-1] if source_images else "") - slides.append({"text": _ensure_sentence_complete(combined), "image": img, "index": len(slides) + 1}) - - lang, emotion = detect_language_and_emotion(title, ai_text) - voice = get_voice_for_content(title, ai_text) - - post = { - "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), - "title": title, - "text": ai_text, - "img": source_images[0] if source_images else "", - "url": "", - "kind": "personal_opinion", - "slides": slides, - "images": source_images[:10], - "video": "", - "voice": voice, - "emotion": emotion, - "language": lang, - "ts": int(time.time()), - "sources": source_details[:5] - } - - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - - return JSONResponse({"post": post, "slides": slides}) - - -# ===== END PERSONAL OPINION POST v2 ===== - def _bg(): time.sleep(15) while True: @@ -2411,689 +1155,4 @@ def _bg(): time.sleep(90) threading.Thread(target=_bg,daemon=True).start() -# ===== AUTO SCHEDULER: rewrite AI + short at 7/13/19 VN time ===== -_AUTO_SCHEDULE_TIMES = [(7, '07:00'), (13, '13:00'), (19, '19:00')] -_AUTO_LOG = os.path.join(DATA_DIR, 'auto_rewrite_log.json') - -def _load_auto_log(): - try: - if os.path.exists(_AUTO_LOG): - with open(_AUTO_LOG, 'r') as f: - return json.load(f) - except: pass - return {} - -def _save_auto_log(log): - try: - tmp = _AUTO_LOG + '.tmp' - with open(tmp, 'w') as f: - json.dump(log, f) - os.replace(tmp, _AUTO_LOG) - except: pass - -async def _auto_fetch_short(post_id): - """Try to auto-generate a short for a post.""" - try: - import httpx - async with httpx.AsyncClient(timeout=180) as cl: - r = await cl.post( - f"http://localhost:7860/api/ai/short/{post_id}", - json={"voice":"vi-VN-HoaiMyNeural","emotion":"neutral","speed":1.2}, - headers={"Content-Type":"application/json"} - ) - if r.status_code < 300: - sj = r.json() - if sj.get('video'): - posts = _load_wall_posts() - for p in posts: - if p.get('id') == post_id: - p['video'] = sj['video'] - break - _save_wall_posts(posts) - return True - except: pass - return False - -async def _auto_rewrite_one(topic, slot_label, used_urls=None, post_index=0): - """Rewrite one topic: find articles, summarize, post to wall, trigger short. - used_urls: shared set to avoid duplicate articles across topics. - post_index: 0-based index to create multiple posts per topic (0,1,2 = up to 3 posts).""" - from urllib.parse import quote as _q - # Get MORE items to support 1-3 posts per topic - items = _search_all(topic, limit=12) - # Skip URLs already used by another topic - if used_urls is not None: - filtered = [it for it in items if it.get('url') not in used_urls] - if filtered: - items = filtered - if not items or post_index >= len(items): - return False - - # Get article at post_index (0,1,2 for multiple posts) - item = items[post_index] # post_index allows multiple articles per topic - url = item.get('url', '') - title = item.get('title', topic) - if url and used_urls is not None: - used_urls.add(url) - if not url.startswith('http'): - return False - - data = _scrape_article_for_rewrite(url) - if not data or not data.get('paragraphs'): - return False - - raw_text = '\n'.join(data['paragraphs']) - ai_text = None - - # Try AI generation - try: - import ai_ext - prompt = f"Tóm tắt tin tức (tự động {slot_label}):\nTiêu đề: {data['title']}\n{raw_text[:10000]}\n\n4-6 ý chính dạng bullet. Cuối ghi nguồn." - ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000) - except: pass - - if not ai_text or len(ai_text) < 80: - pts = data['paragraphs'][:6] - ai_text = '\n\n'.join([f"• {p[:300]}" for p in pts]) - via = item.get('via', '') or urlparse(url).netloc.replace('www.', '') - ai_text += f"\n\nNguồn tham khảo: {via}" - - # Build slides - images = data.get('images', []) - pts = data['paragraphs'][:10] - slides = [] - for i, p in enumerate(pts[:8]): - img = images[i] if i < len(images) else (images[-1] if images else data.get('og_img', '')) - slides.append({'text': p[:300], 'image': img, 'index': i + 1}) - - post_id = str(int(time.time() * 1000)) + str(_random2.randint(100, 999)) - post = { - "id": post_id, "title": data.get('title', title)[:200], - "text": ai_text, "img": images[0] if images else data.get('og_img', ''), - "url": url, "kind": "auto_rewrite", "slides": slides, - "images": images[:10], "video": "", - "voice": "vi-VN-HoaiMyNeural", "emotion": "neutral", - "language": "vietnamese", "ts": int(time.time()), - "auto_scheduled": True, "slot": slot_label, - } - - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - - # Trigger short generation async - threading.Thread(target=lambda: asyncio.run(_auto_fetch_short(post_id)), daemon=True).start() - return True - -async def _do_scheduled_run(slot_label): - """Main scheduled run: 1-3 posts from 3 different HOT topics (3-9 total), no duplicates.""" - print(f"[auto] Starting scheduled rewrite for {slot_label}") - - # Get top hot topics, skip duplicates - all_topics = _get_hot_topics() - seen_topics = set() - unique_topics = [] - for t in all_topics: - kw = t.get('topic', '').lower().strip() - if kw and len(kw) > 5 and kw not in seen_topics: - is_dup = False - for s in seen_topics: - # Check if one topic is substring of another - if kw in s or s in kw: - is_dup = True - break - if not is_dup: - seen_topics.add(kw) - unique_topics.append(t) - if len(unique_topics) >= 3: - break - - job_topics = [t['topic'] for t in unique_topics[:3] if t.get('topic')] - if not job_topics: - print(f"[auto] No hot topics found, skipping") - return - - print(f"[auto] Running 3 topics: {job_topics}") - - # Track used URLs to avoid cross-topic duplicates - _used_urls = set() - results = [] - - # Process each topic, create 1-3 posts per topic - for jt in job_topics: - for post_idx in range(3): # Try up to 3 posts per topic - try: - ok = await asyncio.wait_for(_auto_rewrite_one(jt, slot_label, _used_urls, post_idx), timeout=120) - if ok: - results.append((jt, post_idx, True)) - print(f"[auto] Created post {post_idx+1} for '{jt}'") - else: - # No more articles for this topic - break - except Exception as e: - print(f"[auto] Error on '{jt}' post {post_idx}: {e}") - results.append((jt, post_idx, False)) - await asyncio.sleep(1) # Small delay between posts - - # Ensure at least 3 posts total (fallback if needed) - successful_posts = sum(1 for _, _, ok in results if ok) - print(f"[auto] Done {slot_label}: {successful_posts} posts created") - - # Log - from datetime import datetime, timezone, timedelta - VN_TZ_SCHED = timezone(timedelta(hours=7)) - today_str = datetime.now(VN_TZ_SCHED).strftime('%Y-%m-%d') - log = _load_auto_log() - if today_str not in log: log[today_str] = {} - log[today_str][slot_label] = { - 'time': datetime.now(VN_TZ_SCHED).strftime('%H:%M:%S'), - 'count': successful_posts, - 'total': len(job_topics), - } - _save_auto_log(log) - -def _scheduler_loop(): - """Check every 60s; trigger at 7:00, 13:00, 19:00 VN time. - On startup, check for any missed slots today and run them immediately.""" - time.sleep(35) - from datetime import datetime, timezone, timedelta - VN_TZ_SCHED = timezone(timedelta(hours=7)) - - _last_run_date = "" - _last_run_slots = set() - - # On startup: check log for missed slots today - try: - start_now = datetime.now(VN_TZ_SCHED) - today_str = start_now.strftime('%Y-%m-%d') - current_hour = start_now.hour - current_minute = start_now.minute - log = _load_auto_log() - today_log = log.get(today_str, {}) - for h, label in _AUTO_SCHEDULE_TIMES: - # Run if slot is past (either strictly earlier hour, or same hour but window has passed) - should_run = False - if h < current_hour: - should_run = True - elif h == current_hour and current_minute > 10: - should_run = True - if should_run and label not in today_log: - print(f"[auto] Detected missed slot {label} (h={h} < now={current_hour}:{current_minute}), running catch-up now") - _run_scheduled_sync(label) - _last_run_slots.add(label) - except Exception as e: - print(f"[auto] Catch-up check error: {e}") - - while True: - try: - now = datetime.now(VN_TZ_SCHED) - today = now.strftime('%Y-%m-%d') - hour = now.hour - minute = now.minute - - if today != _last_run_date: - _last_run_date = today - _last_run_slots = set() - - slot = None - for h, label in _AUTO_SCHEDULE_TIMES: - if hour == h and 0 <= minute < 5: - slot = label - break - - if slot and slot not in _last_run_slots: - _last_run_slots.add(slot) - _run_scheduled_sync(slot) - except Exception as e: - print(f"[auto] Loop error: {e}") - - time.sleep(60) - -threading.Thread(target=_scheduler_loop, daemon=True, name='auto-rewrite-scheduler').start() - -def _wall_cleanup_once(): - """One-time startup cleanup: sort the persistent wall store newest-first - and remove truly-garbage auto posts (no valid image at ALL, no video, no - slides, no embed URL — i.e. a post that can never be displayed). - - NOTE: This is intentionally conservative. Posts with a valid image or a - valid embed/video are NEVER deleted here — they are only hidden at view - time by _wall_posts_for_view() when the image is a placeholder. This - prevents accidental data loss of FPT Short AI posts whose image is valid - but may temporarily lack a short_thumb.""" - try: - time.sleep(8) - posts = _load_wall_posts() - if not isinstance(posts, list): - return - kept = [] - removed = 0 - removed_ids = [] - needs_sort = False - for p in posts: - if not isinstance(p, dict): - removed += 1 - continue - if _is_auto_post(p): - has_img = _post_has_valid_image(p) - has_content = _post_has_slide_info(p) - vid = (p.get("video") or "").strip() - # Only delete auto posts that are completely unrecoverable: - # no valid image AND no video/slides/embed at all. - if not has_img and not has_content and not vid: - removed += 1 - removed_ids.append(p.get('id', '?')) - continue - kept.append(p) - # Sort if any post lacks proper ordering - prev_ts = None - is_sorted = True - for p in kept: - ts = _created_ts(p) - if prev_ts is not None and ts > prev_ts: - is_sorted = False - break - prev_ts = ts - if removed > 0 or not is_sorted: - kept.sort(key=_created_ts, reverse=True) - _save_wall_posts(kept) - print(f"[wall] startup cleanup: removed {removed} garbage posts ({removed_ids[:10]}), kept {len(kept)}, sorted newest-first") - except Exception as e: - print(f"[wall] startup cleanup error: {e}") - -threading.Thread(target=_wall_cleanup_once, daemon=True, name='wall-cleanup').start() - -@app.get('/api/debug/auto_schedule') -async def debug_auto_schedule(slot: str = '07:00'): - """Manually trigger auto scheduler for debugging.""" - try: - # Check if we can access the data directory - log = _load_auto_log() - topics = _get_hot_topics()[:3] - job_topics = [t['topic'] for t in topics if t.get('topic')] - return JSONResponse({ - "slot": slot, - "log": log, - "hot_topics": job_topics, - "wall_posts_count": len(_load_wall_posts()), - "data_dir_writable": os.access(DATA_DIR, os.W_OK) if os.path.isdir(DATA_DIR) else False, - "data_dir_exists": os.path.isdir(DATA_DIR), - }) - except Exception as e: - return JSONResponse({"error": str(e)}, status_code=500) - -def _run_scheduled_sync(slot): - """Run _do_scheduled_run in a separate event loop (for background thread).""" - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - loop.run_until_complete(_do_scheduled_run(slot)) - except Exception as e: - print(f"[auto] Background run error: {e}") - finally: - loop.close() - -@app.get('/api/debug/trigger_auto') -async def debug_trigger_auto(slot: str = '19:00'): - """Trigger _do_scheduled_run in background thread (non-blocking).""" - threading.Thread(target=_run_scheduled_sync, args=(slot,), daemon=True).start() - return JSONResponse({"status": "started", "slot": slot}) - -# ===== SHORTS RSS PROXY ENDPOINT ===== -@app.get("/api/shorts/rss") -def shorts_rss(): - """Get shorts from YouTube RSS feeds server-side""" - import xml.etree.ElementTree as ET - import html as html_lib2 - import re as re2 - - YOUTUBE_CHANNELS = { - "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg", - "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g", - } - - shorts = [] - seen = set() - - for handle, channel_id in YOUTUBE_CHANNELS.items(): - try: - rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}" - r = req.get(rss_url, headers=HEADERS, timeout=15) - if r.status_code != 200: - continue - - root = ET.fromstring(r.text) - ns = { - 'atom': 'http://www.w3.org/2005/Atom', - 'yt': 'http://www.youtube.com/xml/schemas/2015', - 'media': 'http://search.yahoo.com/mrss/' - } - - for entry in root.findall('atom:entry', ns)[:30]: - title_el = entry.find('atom:title', ns) - title = html_lib2.unescape(title_el.text) if title_el is not None and title_el.text else '' - - link_el = entry.find('atom:link', ns) - link = link_el.get('href', '') if link_el is not None else '' - - vid_el = entry.find('yt:videoId', ns) - vid = vid_el.text if vid_el is not None else '' - - if not vid or vid in seen: - continue - - # Check if it's a short - is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link - - if not is_short: - desc_el = entry.find('media:description', ns) - if desc_el is not None and desc_el.text: - if '#shorts' in desc_el.text.lower(): - is_short = True - - if not is_short: - continue - - seen.add(vid) - - # Get thumbnail - thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg" - media_group = entry.find('media:group', ns) - if media_group is not None: - thumb_el = media_group.find('media:thumbnail', ns) - if thumb_el is not None: - thumb = thumb_el.get('url', thumb) - - shorts.append({ - 'id': vid, - 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120], - 'img': thumb, - 'link': f'https://www.youtube.com/shorts/{vid}', - 'channel': handle, - 'source': 'yt' - }) - - if len(shorts) >= 40: - break - - except Exception as e: - print(f"RSS error for {handle}: {e}") - continue - - return {"shorts": shorts, "count": len(shorts)} - -# ===== M3U IPTV Channels (FPT Play Bóng Đá live streams) ===== -_M3U_URL = "https://raw.githubusercontent.com/Love4vn/Stalker2M3U/refs/heads/1/live_schedule_Optimize.m3u" -_m3u_cache = {"t": 0, "d": []} -_M3U_CACHE_FILE = os.path.join("/data" if os.path.isdir('/data') else "/app/data", 'm3u_cache.json') - -def _load_m3u_disk(): - """Load M3U cache from disk (if available).""" - try: - if os.path.exists(_M3U_CACHE_FILE): - with open(_M3U_CACHE_FILE, 'r', encoding='utf-8') as f: - d = json.load(f) - if d and isinstance(d.get('channels'), list): - return d - except Exception: - pass - return None - -def _save_m3u_disk(channels, ts): - """Save M3U cache to disk.""" - try: - os.makedirs(os.path.dirname(_M3U_CACHE_FILE), exist_ok=True) - with open(_M3U_CACHE_FILE, 'w', encoding='utf-8') as f: - json.dump({"channels": channels, "t": ts}, f, ensure_ascii=False) - except Exception: - pass - -def _parse_m3u(): - """Fetch & parse the M3U playlist from GitHub.""" - r = req.get(_M3U_URL, headers={"User-Agent": "Mozilla/5.0"}, timeout=20) - if r.status_code != 200: - return [] - lines = r.text.splitlines() - out = [] - cur = {} - for line in lines: - line = line.strip() - if line.startswith("#EXTINF"): - t_match = re.search(r',(.+)$', line) - cur = { - "title": t_match.group(1).strip() if t_match else "Channel", - "id": "", - "logo": "", - "group": "", - "url": "", - "vlcopts": {}, - } - for attr_match in re.finditer(r'([a-zA-Z0-9-]+)="([^"]*)"', line): - k, v = attr_match.group(1), attr_match.group(2) - if k == "tvg-id": - cur["id"] = v - elif k == "tvg-logo": - cur["logo"] = v - elif k == "group-title": - cur["group"] = v - elif line.startswith("#EXTVLCOPT:"): - key_part = line[len("#EXTVLCOPT:"):] - if "=" in key_part: - k, v = key_part.split("=", 1) - cur.setdefault("vlcopts", {})[k.strip()] = v.strip() - elif line and not line.startswith("#") and cur: - cur["url"] = line - out.append(cur) - cur = {} - # Deduplicate by URL - seen = set() - deduped = [] - for c in out: - if c["url"] not in seen: - seen.add(c["url"]) - deduped.append(c) - return deduped - -def _m3u_refresh(): - """Refresh M3U cache in background.""" - n = int(time.time()) - try: - channels = _parse_m3u() - _m3u_cache["t"] = n - _m3u_cache["d"] = channels - _save_m3u_disk(channels, n) - except Exception: - pass - -def _m3u_load(): - """Load M3U: return disk/in-memory cache immediately, refresh in background if stale.""" - global _m3u_cache - n = int(time.time()) - # Try in-memory cache first - if _m3u_cache["d"] and n - _m3u_cache["t"] < 180: - return _m3u_cache["d"], _m3u_cache["t"] - # Try disk cache - disk = _load_m3u_disk() - if disk and disk.get("channels"): - _m3u_cache = {"t": disk.get("t", 0), "d": disk["channels"]} - # Refresh in background if older than 3 min (Stalker play_tokens expire ~3-7 min) - if n - _m3u_cache["t"] >= 180: - threading.Thread(target=_m3u_refresh, daemon=True).start() - return _m3u_cache["d"], _m3u_cache["t"] - # No cache at all — fetch synchronously (first run) - _m3u_refresh() - return _m3u_cache["d"], _m3u_cache["t"] - -@app.get('/api/m3u/channels') -def api_m3u_channels(refresh: int = Query(default=0)): - if refresh: - # FIX: sync refresh — re-parse the M3U so stalker play_tokens are fresh - # before the frontend builds the /api/proxy/m3u_hls URL. The old code - # only kicked off a background thread and returned the STALE cache, - # so clients played with expired tokens -> black screen / 502. - try: - _m3u_refresh() - except Exception as e: - print(f"[M3U] sync refresh error: {e}") - return JSONResponse({"channels": _m3u_cache["d"], "updated": _m3u_cache["t"], "refreshing": False}) - channels, ts = _m3u_load() - return JSONResponse({"channels": channels, "updated": ts}) - -# Pre-warm M3U cache on startup -threading.Thread(target=lambda: _m3u_load(), daemon=True).start() - -@app.get('/api/proxy/m3u_hls') -def proxy_m3u_hls(url: str = Query(...), ua: str = Query(default=None), cookie: str = Query(default=None), auth: str = Query(default=None)): - """Wrap a raw MPEG-TS / stalker stream URL in a minimal HLS playlist so - Hls.js can play it in the browser (browsers cannot play .ts directly in -
'; @@ -210,19 +84,39 @@ function _renderSlidesIn(key, label, emoji, vids, afterEl){ afterEl.parentNode.insertBefore(wrap, afterEl); } +function _renderShortsIn(afterEl){ + if(!_shortsData||!_shortsData.length||!afterEl) return; + const mixed=interleaveShorts(_shortsData); + if(!mixed.length) return; + const wrap=document.createElement('div'); + wrap.className='slider-wrap'; + let h=`
📱 Shorts Dân trí & SKĐSMới nhất · xen kẽ
`; + mixed.slice(0,30).forEach((a,i)=>{ + const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí'; + h+=`
${a.img?``:''}
${badge} ${esc(a.title)}
`; + }); + h+='
';wrap.innerHTML=h; + afterEl.parentNode.insertBefore(wrap,afterEl); +} + function _renderWallIn(afterEl){ - if(!_wallPosts||!_wallPosts.length) return; + if(!_wallPosts||!_wallPosts.length||!afterEl) return; const posts=_wallPosts; + const aiShorts=posts.filter(p=>p.video); + if(aiShorts.length){ + const wrap=document.createElement('div'); + wrap.className='slider-wrap'; + let h='
🎬 Short AI
'; + aiShorts.slice(0,20).forEach((p,i)=>{h+=`
${esc(p.title)}
`;}); + h+='
';wrap.innerHTML=h; + afterEl.parentNode.insertBefore(wrap,afterEl); + } const wrap=document.createElement('div'); wrap.className='slider-wrap';wrap.id='ai-wall-wrap'; let h='
🧱 Tường AI
'; posts.slice(0,20).forEach((p,i)=>{h+=makeWallItem(p,i);}); h+='
';wrap.innerHTML=h; - const target=document.getElementById('ai-wall-under-compose'); - if(target) target.appendChild(wrap); - else if(afterEl) afterEl.parentNode.insertBefore(wrap,afterEl); - // Interleave YouTube RSS feed videos into the wall with wall CSS - if(wrap && typeof _renderYTFeedInWall === 'function') _renderYTFeedInWall(); + afterEl.parentNode.insertBefore(wrap,afterEl); } function _renderHLIn(afterEl){ @@ -235,2215 +129,245 @@ function _renderHLIn(afterEl){ } } -// === RENDER HIGHLIGHT (Video bóng đá) SECTION — above Livescore, with "Xem thêm" per league === -var _hlPage = {}; // {leagueKey: page} -var _hlHasMore = {}; // {leagueKey: bool} - -function _renderHLSection(){ - const hlEl = document.getElementById('home-hl-section'); - if(!hlEl) return; - if(!_hlLeagueData || Object.keys(_hlLeagueData).length===0){ - return; - } - const HL_CONFIG={"premier-league":{name:"Ngoại Hạng Anh",emoji:"🏴"},"champions-league":{name:"Champions League",emoji:"⭐"},"la-liga":{name:"La Liga",emoji:"🇪🇸"},"serie-a":{name:"Serie A",emoji:"🇮🇹"},"bundesliga":{name:"Bundesliga",emoji:"🇩🇪"},"world-cup":{name:"World Cup 2026",emoji:"🌍"},"fa-cup":{name:"FA Cup",emoji:"🏆"},"friendly":{name:"Giao hữu",emoji:"🤝"}}; - - // Ordered list of leagues that have videos (premier-league first) - const orderedLeagues = []; - const plVids = _hlLeagueData['premier-league']; - if(plVids && plVids.length) orderedLeagues.push('premier-league'); - for(const [key, cfg] of Object.entries(HL_CONFIG)){ - if(key === 'premier-league') continue; - const vids = _hlLeagueData[key]; - if(vids && vids.length) orderedLeagues.push(key); - } - if(orderedLeagues.length === 0){ - return; // nothing to show - } - _hlLeagueKey = orderedLeagues; - - // Build ONE combined video list from ALL leagues (premier league items first). - // The scraped sources return the SAME videos for every league (the league - // sub-pages all resolve to the same content from the server), so combine - // then DEDUPE by link — otherwise the slider shows the same ~10 videos - // repeated N times and "loops back to video #1" after the unique ones. - const seenLinks = new Set(); - let combined = []; - orderedLeagues.forEach(key => { - const vids = _hlLeagueData[key] || []; - vids.forEach(a => { - if(!a || !a.link || seenLinks.has(a.link)) return; - seenLinks.add(a.link); - combined.push(Object.assign({}, a, {_league: key, _pos: combined.length})); - }); - }); - // Newest first: sort by publish date when known (the scrapers now return - // `published` parsed from the image/URL dates). Videos without a date keep - // their relative order and go last, so the slider always starts with the - // freshest clips. - combined.sort(function(x, y){ - const xd = x.published || ''; - const yd = y.published || ''; - if(xd && yd) return xd < yd ? 1 : (xd > yd ? -1 : 0); - if(xd && !yd) return -1; // dated first - if(!xd && yd) return 1; - return (x._pos||0) - (y._pos||0); // stable for undated - }); - _hlLeagueData['all'] = combined; - - // ONE unified "🎬 Video bóng đá" slider (per-league sliders removed). - // All videos render at once — no "Xem thêm" button needed (the paged API - // re-scrapes the same sources, so it adds nothing but duplicates). - let html = '
🎬 Video bóng đá' + combined.length + ' video
'; - html += '
'; - hlEl.innerHTML = html; - _renderHLSlides('all', 'Video bóng đá', '🎬', combined, 'hl-main-track'); -} - -function _renderHLSlides(key, label, emoji, vids, containerId){ - const container = document.getElementById(containerId); - if(!container) return; - if(!vids || !vids.length){ - container.innerHTML = '
Chưa có video
'; - return; - } - // Render ALL football videos immediately (the dataset is small: ~70-80 - // items). No 8-item cap, no chunked lazy-load, no server paging on the - // homepage — every item gets its exact index into the vids array, so - // openHighlightFeed can never mismatch order and the slider can never - // "loop back to video #1". Images use native lazy-loading so only the - // visible thumbnails are fetched. - let h = ''; - vids.forEach((a, i) => { - h += _hlItemHtml(key, a, i); - }); - container.innerHTML = h; -} - -// All football videos are rendered at once from the full vids array, so the -// chunked lazy-load machinery is no longer needed and is removed to keep the -// track's indices simple and duplicate-free. - -function _hlItemHtml(key, a, i){ - return '
' + (a.img ? '' : '') + '
' + esc(a.title) + '
'; -} - -async function _loadMoreHL(key, auto){ - // Legacy: kept as a no-op safety net (the old inline button HTML may still - // be cached in some browsers; it simply appends nothing and hides itself). - const btn = typeof document !== 'undefined' ? document.querySelector('.hl-load-more') : null; - if(btn) btn.style.display = 'none'; - _hlHasMore[key] = false; -} - -// === FPT PLAY SLIDER (auto-updating channel) === -// Shows the latest videos from https://youtube.com/@fptbongdaofficial like the -// Short HOT oEmbed slides. The server can't reach youtube.com from its -// datacenter, so the browser (home IP) fetches the channel via r.jina.ai and -// pushes the result to /api/fptplay/update — the slide refreshes automatically -// when the channel uploads something new. -var _fptVideos = []; -var _fptTimer = null; -var _fptSeen = {}; - -function _fptParseJina(txt){ - // jina markdown of the /videos tab: each entry has a title line and a watch - // URL. Collect (title, videoId) in page order. - const out = []; - const titles = []; - const lines = String(txt||'').split('\n'); - for(let i=0;io.id===id)) title = titles.pop() || ''; - if(!title){ - // fall back to the line itself (sans url) - title = line.replace(/https?:\/\/\S+/g,'').replace(/[|\[\]]/g,'').trim(); - } - out.push({id:id, title:(title||'Video').slice(0,200), link:'https://youtu.be/'+id}); - } else if(/^\s*\d+\./.test(line)){ - const t = line.replace(/^\s*\d+\.\s+/,'').trim(); - if(t && t.length>4 && !/youtube\.com|youtu\.be/i.test(t)) titles.push(t); - } - } - return out; -} - -async function _fptFetchClient(){ - // Browser-side: user's home IP can reach r.jina.ai (same trick as Short HOT - // description). Returns array of {id,title,link}. - try{ - const ctrl = new AbortController(); - const tid = setTimeout(()=>ctrl.abort(), 60000); - const resp = await fetch('https://r.jina.ai/https://www.youtube.com/@fptbongdaofficial/videos', { - headers:{'x-no-cache':'1','x-respond-with':'markdown'}, - signal: ctrl.signal - }); - clearTimeout(tid); - if(!resp.ok) throw new Error('jina '+resp.status); - const txt = await resp.text(); - const parsed = _fptParseJina(txt); - if(!parsed.length) throw new Error('empty parse'); - return parsed; - }catch(e){ - return null; - } -} - -function _fptRender(){ - const el = document.getElementById('home-fpt-section'); - if(!el) return; - if(!_fptVideos || !_fptVideos.length){ - el.innerHTML = ''; - return; - } - const vids = _fptVideos.slice(0, 30); - // Render FPT Play videos using the SAME wall card CSS as Short AI cards - // (via _makeYTFeedWallItem) — 100% match with card video Short AI. - let h = '
📺 FPT Play Bóng Đá' + vids.length + ' video · tự cập nhật
'; - vids.forEach((a,i)=>{ - h += _makeYTFeedWallItem(a, i); - }); - h += '
'; - el.innerHTML = h; - // lazy thumbs - el.querySelectorAll('img[loading]').forEach(function(im){ im.loading='lazy'; }); -} - -async function _fptSync(){ - // 1) read server cache first (fast) +// === WALL POST HELPERS === +function makeWallItem(p,i){ + const hasVideo = p.video && p.video.length > 0; + const thumbContent = p.img + ? `` + : (hasVideo ? `` : ''); + const videoBadge = hasVideo ? `
🎬
` : ''; + const videoBtn = hasVideo + ? `` + : ``; + return `
${thumbContent}${videoBadge}
${esc(p.title)}
${esc((p.text||'').slice(0,180))}
${videoBtn}
`; +} + +async function makeShortVideo(postId, btn, voice, speed){ + if(!postId)return; + const origText = btn ? btn.textContent : '🎬 Tạo Video'; + if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';} + toast('⏳ Đang tạo video shorts...'); try{ - const r = await fetch('/api/fptplay/videos'); + let url = '/api/ai/short/'+encodeURIComponent(postId); + const params = []; + if(voice) params.push('voice='+encodeURIComponent(voice)); + if(speed) params.push('speed='+encodeURIComponent(speed)); + if(params.length) url += '?' + params.join('&'); + const r = await fetch(url, {method:'POST'}); const j = await r.json(); - if(j && j.videos && j.videos.length){ - _fptVideos = j.videos; - _fptRender(); - } - }catch(e){} - // 2) refresh from the channel (client-side jina) — replaces stale cache - const fresh = await _fptFetchClient(); - if(fresh && fresh.length){ - // push to server so the slide stays updated and persisted - try{ - const body = JSON.stringify({videos: fresh}); - const r2 = await fetch('/api/fptplay/update', {method:'POST', headers:{'Content-Type':'application/json'}, body}); - const j2 = await r2.json(); - if(j2 && j2.videos && j2.videos.length) _fptVideos = j2.videos; - else _fptVideos = fresh; - }catch(e2){ - _fptVideos = fresh; - } - _fptRender(); - } -} - -function _fptStartAuto(){ - if(_fptTimer) return; - _fptSync(); // immediate first pass - _fptTimer = setInterval(_fptSync, 12 * 60 * 1000); // auto-refresh every 12 min -} - -// === YOUTUBE RSS FEED — auto-updating FPT Bóng Đá videos on Tường AI === -// Channel ID UC4LvrpNXujjbGOS4RDvr41g = FPT Bóng Đá. -// The browser fetches the YouTube RSS feed (feeds/videos.xml) directly since -// the datacenter can't reach youtube.com. Parsed entries are interleaved into -// the AI wall (Tường AI) using the same wall CSS classes as makeWallItem so -// they look like native wall posts. Auto-refresh every 15 minutes. -var _ytFeedVideos = []; -var _ytFeedTimer = null; -var _ytFeedUrl = 'https://www.youtube.com/feeds/videos.xml?channel_id=UC4LvrpNXujjbGOS4RDvr41g'; -// The browser cannot fetch this URL directly (YouTube RSS lacks CORS headers). -// The server-side /api/yt/feed endpoint fetches + parses it and returns JSON. - -function _ytParseRssXml(xmlText){ - // Parse YouTube RSS XML. The browser can fetch the raw XML directly. - // Returns [{id, title, link, img, published}] in newest-first order. - var out = []; - try{ - var parser = new DOMParser(); - var doc = parser.parseFromString(xmlText, 'application/xml'); - // Check for parse errors - var err = doc.querySelector('parsererror'); - if(err){ return null; } - var entries = doc.getElementsByTagName('entry'); - for(var i=0; i String(x.id) === String(postId)); + if(p){ + p.video = j.video; + const itemId = 'wall-item-'+postId; + const el = document.getElementById(itemId); + if(el){ + const idx = _wallPosts.indexOf(p); + el.outerHTML = makeWallItem(p, idx); + const newEl = document.getElementById(itemId); + if(newEl) newEl.className = 'wall-item wall-item-new'; } - // Fallback: YouTube default thumbnail - if(!thumb){ thumb = 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg'; } - out.push({ - id: 'yt-' + vid, - videoId: vid, - title: (title || 'Video').slice(0,200), - link: link, - img: thumb, - published: published - }); - } - return out.length ? out : null; - }catch(e){ - console.error('[yt-feed] parse error', e); - return null; - } -} - -function _normalizeYoutubeTs(p){ - // Sort key: use published date or a numeric id prefix, newest first - if(p.published){ - var d = new Date(p.published); - if(!isNaN(d.getTime())){ return d.getTime(); } - } - // fallback: parse videoId is not chronological; use 0 - return 0; -} - -async function _ytFetchFeed(){ - // Fetch the YouTube RSS feed via r.jina.ai reader proxy (works from the browser - // — YouTube blocks direct RSS access due to CORS). r.jina.ai proxies the - // rss2json.com JSON output as plain text inside a markdown blob. - try{ - var ctrl = new AbortController(); - var tid = setTimeout(function(){ ctrl.abort(); }, 20000); - var rssUrl = 'https://www.youtube.com/feeds/videos.xml?channel_id=UC4LvrpNXujjbGOS4RDvr41g'; - var rjUrl = 'https://r.jina.ai/https://api.rss2json.com/v1/api.json?rss_url=' + encodeURIComponent(rssUrl); - var resp = await fetch(rjUrl, { - headers:{'Accept':'text/plain','x-jina-reader':'1','x-no-cache':'1'}, - signal: ctrl.signal - }); - clearTimeout(tid); - if(!resp.ok){ throw new Error('HTTP ' + resp.status); } - var txt = await resp.text(); - // r.jina.ai wraps the JSON in a markdown block — extract the JSON - var jsonMatch = txt.match(/\{[\s\S]*"status"\s*:\s*"ok"[\s\S]*\}/); - if(!jsonMatch){ - console.error('[yt-feed] no JSON in r.jina.ai response'); - return null; - } - var data = JSON.parse(jsonMatch[0]); - if(!data.items || !data.items.length){ return null; } - var out = []; - for(var i=0;i' - : '
'; - var videoBadge = '
🎬
'; - var vid = v.videoId || v.id; - var callOpen = "openYTEmbedFeed('"+esc(vid)+"','"+esc(v.title)+"')"; - return '
' + - '
' + - thumbContent + videoBadge + - '
' + - '
' + esc(v.title) + '
' + - '
' + esc((v.published||'').replace(/T.*/,'') ) + '
' + - '
' + - '' + - '
' + - '
'; -} - -function _renderYTFeedInWall(){ - // Interleave YouTube feed videos into the wall track, using wall CSS. - // Called after _renderWallIn and after each feed refresh. - var track = document.getElementById('ai-wall-track'); - if(!track){ return; } - // Remove any previous feed items (they get re-appended to stay "latest") - var existing = track.querySelectorAll('.wall-yt-feed-item'); - existing.forEach(function(el){ el.remove(); }); - if(!_ytFeedVideos || !_ytFeedVideos.length){ return; } - // Interleave: insert feed items at regular intervals among wall posts - var wallItems = Array.prototype.slice.call(track.children); - var feedItems = _ytFeedVideos.slice(0, 12); // cap to keep wall tidy - var step = Math.max(1, Math.ceil(wallItems.length / feedItems.length)); - var insertIdx = step; - feedItems.forEach(function(v, i){ - var wrapper = document.createElement('div'); - wrapper.className = 'wall-yt-feed-item'; - wrapper.innerHTML = _makeYTFeedWallItem(v, i); - if(insertIdx < wallItems.length){ - track.insertBefore(wrapper, wallItems[insertIdx]); - wallItems.splice(insertIdx, 0, wrapper); - insertIdx += step + 1; - }else{ - track.appendChild(wrapper); - wallItems.push(wrapper); - } - }); -} - -function openYTEmbedFeed(videoId, title){ - // Open a YouTube embed in the SAME TikTok-style viewer used by Short AI - // (buildTikTokSlide + initTikTokFeed) — 100% match with Short AI player. - // Builds a SCROLLABLE feed that starts at this FPT video and lets the user - // swipe UP/DOWN to browse older FPT videos interleaved with Short AI content, - // in newest-first order. - showView('view-tiktok'); - var el = document.getElementById('view-tiktok'); - if(!el){ return; } - - function _fptTs(v){ - if(v && v.published){ - var d = new Date(v.published); - if(!isNaN(d.getTime())) return d.getTime(); - } - return 0; - } - - // 1) Gather all playable items: FPT wall videos + Short AI posts (newest first) - var items = []; - var seenFpt = {}; - function pushFpt(v){ - if(!v) return; - var vid = v.videoId || v.id; - if(!vid || seenFpt[vid]) return; - seenFpt[vid] = 1; - items.push({ - kind:'fpt', - videoId: vid, - title: v.title || 'Video', - img: v.img || 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg', - ts: _fptTs(v) - }); - } - (_ytFeedVideos||[]).forEach(pushFpt); - (_fptVideos||[]).forEach(pushFpt); - (_wallPosts||[]).forEach(function(p){ - if(!p || !p.video) return; - var ts = parseInt(p.created||'0',10); - if(isNaN(ts) || !ts){ var d = new Date(p.created_str||''); ts = isNaN(d.getTime()) ? 0 : d.getTime(); } - items.push({ - kind:'ai', - videoId: p.id || ('ai-' + items.length), - postId: p.id || '', - title: p.title || 'Video', - img: p.short_thumb || p.img || '', - text: (p.text && p.text !== p.title ? p.text : '').slice(0,400), - video: p.video, - ts: ts - }); - }); - // 2) Sort newest-first, then rotate so the clicked FPT video is first - items.sort(function(a,b){ return (b.ts||0) - (a.ts||0); }); - var start = 0; - for(var i=0;i' - + ''; - } - function aiVtag(it){ - var isYT = /youtube\.com\/embed|youtu\.be\/|youtube-nocookie|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(it.video||''); - if(!it.video) return ''; - return isYT - ? '
' - : ''; - } - - var h = '' - + '
'; - ordered.forEach(function(it, idx){ - var vtag, badge, badgeClass, shareUrl, postId, desc, extraBtn; - if(it.kind === 'fpt'){ - vtag = fptVtag(it); - badge = 'FPT Play'; badgeClass = 'badge-fpt'; - shareUrl = 'https://www.youtube.com/watch?v=' + it.videoId; - postId = ''; desc = ''; extraBtn = ''; - } else { - vtag = aiVtag(it); - badge = 'Short AI'; badgeClass = 'badge-ai'; - shareUrl = it.video || ''; - postId = it.postId || ''; - desc = it.text || ''; - extraBtn = ''; - } - h += buildTikTokSlide({ - vtag: vtag, - title: it.title, - badge: badge, - badgeClass: badgeClass, - videoId: it.videoId + '-feed-' + String(idx), - idx: idx, - total: ordered.length, - shareUrl: shareUrl, - postId: postId, - desc: desc, - extraBtn: extraBtn || '' - }); - }); - h += '
'; - el.innerHTML = h; - setTimeout(function(){ initTikTokFeed(); }, 200); -} - -async function _ytFeedSync(){ - // 1) render from cache (immediate) - if(_ytFeedVideos.length){ - _renderYTFeedInWall(); - } - // 2) refresh from the live channel feed - var fresh = await _ytFetchFeed(); - if(fresh && fresh.length){ - _ytFeedVideos = fresh.slice(0, 15); - _renderYTFeedInWall(); - } -} - -function _ytFeedStartAuto(){ - if(_ytFeedTimer) return; - _ytFeedSync(); - _ytFeedTimer = setInterval(_ytFeedSync, 15 * 60 * 1000); // every 15 min -} - -// === WALL POST HELPERS === -function makeWallItem(p,i){ - var hasVideo = p.video && p.video.length > 0;var isEmbed = !!(p.embed_oembed || /tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|youtube\.com\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(p.video||'')); - var isSlide = (p.slides && p.slides.length) || p.kind==='slide_summary'; - // Slide/design posts: keep the image's natural aspect ratio (no 16:9 crop) - // so portrait-designed slides aren't cut — this fixes the "saved image ratio - // and background position look wrong vs the preview" bug on the wall thumb. - var thumbStyle = isSlide - ? 'aspect-ratio:auto;max-height:340px;display:flex;align-items:flex-start;justify-content:center;background:#000' - : ''; - var thumbContent = isEmbed - ? (p.img - ? '' - : '
') - : (isSlide - ? (p.img ? '' : (hasVideo ? '' : '')) - : (p.img ? '' : (hasVideo ? '' : ''))); - var videoBadge = hasVideo ? '
🎬
' : ''; - var vid = p.id||i; - var lang = p.language || detectLanguage(p.title + ' ' + (p.text||'')); - var curVoice = p.voice || getAutoVoice(lang); - var curEmotion = p.emotion || detectEmotion(p.title + ' ' + (p.text||'')); - var selKey = 'inline-' + vid; - if(!_ttsSelections[selKey]) _ttsSelections[selKey] = {voice: curVoice, emotion: curEmotion}; - var voiceOpts = ''; - VOICE_LIST.forEach(function(v){ - voiceOpts += ''; - }); - var emotOpts = ''; - EMOTION_LIST.forEach(function(e){ - emotOpts += ''; - }); - var spd = p.short_speed || '1.2'; - var voiceBar = '
' - +'' - +'' - +'' - +'
'; -var makeBtn = hasVideo - ? '' - : ''; - var designBtn = (p.slides && p.slides.length) ? '' : ''; - return '
'+thumbContent+videoBadge+'
'+esc(p.title)+'
'+esc((p.text||'').slice(0,180))+'
'+voiceBar+'
'+designBtn+makeBtn+'
'; -} - -/* ===================================================================== - * Short AI Creator v2 - * - TikTok background-music list (server-provided) or uploaded audio - * - uploaded image OR uploaded video as the short background - * - "Tạo lại" (recreate): use the DESIGNED slide images + the previous - * short's audio (NO text ever enters the video again) - * ===================================================================== */ -var _shortMusicList = []; -async function loadShortMusicList(){ - if(_shortMusicList.length) return _shortMusicList; - try{ - const r = await fetch('/api/ai-short/music'); - const j = await r.json(); - _shortMusicList = (j.music || []); - }catch(e){ _shortMusicList = []; } - return _shortMusicList; -} - -function openShortCreator(postId){ - if(!postId) return; - const p = _wallPosts.find(x => String(x.id) === String(postId)); - if(!p) return; - // if the post has designed slides, recreate defaults to slides mode - const hasSlides = p.slides && p.slides.length > 0; - _buildShortCreatorModal(p, hasSlides, false); -} - -/* 🔥 Thêm Short HOT — homepage button. Opens the SAME short-creator modal with - * full scrap capability (image / uploaded video / video-from-link) but creates - * a BRAND-NEW wall post (no source article) when the short is generated. */ -function openShortHotCreator(){ - const p = { - id: 'hot-' + Date.now(), - title: '', - text: '', - img: null, - images: [], - slides: null, - video: null, - language: 'vi', - }; - _buildShortCreatorModal(p, false, true); -} - -function _buildShortCreatorModal(p, defaultUseSlides, hotMode){ - loadShortMusicList().then(music => { - const hasPrev = !!(p.short_audio_url || p.video); - const hasSlides = p.slides && p.slides.length > 0; - const useSlideDef = defaultUseSlides !== undefined ? defaultUseSlides : (hasSlides && hasPrev); - const overlay = document.createElement('div'); - overlay.id = 'short-creator-overlay'; - overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.94);z-index:99999;display:flex;align-items:center;justify-content:center;padding:12px;overflow-y:auto'; - - // voice/emotion from stored selection - const selKey = 'inline-' + p.id; - if(!_ttsSelections[selKey]) _ttsSelections[selKey] = {voice: p.voice || getAutoVoice(p.language || detectLanguage(p.title+' '+(p.text||''))), emotion: p.emotion || detectEmotion(p.title+' '+(p.text||''))}; - const curVoice = _ttsSelections[selKey].voice || 'vi-VN-HoaiMyNeural'; - const curEmotion = _ttsSelections[selKey].emotion || 'neutral'; - - let h = '
'; - h += '

'+(hotMode?'🔥 Thêm Short HOT':'🎬 Tạo Short AI')+(hasPrev?' (Tạo lại)':'')+'

'; - if(hotMode){ - h += '
'; - h += '
'; - } - - /* 0. Recreate mode (designed slides only, no text) */ - if(hasSlides){ - h += '
'; - h += ''; - h += '
Dùng ảnh slide đã thiết kế làm nền + giữ nguyên audio của Short trước đó. Chữ KHÔNG xuất hiện trong video.
'; - h += '
'; - h += '
Chọn slide muốn đưa vào Short (tích = dùng):
'; - p.slides.forEach((s,i)=>{ - const simg = s.image || p.img || ''; - h += ''; - }); - h += '
'; - } - - /* 1. Background: image (default) / uploaded video / scraped video link */ - h += '
'; - h += '
'; - h += ''; - h += ''; - h += ''; - h += '
'; - h += ''; - h += ''; - h += ''; - h += '
'; - - /* 2. Audio + 3. Voice — SKIPPED in HOT mode (video keeps its own audio) */ - if(!hotMode){ - /* 2. Audio: previous short audio / TikTok music / uploaded audio */ - h += '
'; - h += ''; - /* Music chooser — luôn hiển thị để người dùng NGHE THỬ trước khi chọn */ - h += '
'; - h += '
'; - h += '
'; - h += ''; - h += '
▶ Nghe thử nhạc nền TikTok trước khi chọn. Nhạc sẽ được trộn vào video (nền) khi tạo.
'; - h += '
'; - h += ''; - h += '
'; - - /* 3. Voice + emotion + speed (TTS) */ - h += '
'; - h += '
'; - h += '
'; - h += '
'; - h += '
'; - } - - h += '
'; - h += ''; - h += ''; - h += '
'; - h += '
'; - overlay.innerHTML=h; document.body.appendChild(overlay); - // Cleanup HLS preview instance whenever the modal is removed (✕ / Hủy / success) - (function(){ - const obs = new MutationObserver(function(muts){ - if(document.getElementById('sc-scrape-video')){ - const p = document.getElementById('sc-scrape-video'); - if(p._hls){ try{ p._hls.destroy(); }catch(e){} p._hls = null; } - } - }); - obs.observe(document.body, {childList:true, subtree:false}); - // stop after this overlay is gone - setTimeout(()=>obs.disconnect(), 60*1000); - })(); - - // ---- mode toggles ---- - let bgMode = hotMode ? 'link' : 'img'; - function setBgMode(m){ - bgMode = m; - document.getElementById('sc-bg-mode-img').style.background = m==='img' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-img').style.color = m==='img' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-mode-video').style.background = m==='video' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-video').style.color = m==='video' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-mode-link').style.background = m==='link' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-link').style.color = m==='link' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-img-wrap').style.display = (m==='img' || m==='link') ? 'block' : 'none'; - document.getElementById('sc-bg-video-wrap').style.display = m==='video' ? 'block' : 'none'; - document.getElementById('sc-bg-link-wrap').style.display = m==='link' ? 'block' : 'none'; - } - if(hotMode){ - // HOT mode: only video-from-link is offered; hide ảnh/upload-video buttons - document.getElementById('sc-bg-mode-img').style.display = 'none'; - document.getElementById('sc-bg-mode-video').style.display = 'none'; - document.getElementById('sc-bg-mode-link').style.background = '#2d8659'; - document.getElementById('sc-bg-mode-link').style.color = '#fff'; - } else { - document.getElementById('sc-bg-mode-img').addEventListener('click', ()=>setBgMode('img')); - document.getElementById('sc-bg-mode-video').addEventListener('click', ()=>setBgMode('video')); - document.getElementById('sc-bg-mode-link').addEventListener('click', ()=>setBgMode('link')); - } - - // ---- scraped video link: fetch preview ---- - const scLinkInput = document.getElementById('sc-video-link'); - const scScrapeBtn = document.getElementById('sc-video-scrape'); - if(scScrapeBtn && scLinkInput){ - scScrapeBtn.addEventListener('click', async ()=>{ - const url = scLinkInput.value.trim(); - const st = document.getElementById('sc-video-scrape-status'); - const preview = document.getElementById('sc-video-preview'); - const meta = document.getElementById('sc-video-meta'); - if(!url){ - st.textContent = '⚠️ Dán link video trước.'; - st.style.color = '#e0a030'; - return; - } - st.textContent = '⏳ Đang lấy thông tin video...'; - st.style.color = '#888'; - try{ - const r = await fetch('/api/ai-short/scrape?url=' + encodeURIComponent(url)); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Không lấy được video'); - // metadata - let metaHtml = ''; - if(j.title) metaHtml += '
' + esc(j.title) + '
'; - if(j.duration) metaHtml += '
⏱️ ' + Math.round(j.duration) + 's
'; - if(j.extractor) metaHtml += '
Nguồn: ' + esc(j.extractor) + '
'; - if(j.note) metaHtml += '
⚠️ ' + esc(j.note) + '
'; - meta.innerHTML = metaHtml; - meta.style.display = 'block'; - // direct URL for the short; keep oEmbed fallback metadata too - const scDirect = j.direct_url || ''; - let scEmbed = j.embed_url || ''; - // YouTube/other scrape often returns the oEmbed-style iframe URL via - // direct_url (embed pages can't be downloaded as media). Normalize: - // treat direct embed URLs as oEmbed sources so the submit path saves - // an embeddable slide with auto title/thumb instead of erroring. - if(!scEmbed && /youtube\.com\/embed|youtu\.be\/|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|player\.vimeo\.com|platform\.twitter\.com/.test(scDirect)){ - scEmbed = scDirect; - } - const scThumb = j.thumbnail || j.thumb || ''; - const scDesc = j.description || ''; - meta.setAttribute('data-title', j.title || ''); - meta.setAttribute('data-direct', scDirect || ''); - meta.setAttribute('data-embed', scEmbed || ''); - meta.setAttribute('data-thumb', scThumb || ''); - meta.setAttribute('data-desc', scDesc || ''); - // Show description (YouTube/other) under the title in the meta box - if(scDesc){ - metaHtml += '
' + esc(scDesc) + '
'; - meta.innerHTML = metaHtml; - } - // Auto-fill the Short HOT title field with the real scraped title - const hotTitle = document.getElementById('sc-hot-title'); - if(hotTitle){ hotTitle.setAttribute('data-autofilled', j.title ? '1' : '0'); } - if(hotTitle && j.title && !hotTitle.value.trim()){ - hotTitle.value = j.title; - } - document.getElementById('sc-scrape-direct').value = scDirect; - document.getElementById('sc-scrape-duration').value = j.duration ? String(j.duration) : ''; - // YouTube description client-side fallback: the user's browser (home - // IP) can reach r.jina.ai even when the server cannot; fill the - // description if the server didn't return one. - if(!scDesc && /youtube\.com|youtu\.be/.test(url)){ - try{ - fetch('https://r.jina.ai/' + url, {headers:{'x-no-cache':'1'}}) - .then(resp => resp.text()) - .then(txt => { - const m = txt.match(/(?:^|\n)Description:\s*([\s\S]*?)(?=\n[A-Z][a-z]+:|$)/); - const t2 = txt.match(/(?:^|\n)Title:\s*(.+)/); - if(m && m[1] && m[1].trim()){ - const d = m[1].trim().slice(0,2000); - meta.setAttribute('data-desc', d); - metaHtml += '
' + esc(d) + '
'; - meta.innerHTML = metaHtml; - } - if(t2 && t2[1] && hotTitle && !hotTitle.value.trim()){ - hotTitle.value = t2[1].trim().slice(0,250); - } - }).catch(()=>{}); - }catch(e2){} - } - // fallback note when only oEmbed metadata is available (no direct media) - if(!scDirect && scEmbed){ - st.textContent = 'ℹ️ Video không tải trực tiếp được, sẽ chèn dạng oEmbed (tự lấy tiêu đề/mô tả).'; - st.style.color = '#e0a030'; - meta.style.display = 'block'; - const ebtn = document.getElementById('sc-video-scrape'); - if(ebtn) ebtn.style.display = 'none'; - } - if(j.previewable && scDirect){ - const isYouTube = /youtube\.com\/embed|youtu\.be\/|youtube-nocookie/.test(scDirect); - const isHls = !!j.is_hls || /\.m3u8/i.test(scDirect); - const streamUrl = isHls - ? '/api/ai-short/scrape/hls?url=' + encodeURIComponent(scDirect) - : '/api/ai-short/scrape/preview?url=' + encodeURIComponent(scDirect); - preview.style.display = 'block'; - preview.setAttribute('data-ishls', isHls ? '1' : '0'); - if(isYouTube){ - // YouTube embed — render as iframe (direct embed URL already has autoplay) - preview.setAttribute('data-ishls', '0'); - preview.innerHTML = ''; - st.textContent = '✅ Đã lấy video YouTube. Bấm play để xem trước.'; - st.style.color = '#8f8'; - } else { - preview.innerHTML = ''; - const v = preview.querySelector('#sc-scrape-video'); - if(isHls && v && typeof Hls !== 'undefined' && Hls.isSupported()){ - const hls = new Hls(); - hls.loadSource(streamUrl); - hls.attachMedia(v); - hls.on(Hls.Events.MANIFEST_PARSED, ()=>{ v.play().catch(()=>{}); }); - v._hls = hls; - } else if(isHls && v && v.canPlayType('application/vnd.apple.mpegurl')){ - v.src = streamUrl; // native Safari HLS - } - st.textContent = '✅ Đã lấy video. Bấm play để xem trước.'; - st.style.color = '#8f8'; - } - } else { - preview.style.display = 'none'; - if(j.note){ - st.textContent = '⚠️ ' + j.note; - st.style.color = '#e0a030'; - } else { - st.textContent = '❌ Không phát trước được (có thể do nguồn chặn). Bạn vẫn có thể thử tạo short.'; - st.style.color = '#e05555'; - } - } - }catch(e){ - st.textContent = '❌ ' + e.message; - st.style.color = '#e05555'; - preview.style.display = 'none'; - document.getElementById('sc-scrape-direct').value = ''; - document.getElementById('sc-scrape-duration').value = ''; - } - }); - } - - // ---- rewrite image picker (chọn 1 ảnh cho nhiều slide) ---- - let _scChosenImg = ''; - document.getElementById('sc-rewrite-list').addEventListener('click', e=>{ - const btn = e.target.closest('.sc-rw-img'); - if(!btn) return; - document.querySelectorAll('.sc-rw-img').forEach(b=>{ b.style.borderColor='#333'; b.dataset.sel='0'; }); - btn.style.borderColor='#ffd700'; btn.dataset.sel='1'; - _scChosenImg = btn.dataset.img || ''; - const hidden = document.getElementById('sc-chosen-img'); - if(hidden) hidden.value = _scChosenImg; - }); - - // ---- audio source toggles (skipped in HOT mode) ---- - if(!hotMode){ - function setAudioSrc(v){ - // nhạc nền TikTok luôn hiển thị để nghe thử; ẩn khi chọn "Không âm thanh" - document.getElementById('sc-music-wrap').style.display = v==='none' ? 'none' : 'block'; - document.getElementById('sc-upload-wrap').style.display = v==='upload' ? 'block' : 'none'; - } - document.getElementById('sc-audio-src').addEventListener('change', e=>setAudioSrc(e.target.value)); - if(hasPrev && p.video) setAudioSrc('prev'); else setAudioSrc('tts'); - } - - // ---- recreate slides: show/hide slide picker ---- - const scReuse = document.getElementById('sc-reuse-slides'); - if(scReuse){ - scReuse.addEventListener('change', function(){ - const pk = document.getElementById('sc-slide-picker'); - if(pk) pk.style.display = this.checked ? 'block' : 'none'; - }); - } - - // ---- music preview player (skipped in HOT mode) ---- - let _scAudio = null; - const listenBtn = hotMode ? null : document.getElementById('sc-music-listen'); - const musicSel = hotMode ? null : document.getElementById('sc-music'); - const playerBox = hotMode ? null : document.getElementById('sc-music-playerbox'); - if(listenBtn && musicSel){ - listenBtn.addEventListener('click', function(){ - const opt = musicSel.options[musicSel.selectedIndex]; - const aurl = opt ? (opt.dataset.aurl || '') : ''; - if(!aurl){ - alert('Không có link nhạc cho lựa chọn này.'); - return; - } - // proxy để tránh CORS khi phát thử trong trình duyệt - const streamUrl = '/api/ai-short/music/stream?url=' + encodeURIComponent(aurl); - if(_scAudio && _scAudio.dataset.src === aurl && !_scAudio.paused){ - _scAudio.pause(); listenBtn.textContent = '▶ Nghe thử'; - return; - } - if(_scAudio) _scAudio.pause(); - if(playerBox) playerBox.style.display = 'block'; - if(playerBox) playerBox.innerHTML = '
🎧 '+esc(opt.text)+'
'; - _scAudio = playerBox ? playerBox.querySelector('audio') : null; - if(_scAudio){ - _scAudio.dataset.src = aurl; - _scAudio.addEventListener('ended', function(){ listenBtn.textContent = '▶ Nghe thử'; }); - _scAudio.addEventListener('error', function(){ - listenBtn.textContent = '▶ Nghe thử'; - toast('❌ Không phát được nhạc thử (mạng/vùng chặn). Bạn vẫn có thể chọn để trộn vào video.'); - }); - listenBtn.textContent = '⏹ Dừng'; - } - }); - } - - // ---- create ---- - document.getElementById('sc-create-btn').addEventListener('click', async ()=>{ - const btn = document.getElementById('sc-create-btn'); - const st = document.getElementById('sc-status'); - btn.disabled = true; btn.textContent = '⏳ Đang tạo...'; - st.textContent = 'Đang chuẩn bị...'; - - // upload files first - try{ - // image file (not in HOT mode) - let imgUrl = ''; - const imgUrlInput = document.getElementById('sc-img-url'); - if(imgUrlInput) imgUrl = imgUrlInput.value.trim() || ''; - const imgFile = hotMode ? null : document.getElementById('sc-img-file').files[0]; - if(imgFile){ - st.textContent = '⏳ Đang tải ảnh lên...'; - const fd = new FormData(); fd.append('file', imgFile, imgFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload ảnh'); - imgUrl = j.url; - } - // video file (not in HOT mode) - let videoUrl = ''; - const videoFile = hotMode ? null : document.getElementById('sc-video-file').files[0]; - if(videoFile){ - st.textContent = '⏳ Đang tải video lên...'; - const fd = new FormData(); fd.append('file', videoFile, videoFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload video'); - videoUrl = j.url; - } - // audio file (not in HOT mode) - let uploadAudioUrl = ''; - const audioFile = hotMode ? null : document.getElementById('sc-audio-file').files[0]; - if(audioFile){ - st.textContent = '⏳ Đang tải audio lên...'; - const fd = new FormData(); fd.append('file', audioFile, audioFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload audio'); - uploadAudioUrl = j.url; - } - - const audioSrc = hotMode ? 'video' : (document.getElementById('sc-audio-src').value); - const useSlides = hotMode ? false : (document.getElementById('sc-reuse-slides') ? document.getElementById('sc-reuse-slides').checked : false); - // nhạc nền TikTok: giá trị != none được trộn vào video (kể cả tạo lại) - let musicId = ''; - const musicSel = hotMode ? null : document.getElementById('sc-music'); - if(musicSel && musicSel.value && musicSel.value !== 'none' && audioSrc !== 'none'){ - musicId = musicSel.value; - } - if(audioSrc === 'music') musicId = musicSel ? musicSel.value : ''; - let audioUrl = ''; - if(hotMode){ audioUrl = ''; } - else if(audioSrc==='upload') audioUrl = uploadAudioUrl; - else if(audioSrc==='prev' && p.video){ audioUrl = p.short_audio_url || ''; } - // reuse_audio explicitly: only when user chose "giữ nguyên audio short trước" - const reuseAudio = hotMode ? false : (audioSrc === 'prev'); - // collect selected slide indices (recreate mode) - let slideIndices = []; - if(useSlides){ - document.querySelectorAll('#sc-slide-picker .sc-slide-chk:checked').forEach(chk=>{ - slideIndices.push(parseInt(chk.dataset.idx)); - }); - if(!slideIndices.length){ - st.textContent = '⚠️ Chọn ít nhất 1 slide để tạo lại.'; - throw new Error('Chọn ít nhất 1 slide'); - } - } - // reuse_audio is sent explicitly above; music (audio_music) is overlaid by the backend - const body = { - post_id: p.id, - use_slides: useSlides, - slide_indices: slideIndices, - reuse_audio: reuseAudio, - voice: hotMode ? 'vi-VN-HoaiMyNeural' : document.getElementById('sc-voice').value, - emotion: hotMode ? 'neutral' : document.getElementById('sc-emotion').value, - speed: hotMode ? 1.0 : (parseFloat(document.getElementById('sc-speed').value) || 1.2), - audio_music: musicId, - audio_url: audioUrl, - }; - if(hotMode){ - // create a brand-new wall post on the AI wall - body.create_new = true; - const hotTitleEl = document.getElementById('sc-hot-title'); - body.title = hotTitleEl ? hotTitleEl.value.trim() : ''; - // scraped video title as fallback wall title - if(!body.title){ - const meta = document.getElementById('sc-video-meta'); - body.title = (meta && meta.dataset.title) ? meta.dataset.title : '🔥 Short HOT'; - } - body.text = ''; - body.language = 'vi'; - const srcEl = document.getElementById('sc-video-link'); - if(srcEl && srcEl.value.trim()) body.url = srcEl.value.trim(); - } - // if uploaded video selected -> use it as background via images? No: - if(bgMode==='video' && videoUrl){ - body.video_url = videoUrl; // backend handles - const vmute = document.getElementById('sc-video-mute'); - if(vmute && vmute.checked) body.video_muted = true; - } else if(bgMode==='link'){ - // scraped video from link: video-first + image tail completion - const scDirect = document.getElementById('sc-scrape-direct') ? document.getElementById('sc-scrape-direct').value : ''; - const meta = document.getElementById('sc-video-meta'); - const scEmbed = meta ? (meta.getAttribute('data-embed') || '') : ''; - const scThumb = meta ? (meta.getAttribute('data-thumb') || '') : ''; - const scTitle = meta ? (meta.getAttribute('data-title') || '') : ''; - const scDesc = meta ? (meta.getAttribute('data-desc') || '') : ''; - // if the modal title was auto-filled from the scrape, prefer it for - // the wall post (user can still edit it before submitting) - const hotTitleVal = document.getElementById('sc-hot-title') ? document.getElementById('sc-hot-title').value.trim() : ''; - if(scDirect && !/youtube\.com\/embed|youtu\.be\/|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|player\.vimeo\.com|platform\.twitter\.com/.test(scDirect)){ - body.video_url = scDirect; - body.scrape_mode = true; // video-first assembly - const vdur = document.getElementById('sc-scrape-duration') ? document.getElementById('sc-scrape-duration').value : ''; - if(vdur) body.video_dur = parseFloat(vdur) || undefined; - const lmute = document.getElementById('sc-link-mute'); - if(lmute && lmute.checked) body.video_muted = true; - // still send the chosen images (they complete the short if the - // video is shorter than the voice) - const chosen = document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''; - const imgs = []; - if(chosen) imgs.push(chosen); - if(imgUrl) imgs.push(imgUrl); - if(imgs.length) body.images = imgs; - if(chosen) body.fixed_image = chosen; - } else if(scEmbed){ - // oEmbed fallback: media can't be downloaded (TikTok/FB/IG/YT block - // datacenter IPs) -> save the short as an embeddable slide with - // auto title/desc/thumb from the scrape metadata. - body.embed_url = scEmbed; - body.embed_title = hotTitleVal || scTitle || ''; - body.embed_thumb = scThumb || ''; - body.embed_desc = scDesc || ''; - const chosenImg = imgUrl || (document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''); - if(chosenImg) body.images = [chosenImg]; - } else { - // No direct media and no embed metadata from the scrape. If the - // user pasted a social/link URL, still post it — the backend - // auto-probes oEmbed and saves the short as an embed slide with - // auto title/desc/thumb (no more "chưa lấy được video" error). - const srcUrlEl = document.getElementById('sc-video-link'); - const srcUrl = srcUrlEl ? srcUrlEl.value.trim() : ''; - if(srcUrl && /^https?:\/\//i.test(srcUrl)){ - body.url = srcUrl; - body.allow_oembed_fallback = true; - st.textContent = 'ℹ️ Không lấy được video trực tiếp — sẽ đăng dạng oEmbed (backend tự lấy tiêu đề/mô tả/ảnh).'; - st.style.color = '#e0a030'; - } else { - st.textContent = '⚠️ Bấm "📥 Lấy video" để lấy video từ link trước khi tạo.'; - throw new Error('Chưa lấy được video từ link'); - } - } - } else { - // 1. ảnh chọn từ danh sách rewrite (áp dụng cho nhiều slide, fix nền cho cả short) - // 2. ảnh URL nhập tay / tải lên - const chosen = document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''; - const imgs = []; - if(chosen) imgs.push(chosen); - if(imgUrl) imgs.push(imgUrl); - if(imgs.length) body.images = imgs; // backend: first = fixed bg (normal mode) - if(chosen) body.fixed_image = chosen; // applies to slides mode too (1 ảnh cho nhiều slide) - } - st.textContent = '⏳ Đang tạo video short (có thể mất 1-2 phút)...'; - const r2 = await fetch('/api/ai-short', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)}); - const j2 = await r2.json(); - if(!r2.ok || j2.error) throw new Error(j2.error || 'Lỗi tạo video'); - toast('✅ Đã tạo Short AI!'); - const pp = _wallPosts.find(x => String(x.id) === String(p.id)); - if(pp){ - pp.video = j2.video; - pp.voice = j2.voice; pp.emotion = j2.emotion; pp.short_speed = j2.speed; - pp.short_music = j2.music; pp.short_audio_url = audioUrl; pp.short_use_slides = j2.use_slides; - pp.short_images = j2.images; - } - if(hotMode && j2.post){ - // 🆕 brand-new wall post created by the backend -> prepend on the AI wall - prependWallPost(j2.post); - } else { - const itemId = 'wall-item-'+p.id; - const el = document.getElementById(itemId); - if(el){ - const idx = _wallPosts.indexOf(pp); - el.insertAdjacentHTML('afterend', makeWallItem(pp, idx)); - el.remove(); - } - } - document.getElementById('short-creator-overlay').remove(); - }catch(e){ - st.textContent = '❌ ' + e.message; - btn.disabled = false; btn.textContent = hotMode ? '🔥 Thêm Short HOT' : '🎬 Tạo Short AI'; - toast('❌ ' + e.message); - } - }); - }); -} - -/* legacy fast path — used by any remaining tts-create-btn handlers */ -async function makeShortVideo(postId, btn, voice, speed, emotion){ - openShortCreator(postId); - return; -} - -var VOICE_LIST = [ - {id:'vi-VN-HoaiMyNeural', label:'🎙️ Hoài My (VI)', lang:'vi'}, - {id:'vi-VN-NamMinhNeural', label:'🎙️ Nam Minh (VI)', lang:'vi'}, - {id:'en-US-AndrewMultilingualNeural', label:'🎙️ Andrew (EN)', lang:'en'}, - {id:'en-AU-WilliamMultilingualNeural', label:'🎙️ William (EN)', lang:'en'}, - {id:'pt-BR-ThalitaMultilingualNeural', label:'🎙️ Thalita (PT)', lang:'pt'}, - {id:'fr-FR-VivienneMultilingualNeural', label:'🎙️ Vivienne (FR)', lang:'fr'}, - {id:'fr-FR-RemyMultilingualNeural', label:'🎙️ Rémy (FR)', lang:'fr'}, - {id:'de-DE-SeraphinaMultilingualNeural', label:'🎙️ Seraphina (DE)', lang:'de'}, - {id:'de-DE-FlorianMultilingualNeural', label:'🎙️ Florian (DE)', lang:'de'}, - {id:'ko-KR-HyunsuMultilingualNeural', label:'🎙️ Hyunsu (KO)', lang:'ko'}, - {id:'it-IT-GiuseppeMultilingualNeural', label:'🎙️ Giuseppe (IT)', lang:'it'}, -]; -var EMOTION_LIST = [ - {id:'neutral', label:'😐 Trung tính'}, - {id:'happy', label:'😊 Vui vẻ'}, - {id:'excited', label:'🔥 Hào hứng'}, - {id:'sad', label:'😢 Buồn'}, - {id:'humorous', label:'😂 Hài hước'}, - {id:'serious', label:'⚠️ Nghiêm túc'}, - {id:'urgent', label:'🚨 Khẩn cấp'}, - {id:'warm', label:'💖 Ấm áp'}, -]; - -document.addEventListener('click',function(e){ - var btn = e.target.closest('.tts-voice-btn'); - if(btn){ - var container = btn.closest('.tts-selector'); - if(container){ - var selKey = 'inline-'+container.dataset.postId; - if(!_ttsSelections[selKey]) _ttsSelections[selKey]={voice:btn.dataset.voice,emotion:'neutral'}; - var allBtns = container.querySelectorAll('.tts-voice-btn'); - for(var i=0;ip.video); + let shortAISection = document.getElementById('short-ai-section'); + if(aiShorts.length === 0){ + if(shortAISection) shortAISection.remove(); return; } - var ebtn = e.target.closest('.tts-emotion-btn'); - if(ebtn){ - var container = ebtn.closest('.tts-selector'); - if(container){ - var selKey = 'inline-'+container.dataset.postId; - if(!_ttsSelections[selKey]) _ttsSelections[selKey]={voice:'vi-VN-HoaiMyNeural',emotion:ebtn.dataset.emotion}; - var allBtns = container.querySelectorAll('.tts-emotion-btn'); - for(var i=0;i{ + h+=`
${esc(p.title)}
`; + }); + track.innerHTML = h; } - return; } -}); -function detectLanguage(text){ - if(!text) return 'vi'; - var t=text.toLowerCase(), chars=new Set(t); - var vnChars='đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵý'; - var vnCount=0; for(var c of vnChars){if(chars.has(c)) vnCount++;} - if(vnCount>=2) return 'vi'; - if(chars.has('ñ')||chars.has('¿')||chars.has('¡')) return 'es'; - if(chars.has('ã')||chars.has('õ')) return 'pt'; - var words=t.split(/\s+/); - var enWords=['the','is','at','which','on','and','or','but','this','that','with','from','have','been']; - var enCount=words.filter(function(w){return enWords.indexOf(w)>=0;}).length; - if(enCount>=2) return 'en'; - return 'vi'; } -function detectEmotion(text){ - if(!text) return 'neutral'; - var t=text.toLowerCase(); - var kws={ - happy:['vui','hạnh phúc','tuyệt','thành công','chiến thắng','feliz','maravilloso','happy','joy','wonderful','great','amazing','love','excellent'], - excited:['hào hứng','phấn khích','đột phá','kỷ lục','đỉnh cao','emocionante','increíble','excited','thrilling','unbelievable','awesome','breakthrough'], - sad:['buồn','đau','mất','thảm họa','khủng hoảng','triste','terrible','sad','unhappy','tragic','painful','death'], - humorous:['hài hước','buồn cười','haha','đùa','engraçado','gracioso','funny','hilarious','joke','lol'], - serious:['nghiêm trọng','khẩn cấp','quan trọng','lo ngại','sério','crítico','serious','critical','urgent','severe','crisis'], - urgent:['khẩn cấp','báo động','ngay lập tức','urgent','breaking','alert','emergency'], - warm:['ấm áp','tình cảm','yêu thương','warm','love','heart','touching'] - }; - var bestScore=0, bestEmotion='neutral'; - for(var em in kws){var score=0; for(var kw of kws[em]){if(t.indexOf(kw)>=0) score++;} if(score>bestScore){bestScore=score;bestEmotion=em;}} - return bestEmotion; -} -function getAutoVoice(lang){var map={vi:'vi-VN-HoaiMyNeural',pt:'pt-BR-ThalitaMultilingualNeural',en:'en-US-AndrewMultilingualNeural',fr:'fr-FR-VivienneMultilingualNeural',de:'de-DE-SeraphinaMultilingualNeural',ko:'ko-KR-HyunsuMultilingualNeural',it:'it-IT-GiuseppeMultilingualNeural'};return map[lang]||'vi-VN-HoaiMyNeural';} -function buildVoiceEmotionSelector(post){ - var lang=post.language||detectLanguage(post.title+' '+(post.text||'')); - var _oldVoiceMap = {'hoaimy':'vi-VN-HoaiMyNeural','namminh':'vi-VN-NamMinhNeural','andrew':'en-US-AndrewMultilingualNeural','jenny':'en-US-AndrewMultilingualNeural','thalita':'pt-BR-ThalitaMultilingualNeural','pt_thalita':'pt-BR-ThalitaMultilingualNeural','vivienne':'fr-FR-VivienneMultilingualNeural','remy':'fr-FR-RemyMultilingualNeural','seraphina':'de-DE-SeraphinaMultilingualNeural','florian':'de-DE-FlorianMultilingualNeural','sunhee':'ko-KR-HyunsuMultilingualNeural','hyunsu':'ko-KR-HyunsuMultilingualNeural','giuseppe':'it-IT-GiuseppeMultilingualNeural','ela':'en-US-AndrewMultilingualNeural','denise':'fr-FR-VivienneMultilingualNeural','katja':'de-DE-SeraphinaMultilingualNeural','nanami':'en-US-AndrewMultilingualNeural','xiaochen':'en-US-AndrewMultilingualNeural','es_carlos':'en-US-AndrewMultilingualNeural','pt_francisco':'pt-BR-ThalitaMultilingualNeural'}; - var _postVoice = post.voice ? (_oldVoiceMap[post.voice] || post.voice) : ''; - var autoVoice= _postVoice || getAutoVoice(lang); - var autoEmotion=post.emotion||detectEmotion(post.title+' '+(post.text||'')); - var selKey = 'inline-'+post.id; - if(!_ttsSelections[selKey]){_ttsSelections[selKey] = {voice: autoVoice, emotion: autoEmotion};} - var h='
'; - h+='
🎙️ Giọng đọc (ngôn ngữ: '+lang.toUpperCase()+'):
'; - VOICE_LIST.forEach(function(v){var sel=v.id===_ttsSelections[selKey].voice?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
😊 Cảm xúc:
'; - EMOTION_LIST.forEach(function(e){var sel=e.id===_ttsSelections[selKey].emotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
⚡ Tốc độ:'; - h+='
'; - h+='
'; - return h; -} -window.showVoiceEmotionSelector=function(postId,title,text){ - var overlay=document.createElement('div'); - overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px'; - var box=document.createElement('div');box.style.cssText='background:#1a1a1a;border:2px solid #2d8659;border-radius:16px;padding:20px;max-width:400px;width:100%;max-height:80vh;overflow-y:auto'; - var lang=detectLanguage(title+' '+text);var autoEmotion=detectEmotion(title+' '+text); - var h='

🎬 Tạo Short AI (ngôn ngữ: '+lang.toUpperCase()+')

'; - h+='
🎙️ Chọn giọng đọc:
'; - VOICE_LIST.forEach(function(v){var sel=v.id===getAutoVoice(lang)?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
😊 Chọn cảm xúc:
'; - EMOTION_LIST.forEach(function(e){var sel=e.id===autoEmotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
⚡ Tốc độ:
'; - h+='
'; - h+='
'; - h+='
'; - h+=''; - box.innerHTML=h;overlay.appendChild(box);document.body.appendChild(overlay); - var selectedVoice=getAutoVoice(lang),selectedEmotion=autoEmotion; - box.querySelectorAll('.ve-voice-btn').forEach(function(btn){btn.addEventListener('click',function(){box.querySelectorAll('.ve-voice-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';});this.style.borderColor='#5cb87a';this.style.background='#1a2a1f';selectedVoice=this.dataset.voice;});}); - box.querySelectorAll('.ve-emotion-btn').forEach(function(btn){btn.addEventListener('click',function(){box.querySelectorAll('.ve-emotion-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';});this.style.borderColor='#5cb87a';this.style.background='#1a2a1f';selectedEmotion=this.dataset.emotion;});}); - box.querySelector('#ve-cancel-btn').addEventListener('click',function(){overlay.remove();}); - box.querySelector('#ve-create-btn').addEventListener('click',async function(){ - this.disabled=true;this.textContent='⏳ Đang tạo...'; - box.querySelector('#ve-status').style.display='block';box.querySelector('#ve-status').textContent='Đang tạo video shorts...'; - try{ - var speed=parseFloat(box.querySelector('#ve-speed').value)||1.2; - if(!_ttsSelections["inline-"+postId]) _ttsSelections["inline-"+postId]={voice:"vi-VN-HoaiMyNeural",emotion:"neutral"}; - _ttsSelections["inline-"+postId].voice=selectedVoice;_ttsSelections["inline-"+postId].emotion=selectedEmotion; - var r=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:selectedVoice,emotion:selectedEmotion,speed:speed})}); - var j=await r.json(); - if(!r.ok||j.error) throw new Error(j.error||'Lỗi tạo video'); - toast('✅ Đã tạo Short AI!');overlay.remove(); - var p=_wallPosts.find(function(x){return String(x.id)===String(postId);}); - if(p){p.video=j.video;p.voice=j.voice;p.emotion=j.emotion;} - }catch(e){this.disabled=false;this.textContent='🎬 Tạo Short';box.querySelector('#ve-status').textContent='❌ '+e.message;} - }); -}; function prependWallPost(post){ _wallPosts.unshift(post); const track=document.getElementById('ai-wall-track'); const wrap=document.getElementById('ai-wall-wrap'); - const target=document.getElementById('ai-wall-under-compose'); - if(target && (!track||!wrap)){ - const newWrap=document.createElement('div'); - newWrap.className='slider-wrap';newWrap.id='ai-wall-wrap'; - newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; - target.appendChild(newWrap); - const firstItem=newWrap.querySelector('.wall-item'); - if(firstItem)firstItem.className='wall-item wall-item-new'; - // re-interleave YouTube feed items after new wall content - if(typeof _ytFeedVideos !== 'undefined') _renderYTFeedInWall(); + const homeEl=document.getElementById('view-home'); + if(!track||!wrap){ + if(homeEl){ + let insertBefore=homeEl.querySelector('.slider-wrap'); + const newWrap=document.createElement('div'); + newWrap.className='slider-wrap'; + newWrap.id='ai-wall-wrap'; + newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; + if(insertBefore) homeEl.insertBefore(newWrap,insertBefore); + else homeEl.appendChild(newWrap); + const firstItem=newWrap.querySelector('.wall-item'); + if(firstItem)firstItem.className='wall-item wall-item-new'; + } return; } - if(track){ - track.insertAdjacentHTML('afterbegin', makeWallItem(post, 0)); - track.scrollTo({left:0,behavior:'smooth'}); - // re-interleave YouTube feed items after new wall content - if(typeof _renderYTFeedInWall === 'function') _renderYTFeedInWall(); - } -} - + const div=document.createElement('div'); + div.className='wall-item wall-item-new'; + div.id='wall-item-'+(post.id||'new-'+Date.now()); + const hasVideo = post.video && post.video.length > 0; + const thumbContent = post.img + ? `` + : (hasVideo ? `` : ''); + const videoBadge = hasVideo ? `
🎬
` : ''; + const videoBtn = hasVideo + ? `` + : ``; + div.innerHTML=`
${thumbContent}${videoBadge}
${esc(post.title)}
${esc((post.text||'').slice(0,180))}
${videoBtn}
`; + track.prepend(div); + track.scrollTo({left:0,behavior:'smooth'}); + if(hasVideo) refreshShortAISlider(); +} + +// === REST OF FUNCTIONS === +let _shortsData=[]; let _wallPosts=[]; let _currentView='home'; let _currentEventId=null; let _currentMatchUrl=null; +function interleaveShorts(shorts){const dt=shorts.filter(s=>s.channel==='baodantri7941');const sk=shorts.filter(s=>s.channel==='baosuckhoedoisongboyte');const result=[];let i=0,j=0;while(i{const topicText=t.topic||t.label.replace(/^#/,'');return``;}).join('');} +async function loadHotTopics(){const j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));const el=document.getElementById('hot-topics');if(!el)return;el.innerHTML=(j.topics||[]).slice(0,18).map(t=>{const topicText=t.topic||t.label.replace(/^#/,'');return``;}).join('');if(j.topics&&j.topics[0]){const firstTopic=j.topics[0].topic||j.topics[0].label.replace(/^#/,'');setTimeout(()=>searchTopic(firstTopic),800);}} function searchTopic(topic){if(!topic){topic=document.getElementById('topic-input')?.value.trim();if(!topic){alert('Nhập chủ đề');return;}}document.getElementById('topic-input').value='';_htTopic=topic;_htPage=0;showHashtagSources(topic,0);} -async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`

🔍 ${esc(topic)}

Đang tìm...
`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`

🔍 ${esc(topic)}

Không tìm được bài viết liên quan
`;return;}let h='';if(page===0)h=`

🔍 ${esc(topic)} (${j.total} bài từ 8 nguồn)

`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`
${esc(s.title)}
${esc(s.via||'')}
`;});if(page===0){h+=`
`;if(j.has_more)h+=``;h+=`
`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}}sources.forEach((s,i)=>{const idx=page*8+i;if(!s.url)return;const ctrl=new AbortController();setTimeout(()=>ctrl.abort(),4000);fetch('/api/article?url='+encodeURIComponent(s.url),{signal:ctrl.signal}).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+idx);if(el)el.innerHTML=``;}}).catch(()=>{});});}catch(e){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(e.message)}
`;}} +async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`

🔍 ${esc(topic)}

Đang tìm...
`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`

🔍 ${esc(topic)}

Không tìm được bài viết liên quan
`;return;}let h='';if(page===0)h=`

🔍 ${esc(topic)} (${j.total} bài từ 8 nguồn)

`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`
${esc(s.title)}
${esc(s.via||'')}
`;});if(page===0){h+=`
`;if(j.has_more)h+=``;h+=`
`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}}sources.forEach((s,i)=>{const idx=page*8+i;if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+idx);if(el)el.innerHTML=``;}}).catch(()=>{});});}catch(e){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(e.message)}
`;}} function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);} async function rewriteHashtag(topic){const btn=event?.target;if(btn){btn.disabled=true;btn.textContent='Đang tổng hợp...';}try{const r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã đăng Tường AI!');if(btn)btn.textContent='✅ Đăng thành công!';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Rewrite AI';}}} -async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='
Đang tải...
';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const d=await _fetchWithTimeout(ep,12000);el.innerHTML=d.html&&d.html.length>50?d.html:'
Không có dữ liệu
';bindMatchClicks(el);if(tab.startsWith('bxh_'))_decorateStandings(el);}catch(e){el.innerHTML='
Lỗi tải hoặc hết thời gian
';}} -function _decorateStandings(el){ - try{ - const items=el.querySelectorAll('.leaderboard-item'); - if(!items.length)return; - // Build header row: # | Đội bóng | Tr T H B BT BB +/- Đ - const head=document.createElement('div'); - head.className='ls-bxh-head'; - head.innerHTML='

Tr

T

H

B

BT

BB

+/-

Đ

'; - el.insertBefore(head, items[0]); - // Make each row use flex layout with the copy cells as a fixed-width grid - items.forEach(function(it){ - it.classList.add('ls-bxh-row'); +async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='
Đang tải...
';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const r=await fetch(ep);const d=await r.json();el.innerHTML=d.html&&d.html.length>50?d.html:'
Không có dữ liệu
';bindMatchClicks(el);}catch(e){el.innerHTML='
Lỗi
';}} +function bindMatchClicks(el){ + el.querySelectorAll('.match-detail').forEach(md=>{ + md.style.cursor='pointer'; + md.addEventListener('click',function(e){ + const statusA=this.querySelector('.status a'); + const teamA=this.querySelector('.teams a[href*="/tran-dau/"]'); + const a = statusA || teamA; + if(a){ + e.preventDefault(); + e.stopPropagation(); + const href=a.getAttribute('href')||''; + const m=href.match(/\/tran-dau\/(\d+)\//); + if(m){ + const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href; + openMatch(m[1],fullUrl); + } + } }); - }catch(e){} + }); + el.querySelectorAll('a').forEach(a=>{ + a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()}); + }); } -function bindMatchClicks(el){el.querySelectorAll('.match-detail').forEach(md=>{md.style.cursor='pointer';md.addEventListener('click',function(e){const statusA=this.querySelector('.status a');const teamA=this.querySelector('.teams a[href*="/tran-dau/"]');const a = statusA || teamA;if(a){e.preventDefault();e.stopPropagation();const href=a.getAttribute('href')||'';const m=href.match(/\/tran-dau\/(\d+)\//);if(m){const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href;openMatch(m[1],fullUrl);}}});});el.querySelectorAll('a').forEach(a=>{a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()});});} function openMatch(id,url){if(!id)return;_currentEventId=id;if(url)_currentMatchUrl=url;document.getElementById('match-overlay').classList.add('active');document.body.style.overflow='hidden';loadMatchTab('detail')} function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''} async function loadMatchTab(tab){document.querySelectorAll('.mo-tab').forEach(t=>t.classList.remove('active'));document.querySelectorAll('.mo-tab').forEach(t=>{if((tab==='comm'&&t.textContent==='Diễn biến')||(tab==='stats'&&t.textContent==='Thống kê')||(tab==='detail'&&t.textContent.includes('Chi tiết')))t.classList.add('active')});const el=document.getElementById('mo-body');if(!el)return;el.innerHTML='
Đang tải...
';try{let apiUrl;if(tab==='stats')apiUrl=`/api/match/${_currentEventId}/stats`;else if(tab==='comm')apiUrl=`/api/match/${_currentEventId}/commentaries`;else{apiUrl=`/api/match/${_currentEventId}/detail`;if(_currentMatchUrl)apiUrl+='?url='+encodeURIComponent(_currentMatchUrl)}const r=await fetch(apiUrl);if(!r.ok){el.innerHTML='
Lỗi máy chủ ('+r.status+')
';return}const d=await r.json();if(d.error){el.innerHTML='
'+esc(d.error)+'
';return}if(tab==='detail'&&typeof renderMatchDetail==='function'){renderMatchDetail(el,d);return}el.innerHTML=d.html||'
Không có dữ liệu
'}catch(e){el.innerHTML='
Lỗi
'}} -function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))} -function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')} -function switchCat(id){document.querySelectorAll('.cat').forEach(c=>c.classList.remove('active'));document.querySelector(`[data-cat="${id}"]`)?.classList.add('active');document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.querySelectorAll('video').forEach(v=>{v.pause();if(v._hls){v._hls.destroy();v._hls=null}});document.querySelectorAll('iframe[data-yt-src]').forEach(f=>{f.src='';const tw=f.closest('.yt-thumb-wrap');if(tw)tw.style.backgroundImage='none'});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else if(id==='m3u'){document.getElementById('view-m3u').classList.add('active');if(typeof loadM3UChannels==='function')loadM3UChannels()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}} -function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}} - -// ===== doShare: COPY link to clipboard, then try native share as bonus ===== - function doShare(title,url,img,postId){ - var shareUrl; - var _base = (typeof SPACE!=='undefined' && SPACE) ? SPACE : location.origin; - if(postId){ - shareUrl = _base+'/s?post_id='+encodeURIComponent(postId)+'&title='+encodeURIComponent(title); - } else { - shareUrl = _base+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||''); - } - // Try clipboard API first (modern, works on HTTPS) - if(navigator.clipboard && navigator.clipboard.writeText){ - navigator.clipboard.writeText(shareUrl).then(function(){ - toast('📋 Đã sao chép link!'); - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - }).catch(function(){ - // Fallback: execCommand (deprecated but works on some browsers) - try{ - var ta=document.createElement('textarea'); - ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; - document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); - if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} - else{prompt('📋 Sao chép link:', shareUrl);} - document.body.removeChild(ta); - }catch(e){prompt('📋 Sao chép link:', shareUrl);} - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - }); - } else { - // execCommand approach - try{ - var ta=document.createElement('textarea'); - ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; - document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); - if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} - else{prompt('📋 Sao chép link:', shareUrl);} - document.body.removeChild(ta); - }catch(e){prompt('📋 Sao chép link:', shareUrl);} - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - } -} - async function doInteract(videoId,type){try{const r=await fetch('/api/v2/interact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,type})});return await r.json();}catch(e){return null;}} async function getInteractions(videoId){try{return await fetch('/api/v2/interactions?id='+encodeURIComponent(videoId)).then(r=>r.json());}catch(e){return{views:0,likes:0,comments:0};}} async function getComments(videoId){try{const j=await fetch('/api/v2/comments?id='+encodeURIComponent(videoId)).then(r=>r.json());return j.comments||[];}catch(e){return[];}} async function postComment(videoId,text){try{const j=await fetch('/api/v2/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,text})}).then(r=>r.json());return j.comments||[];}catch(e){return[];}} -function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.desc?`

${esc(opts.desc)}

`:''}
${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
`;} -function toggleFeedFullscreen(videoId){ - const slide = videoId ? document.querySelector('.tiktok-slide[data-vid="'+videoId+'"]') : null; - const feedEl = slide ? slide.closest('.tiktok-container') : document.querySelector('.tiktok-container'); - if(!feedEl) return; - const on = feedEl.classList.toggle('feed-fullscreen'); - document.body.style.overflow = on ? 'hidden' : ''; - const icons = feedEl.querySelectorAll('[id^="fs-toggle-"]'); - icons.forEach(ic => { ic.textContent = on ? '✕' : '⛶'; }); - if(on){ - // keep the active slide centered & playable in full height - setTimeout(()=>{ slide && slide.scrollIntoView({block:'nearest'}); }, 60); - } else if(slide){ - slide.scrollIntoView({block:'nearest'}); - } -} +function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
`;} async function doView(videoId,btn){const j=await doInteract(videoId,'view');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.views);}} async function doLike(videoId,btn){const j=await doInteract(videoId,'like');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.likes);}} function fmtNum(n){if(!n)return'0';if(n>=1000000)return(n/1000000).toFixed(1)+'M';if(n>=1000)return(n/1000).toFixed(1)+'K';return String(n);} async function loadCounters(videoIds){for(let i=0;iĐang tải...
';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);/* Remove snap so feed can scroll to show comment input */var sl=panel.closest('.tiktok-slide');if(sl)sl.style.scrollSnapAlign='';setTimeout(function(){var feed=document.getElementById('tiktok-feed');if(feed){var slidePos=sl?sl.offsetTop:0;feed.scrollTop=slidePos+200;}/* Focus input */var inp=document.getElementById('cmt-input-'+idx);if(inp)inp.focus();},300);} -function renderInlineComments(panel,videoId,idx,cmts){let h='
💬 Bình luận
';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`
${c.time||''}${esc(c.text)}
`;});}else{h+='
Chưa có bình luận
';}h+=`
`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;} -async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);/* Keep focus on input after submit */var inp2=document.getElementById('cmt-input-'+idx);if(inp2)inp2.focus();} -function toggle169View(videoId,iconId){const slide=videoId?document.querySelector(`.tiktok-slide[data-vid="${videoId}"]`):null;if(slide){slide.classList.toggle('ratio-wide');const iconEl=iconId?document.getElementById(iconId):null;if(iconEl)iconEl.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';else{const btn=slide.querySelector('.tiktok-right-btn .icon');if(btn)btn.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';}return}document.querySelectorAll('.tiktok-slide.ratio-wide').forEach(s=>s.classList.remove('ratio-wide'));document.querySelectorAll('.tiktok-slide').forEach(s=>s.classList.add('ratio-wide'));document.querySelectorAll('.tiktok-right-btn .icon').forEach(b=>{if(b.textContent==='🖥️')b.textContent='📺';})} -function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){sl._active=true;if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc){fr.src=fr.dataset.ytSrc;const tw=fr.closest('.yt-thumb-wrap');if(tw)tw.style.backgroundImage='none'}const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{sl._active=false;if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const g=sl.querySelector('.slide-gesture');const v=sl.querySelector('video');const fr=sl.querySelector('iframe');const tapFn=e=>{if(g&&e.target!==g)return;if(v){e.preventDefault();if(e.detail>2)return;v.paused?v.play().catch(()=>{}):v.pause()}else if(fr&&fr.dataset.ytSrc&&sl._active){const src=fr.dataset.ytSrc;if(/tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com|youtube\.com\/embed/.test(src)){window.open(src.replace(/&/g,'&'),'_blank')}}};if(g)g.addEventListener('click',tapFn);if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids)} -async function openHighlightFeed(league,idx,link,forceUrl){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}catch(e){articles=[]}}if(!articles.length){el.innerHTML='
Không có video
';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link)+'&img='+encodeURIComponent(a.img||''));const v=await r.json();if(v&&v.src){return{_idx:i,title:a.title||v.title||'',link:a.link||'',img:a.img||v.poster||'',src:v.src,type:v.type||'',poster:v.poster||a.img||''}}return null}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='
Không tìm thấy video
';return}let ti=-1;if(link){ti=vids.findIndex(v=>(v.link||'')===(link||''));}if(ti<0)ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`
`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${esc(v.poster)}"`:'';const vtag=isYT?`
`:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;const nv=(i+1)%ordered.length;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',postId:'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -async function openYTShortsFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đã xóa Shorts Dân trí/SKĐS
';} -async function openShortAIFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');if(!_wallPosts||!_wallPosts.length){el.innerHTML='
Không có Short AI
';return}const aiPosts=_wallPosts.filter(p=>p.video);if(!aiPosts.length||idx>=aiPosts.length){el.innerHTML='
Không có Short AI
';return}const ordered=aiPosts.slice(idx).concat(aiPosts.slice(0,idx));let h=`
`;ordered.forEach((p,i)=>{const baseIdx=_wallPosts.indexOf(p);const isYT=/youtube\.com\/embed|youtu\.be\/|youtube-nocookie|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(p.video||'');const vtag=p.video?isYT?`
`:``:'';h+=buildTikTokSlide({vtag,title:p.title,badge:'Short AI',badgeClass:'badge-ai',videoId:p.id||'ai-'+i,idx:i,total:ordered.length,shareUrl:p.video||'',postId:p.id||'',desc:(p.text&&p.text!==p.title?p.text:'').slice(0,400),extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -function readWallPost(idx){const p=_wallPosts&&_wallPosts[idx];if(!p)return;if(p.slides&&p.slides.length){readSlidePost(idx);return}const isEmb=p.embed_oembed||/(tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|youtube\.com\/embed|platform\.twitter\.com|player\.vimeo\.com)/.test(p.video||'');if(isEmb||(p.video&&p.video.indexOf('/api/ai/short-file/')===0&&!p.url)){openShortAIFeed(_wallPosts.filter(x=>x.video).indexOf(p));return}readArticle(p.url||'','','',p.title,p.text);} -/** Show rewrite slide viewer - vertical slides with text+image */ -function readSlidePost(idx){const p=_wallPosts[idx];if(!p||!p.slides)return;showView('view-article');const el=document.getElementById('view-article');let h=`
`;p.slides.forEach((s,i)=>{h+=`
Slide ${s.index||i+1}/${p.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
`;el.innerHTML=h;} - -/** Slide Designer Modal - design a slide image with high-contrast text on background */ -function designerGetRatio(){const v=document.getElementById('designer-ratio')?.value||'3:4';const m=v.split(':');return m.length===2?{w:parseInt(m[0]),h:parseInt(m[1])}:1;} -function designerGetLayout(){return document.getElementById('designer-layout')?.value||'solid';} -function designerDebounce(fn,d){clearTimeout(fn._t);fn._t=setTimeout(fn,d);} -function openSlideDesigner(idx){ - designerSlideIdx=idx; - const p=_wallPosts[idx];if(!p||!p.slides)return; - const overlay=document.createElement('div');overlay.id='slide-designer-overlay';overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00'].forEach(c=>{h+=``;}); - h+='
'; - h+='
'; - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h;document.body.appendChild(overlay); - document.getElementById('designer-slide-select').addEventListener('change',function(){updateDesignerText(this.value);previewDesignerSlide();}); - document.getElementById('designer-preview-btn').addEventListener('click',function(){previewDesignerSlide();}); - document.getElementById('designer-save-btn').addEventListener('click',function(){saveDesignerSlide(p.title,(p.id||''),idx);}); - ['change','input'].forEach(function(evt){ - const txt=document.getElementById('designer-text');if(txt)txt.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const bg=document.getElementById('designer-bg-url');if(bg)bg.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const ratio=document.getElementById('designer-ratio');if(ratio)ratio.addEventListener(evt,function(){previewDesignerSlide();}); - const layout=document.getElementById('designer-layout');if(layout)layout.addEventListener(evt,function(){previewDesignerSlide();}); - }); - previewDesignerSlide(); -} -function updateDesignerText(slideIdx){const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return;const s=p.slides[parseInt(slideIdx)];if(s)document.getElementById('designer-text').value=s.text||'';document.getElementById('designer-bg-url').value=s.image||p.img||'';designerBgDataUrl=null;} -function handleDesignerBgFile(input){ - const file=input.files&&input.files[0];if(!file)return; - const reader=new FileReader(); - reader.onload=function(e){designerBgDataUrl=e.target.result;document.getElementById('designer-bg-url').value='[uploaded]';}; - reader.readAsDataURL(file); -} -function previewDesignerSlide(){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const previewArea=document.getElementById('designer-preview-area');if(!previewArea)return; - previewArea.style.display='block';previewArea.innerHTML='
⏳ Đang tạo xem trưởng...
'; - const canvas=document.createElement('canvas'); - const vw=Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540); - const maxW=Math.min(540, Math.floor(vw*0.9)); - canvas.width=maxW;canvas.height=Math.round(maxW*ratio.h/ratio.w); - canvas.style.maxWidth='100%';canvas.style.width='100%';canvas.style.height='auto'; - canvas.style.borderRadius='12px';canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; - canvas.style.display='block';canvas.style.margin='0 auto'; - const ctx=canvas.getContext('2d');const img=new Image();img.crossOrigin='anonymous'; - function drawLayout(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(canvas.width/2,canvas.height/2,0,canvas.width/2,canvas.height/2,Math.max(canvas.width,canvas.height)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,canvas.width,canvas.height);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,canvas.width,canvas.height/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,canvas.height/2,canvas.width,canvas.height/2);} - else if(layout==='spotlight'){const cx=canvas.width/2,cy=canvas.height/2,r=Math.max(canvas.width,canvas.height)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(canvas.width,0);ctx.lineTo(0,canvas.height);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);} - } - function drawText(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(canvas.width*28/540)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(canvas.width*0.82); - const words=text.split(' ');let line='';let y=Math.round(canvas.height/2); - const fontSize=Math.round(canvas.width*28/540);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),canvas.width/2,y);y+=lineHeight;line=words[i];}else{line=test;}} - ctx.fillText(line.trim(),canvas.width/2,y); - } - function renderAll(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,canvas.width,canvas.height); - drawLayout(); - drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(canvas.width/iw,canvas.height/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(canvas.width-dw)/2,dy=(canvas.height-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayout();drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - }; - img.onerror=function(){renderAll();}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{renderAll();} -} -async function saveDesignerSlide(title,postId,idx){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[idx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const statusEl=document.getElementById('designer-status');if(statusEl)statusEl.textContent='⏳ Đang tạo ảnh...'; - const FINAL_W=ratio.w>=ratio.h?1800:1350; - const FINAL_H=Math.round(FINAL_W*ratio.h/ratio.w); - const canvas=document.createElement('canvas');canvas.width=FINAL_W;canvas.height=FINAL_H; - const ctx=canvas.getContext('2d'); - const img=new Image();img.crossOrigin='anonymous'; - function drawLayoutF(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(FINAL_W/2,FINAL_H/2,0,FINAL_W/2,FINAL_H/2,Math.max(FINAL_W,FINAL_H)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,FINAL_W,FINAL_H);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,FINAL_W,FINAL_H/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,FINAL_H/2,FINAL_W,FINAL_H/2);} - else if(layout==='spotlight'){const cx=FINAL_W/2,cy=FINAL_H/2,r=Math.max(FINAL_W,FINAL_H)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(FINAL_W,0);ctx.lineTo(0,FINAL_H);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);} - } - function drawTextF(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(FINAL_W*48/1080)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(FINAL_W*0.82);const words=text.split(' ');let line='';let y=Math.round(FINAL_H/2); - const fontSize=Math.round(FINAL_W*48/1080);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),FINAL_W/2,y);y+=lineHeight;line=words[i];}else{line=test;}}ctx.fillText(line.trim(),FINAL_W/2,y); - } - function render(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(FINAL_W/iw,FINAL_H/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(FINAL_W-dw)/2,dy=(FINAL_H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - }; - img.onerror=function(){if(statusEl)statusEl.textContent='⚠️ Không tải được ảnh nền, dùng nền mặc định';ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H);drawLayoutF();drawTextF();canvas.toBlob(function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - fetch('/api/wall/img',{method:'POST',body:formData}).then(r=>r.json()).then(j=>{ - if(j.ok){s.image=j.url;const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}).then(r=>r.json()).then(wj=>{if(wj.post)prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');document.getElementById('slide-designer-overlay').remove();});} - }).catch(e=>{if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);}); - },'image/png');}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{render();} -} - -function readNewsTab(tab){loadNewsTab();} -function loadNewsTab(){const el=document.getElementById('view-cat');if(!el)return;el.innerHTML='
Đang tải tin tức...
';fetch('/api/homepage').then(r=>r.json()).then(articles=>{if(!articles||!articles.length){el.innerHTML='
Không có tin
';return}let h='
';articles.forEach(a=>{const src=a.source||'vne';const badge=a.group||a.source||'';h+=`
${a.img?``:''}
${esc(badge)}
${esc(a.title)}
`;});h+='
';el.innerHTML=h;}).catch(()=>{el.innerHTML='
Lỗi tải
';});} - -function readArticle(url,title,img,presetTitle,presetText){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';if(presetTitle){el.innerHTML=`

${esc(presetTitle)}

${presetText?`
${esc(presetText)}
`:''}
`;return;}if(!url)return;fetch('/api/article?url='+encodeURIComponent(url)).then(r=>r.json()).then(d=>{let h=`
`;if(d.title)h+=`

${esc(d.title)}

`;if(d.summary)h+=`
${esc(d.summary)}
`;if(d.body)d.body.forEach(b=>{if(b.type==='p')h+=`

${esc(b.text)}

`;else if(b.type==='heading')h+=`

${esc(b.text)}

`;else if(b.type==='img'&&b.src)h+=``;});h+=`
`;el.innerHTML=h;}).catch(()=>{el.innerHTML=`

Không thể tải bài viết

`;});} -async function rewriteSlide(url){if(!url)return;const btn=document.querySelector('.article-actions .primary')||event?.target;if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo slides...';}toast('⏳ Đang tạo slide rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã tạo slide! Đang tạo Short AI...');if(btn)btn.textContent='✅ Đang tạo Short AI...';if(j.post){j.post.slides=j.slides||[];prependWallPost(j.post);}// Show slides immediately if available -if(j.slides && j.slides.length){showView('view-article');const el=document.getElementById('view-article');let h=`
`;j.slides.forEach(s=>{h+=`
Slide ${s.index}/${j.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
⏳ Đang tạo video Short AI...
`;el.innerHTML=h;} -const postId=j.post&&j.post.id;if(postId){setTimeout(async()=>{const sr=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'vi-VN-HoaiMyNeural',emotion:'neutral',speed:1.2})});const sj=await sr.json();if(sr.ok&&sj.video&&typeof _wallPosts!=='undefined'){const p=_wallPosts.find(x=>String(x.id)===String(postId));if(p){p.video=sj.video;const itemId='wall-item-'+postId;const el2=document.getElementById(itemId);if(el2){const idx=_wallPosts.indexOf(p);el2.insertAdjacentHTML('afterend',makeWallItem(p,idx));el2.remove();}}toast('✅ Short AI đã sẵn sàng!');const statusEl=document.getElementById('short-ai-status');if(statusEl)statusEl.innerHTML='✅ Short AI đẵn sàng! ';}},500);}if(btn)btn.textContent='✅ Hoàn tất';}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Slide Rewrite AI';}}} - -function downloadVideo(url, title){ - var a = document.createElement('a'); - a.href = url; - a.download = (title||'video').toString().replace(/[^a-zA-Z0-9_\-\p{L}]/gu,'_').substring(0,60)+'.mp4'; - a.target = '_blank'; - a.rel = 'noopener'; - a.style.display = 'none'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - toast('📥 Đang tải video xuống...'); -} - -// ===== PERSONAL OPINION POST: Viết bài dựa trên quan điểm cá nhân + tin HOT ===== -async function openPersonalPostPreview() { - const opinion = document.getElementById('opinion-input')?.value.trim(); - if (!opinion || opinion.length < 10) { - alert('Vui lòng nhập quan điểm cá nhân (ít nhất 10 ký tự)'); - return; - } - - // Get selected hot topics from UI (if any) - const selectedTopics = []; - if (window._htTopic) { - selectedTopics.push(window._htTopic); - } - - // Get selected sources from hashtag view - const selectedSources = []; - document.querySelectorAll('.hashtag-src-item.selected').forEach(el => { - const idx = parseInt(el.dataset.idx || '0'); - // Would need source tracking - }); - - const btn = event?.target; - const origText = btn ? btn.textContent : ''; - if (btn) { btn.disabled = true; btn.textContent = '⏳ Đang tạo preview...'; } - - try { - const resp = await fetch('/api/personal_post/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: opinion, - selected_topics: selectedTopics, - selected_sources: selectedSources - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi tạo preview'); - - showPersonalPostModal(data.preview, opinion, selectedTopics, selectedSources); - } catch (e) { - toast('❌ ' + e.message); - } finally { - if (btn) { btn.disabled = false; btn.textContent = origText; } - } -} - -function showPersonalPostModal(preview, originalOpinion, selectedTopics, selectedSources) { - // Remove existing modal - const existing = document.getElementById('personal-post-modal'); - if (existing) existing.remove(); - - const modal = document.createElement('div'); - modal.id = 'personal-post-modal'; - modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - - // Each slide renders EXACTLY like the designer's final PNG (same ratio, - // same bg draw, same text draw) — preview = pixel-identical to wall post image. - const slidesHtml = (preview.slides || []).map((s, i) => { - const ratio = {w:3, h:4}; // preview always 3:4 (same as designer final) - const slideStyle = 'width:100%;max-width:280px;margin:0 auto;display:block;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.5)'; - return '
' - + '
Slide ' + (i+1) + '
' - + '' - + '' - + '
'; - }).join(''); - - // Background image source: uploaded data-URL (set later) or slide.image / first source image. - // We keep a small state object so text edits re-render live. - window._pvState = { slides: (preview.slides||[]).map(function(s,i){ - var bg = s.image || (preview.images && preview.images[0]) || ''; - return { text: s.text||'', bg: bg }; - }), ratio: 3/4, layout: 'solid', filter: 'none', glow: 'white', pos: 'bottom', color: '#ffffff' }; - - const sourcesHtml = (preview.sources || []).map((s, i) => { - const imgSrc = (preview.images && preview.images[i+1]) ? preview.images[i+1] : ''; - return '
' - + '
' - + (imgSrc ? '' : '') - + '
' - + '
' + (s.title || '') + '
' - + '' - + '
'; - }).join(''); - - modal.innerHTML = '
' - + '
' - + '

📝 Xem trước bài quan điểm cá nhân

' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '
' - + '' - + '' - + '
' - + '
' + slidesHtml + '
' - + '
' - + '
' - + '' - + '
' - + (sourcesHtml || '
Không có nguồn tin
') - + '
' - + '
' - + '' - + '' - + '
'; - - document.body.appendChild(modal); - - // draw every slide preview canvas - previewRedrawAllSlides(); - - // text edits re-render live - modal.querySelectorAll('.preview-slide-text').forEach(ta => { - ta.addEventListener('input', function(){ - const idx = parseInt(this.dataset.idx || '0', 10); - if(window._pvState && window._pvState.slides[idx]) window._pvState.slides[idx].text = this.value; - previewDrawSlide(idx); - }); - }); - - // Store preview data for publishing - window._personalPostPreview = preview; - window._personalPostOpinion = originalOpinion; -} - -/* Live-edit slide preview canvas (exact same rendering style as designer output) */ -function previewDrawSlide(idx){ - const canvas = document.querySelector('.preview-slide-canvas[data-idx="'+idx+'"]'); - if(!canvas || !window._pvState) return; - const st = window._pvState.slides[idx]; - if(!st) return; - const W = 600, H = Math.round(W * window._pvState.ratio); // 3:4 -> 800 - canvas.width = W; canvas.height = H; - const ctx = canvas.getContext('2d'); - const opts = { text: st.text, pos: window._pvState.pos, glow: window._pvState.glow, - color: window._pvState.color, layout: window._pvState.layout, - filter: window._pvState.filter, bgUrl: st.bg }; - function draw(img){ - // base dark - ctx.fillStyle='#141414'; ctx.fillRect(0,0,W,H); - if(img){ - ctx.save(); - let f=''; - if(opts.filter==='grayscale') f='grayscale(1)'; - else if(opts.filter==='sepia') f='sepia(0.85)'; - else if(opts.filter==='saturate') f='saturate(2.4)'; - else if(opts.filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(opts.filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(opts.filter==='invert') f='invert(1)'; - else if(opts.filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - ctx.drawImage(img,0,0,iw,ih,(W-dw)/2,(H-dh)/2,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // solid overlay like designer - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - drawPreviewText(ctx,W,H,opts); - } - const bgSrc = (typeof _proxyImg==='function') ? _proxyImg(st.bg||'') : (st.bg || ''); - if(bgSrc){ - const im = new Image(); im.crossOrigin='anonymous'; - im.onload = function(){ draw(im); }; - im.onerror = function(){ draw(null); }; - im.src = bgSrc; - } else draw(null); -} -function drawPreviewText(ctx,W,H,opts){ - const text = opts.text || ''; - if(!text.trim()) return; - const fs = Math.min(52, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } +async function toggleComments(videoId,idx){const panel=document.getElementById('cmt-inline-'+idx);if(!panel)return;if(panel.style.display!=='none'){panel.style.display='none';return;}panel.style.display='block';panel.innerHTML='
Đang tải...
';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);} +function renderInlineComments(panel,videoId,idx,cmts){let h='
💬 Bình luận
';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`
${c.time||''}${esc(c.text)}
`;});}else{h+='
Chưa có bình luận
';}h+=`
`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;} +async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);} +function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const v=sl.querySelector('video');if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids)} +async function openHighlightFeed(league,idx,forceUrl){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}catch(e){articles=[]}}if(!articles.length){el.innerHTML='
Không có video
';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link));const v=await r.json();if(v&&v.src)return{...a,...v,_idx:i}}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='
Không tìm thấy video
';return}let ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`
`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${v.poster}"`:'';const vtag=isYT?``:isHLS?``:``;const videoId='hl-'+league+'-'+(v.id||v._idx);h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',extraBtn:``});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function openYTShortsFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const arts=_shortsData.length?_shortsData:await fetch('/api/shorts').then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='
Không có shorts
';return}const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;let h=`
`;ordered.forEach((v,i)=>{const id=v.id||'';const src=`https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;const vtag=``;const badge=v.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';const videoId='yt-'+id;h+=buildTikTokSlide({vtag,title:v.title,badge,badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:'https://youtube.com/watch?v='+id});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function openShortAIFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const wall=(await fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];const vids=wall.filter(p=>p.video);if(!vids.length){el.innerHTML='
Chưa có Short AI
';return}const ordered=startIdx>0?[...vids.slice(startIdx),...vids.slice(0,startIdx)]:vids;let h=`
`;ordered.forEach((p,i)=>{const vtag=``;const videoId='ai-'+(p.id||i);h+=buildTikTokSlide({vtag,title:p.title,badge:'AI',badgeClass:'badge-ai',videoId,idx:i,total:ordered.length,shareUrl:SPACE});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function readArticle(url){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/article?url='+encodeURIComponent(url));const data=await r.json();if(data&&!data.error&&data.body&&data.body.length){_currentArticle={url,data};let h=`

${esc(data.title)}

`;if(data.summary)h+=`
${esc(data.summary)}
`;const seen={};data.body.forEach(b=>{if(b.type==='p')h+=`

${b.text}

`;else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+=``}else if(b.type==='heading')h+=`

${esc(b.text)}

`});h+=`

🤖 Hỏi AI

`;el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}el.innerHTML=`

Không đọc được.

Mở gốc →
`;} +async function rewriteArticle(){const url=_currentArticle?.url;if(!url)return;toast('⏳ Đang rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,context:document.querySelector('.article-view')?.innerText?.slice(0,14000)||''})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng Tường AI!');if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message)}} +async function rewriteUrl(){const url=document.getElementById('url-input')?.value.trim();if(!url)return alert('Dán URL');toast('⏳ Đang rewrite...');try{const r=await fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng!');document.getElementById('url-input').value='';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message)}} +async function askAI(){const q=document.getElementById('ask-q')?.value.trim();if(!q)return alert('Nhập câu hỏi');const a=document.getElementById('ask-a');a.textContent='Đang hỏi...';try{const r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:_currentArticle?.url||'',question:q,context:document.querySelector('.article-view')?.innerText?.slice(0,12000)||''})});const j=await r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}} +async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article'); + const images = p.images || []; + let imgGallery = ''; + if(images.length > 0){ + imgGallery = '
'; + images.forEach((imgUrl, imgIdx) => { + if(imgIdx === 0){ + imgGallery += ``; + } else { + if(imgIdx === 1) imgGallery += ''; + imgGallery += '
'; + } + const hasVideo = p.video && p.video.length > 0; + const voiceOptions = [ + {id:'hoaimy', label:'🎙️ Nữ — Hoài My'}, + {id:'namminh', label:'🎙️ Nam — Nam Minh'}, + ]; + let voiceSelector = ''; + if(!hasVideo){ + voiceSelector = `
🎙️ Chọn giọng đọc:
`; + voiceOptions.forEach(v=>{ + voiceSelector += ``; }); - const fakePost = { - id: 'preview-fake', title: document.getElementById('preview-title')?.value || 'Bài quan điểm', - slides: slides, kind: 'personal_opinion', img: slides[0]?.image||'', url: '', video: '' - }; - if(typeof openSlideDesigner === 'function'){ - // designer expects index into _wallPosts; temporarily append so designer works - const existed = _wallPosts && _wallPosts.some(p => p.id === 'preview-fake'); - if(!existed && Array.isArray(_wallPosts)) _wallPosts.unshift(fakePost); - const idx = _wallPosts.findIndex(p => p.id === 'preview-fake'); - openSlideDesigner(idx >= 0 ? idx : 0); - // the fake post is only a designer context; the designer's own save posts - // the designed slides directly to the wall. Remove the fake entry on close. + voiceSelector += `
Tốc độ:
`; + voiceSelector += `
`; + } + document.getElementById('view-article').innerHTML=`
AI

${esc(p.title)}

${imgGallery}

${esc(p.text)}

${hasVideo?``:''}
${hasVideo?`${voiceSelector}`:`${voiceSelector}`}
`; + const firstVoiceBtn = document.querySelector('.tts-voice-btn'); + if(firstVoiceBtn) firstVoiceBtn.classList.add('active'); + window.scrollTo(0,0)} +async function loadNewsTab(){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/homepage');const news=await r.json();if(!news.length){el.innerHTML='
Không có tin
';return}const groups={};news.forEach(a=>{if(!groups[a.group])groups[a.group]=[];groups[a.group].push(a)});let h='';for(const[g,arts]of Object.entries(groups)){h+=`
${g}
`;arts.slice(0,6).forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'VnE')}
${esc(a.title)}
`});h+='
'}el.innerHTML=h}catch(e){el.innerHTML='
Lỗi
'}} +async function loadCat(id){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';const arts=await fetch('/api/category/'+id).then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='
Không có tin
';return}let h='
';arts.forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'')}
${esc(a.title)}
`});h+='
';el.innerHTML=h} +fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){const home=document.getElementById('view-home');if(home){const w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ Persistent Storage chưa bật.';home.prepend(w)}}}).catch(()=>{}); + +(function(){ + try{ + var hash = window.location.hash; + if(hash && hash.length > 1){ + var articleUrl = decodeURIComponent(hash.substring(1)); + if(articleUrl.startsWith('http')){ + history.replaceState(null, '', window.location.pathname); setTimeout(function(){ - const ov = document.getElementById('slide-designer-overlay'); - if(!ov && Array.isArray(_wallPosts)){ - _wallPosts = _wallPosts.filter(p => p.id !== 'preview-fake'); - } - }, 30000); - } else { - toast('Không có công cụ thiết kế!'); - } -} - -function toggleSourceSelection(el, idx) { - const checkbox = el.querySelector('.source-checkbox'); - checkbox.checked = !checkbox.checked; - el.style.border = checkbox.checked ? '1px solid #2d8659' : '1px solid transparent'; - el.style.background = checkbox.checked ? '#1a2a1f' : '#202020'; -} - -async function publishPersonalPostFromModal() { - const title = document.getElementById('preview-title')?.value.trim(); - if (!title) { - alert('Vui lòng nhập tiêu đề'); - return; - } - - // Collect edited slides (text + designed/bg image from _pvState) - const slides = []; - if (window._pvState && window._pvState.slides) { - window._pvState.slides.forEach((s, i) => { - const text = (s.text || '').trim(); - if (text) slides.push({ text, image: s.bg || '', index: slides.length + 1 }); - }); - } else { - document.querySelectorAll('.preview-slide-text').forEach(ta => { - const text = ta.value.trim(); - if (text) slides.push({ text, image: '', index: slides.length + 1 }); - }); - } - - // Collect selected sources - const sources = []; - document.querySelectorAll('[data-source-idx]').forEach((el, i) => { - const checkbox = el.querySelector('.source-checkbox'); - if (checkbox.checked && window._personalPostPreview?.sources?.[i]) { - sources.push(window._personalPostPreview.sources[i]); - } - }); - - const btn = event.target; - const origText = btn.textContent; - btn.disabled = true; - btn.textContent = '⏳ Đang đăng...'; - - try { - const resp = await fetch('/api/personal_post', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: window._personalPostOpinion, - selected_topics: [], - selected_sources: sources, - custom_title: title, - custom_slides: slides - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi đăng bài'); - - toast('✅ Đã đăng bài quan điểm lên Tường AI!'); - - // Prepend to wall - if (data.post && typeof prependWallPost === 'function') { - prependWallPost(data.post); - } - - // Close modal - document.getElementById('personal-post-modal')?.remove(); - - // Clear opinion input - document.getElementById('opinion-input').value = ''; - } catch (e) { - toast('❌ ' + e.message); - } finally { - btn.disabled = false; - btn.textContent = origText; + if(typeof readArticle==='function') readArticle(articleUrl); + }, 1500); + } } -} - -// === M3U IPTV Player === -var _m3uChannels = []; -var _m3uFiltered = []; -var _m3uPage = 0; -var _m3uPageSize = 24; // lazy-load 24 kênh mỗi trang để tránh treo tab - -function _setM3UFallback(imgEl){ - // Called via onerror when a channel logo fails to load. Replaces it - // with a generated SVG fallback based on the channel's group-title. - // ch.group is stored in the closure via the card's dataset. - try{ - var card = imgEl.closest('.m3u-channel-card'); - var group = (card && card.dataset.group) || ''; - imgEl.src = '/api/m3u/logo_fallback?group=' + encodeURIComponent(group) + '&__t=' + Date.now(); }catch(e){} -} +})(); -async function loadM3UChannels(){ - var el = document.getElementById('view-m3u'); - if(!el) return; - el.innerHTML = '
Đang tải danh sách kênh trực tiếp...
'; +(function(){ try{ - var controller = new AbortController(); - var timeout = setTimeout(function(){ controller.abort(); }, 15000); - var r = await fetch('/api/m3u/channels', {signal: controller.signal}); - clearTimeout(timeout); - var j = await r.json(); - _m3uChannels = j.channels || []; - }catch(e){ - el.innerHTML = '
Lỗi tải kênh: '+esc(e.message||e)+'
'; - return; - } - if(!_m3uChannels.length){ - el.innerHTML = '
Không có kênh nào
'; - return; - } - _m3uFiltered = _m3uChannels.slice(); - _m3uPage = 0; - _renderM3UGrid(); -} - -function _renderM3UGrid(){ - var el = document.getElementById('view-m3u'); - if(!el) return; - var start = _m3uPage * _m3uPageSize; - var pageChannels = _m3uFiltered.slice(start, start + _m3uPageSize); - if(_m3uPage === 0){ - var html = ''; - html += ''; - html += '
'; - html += '
Xem thêm
'; - el.innerHTML = html; - } - var grid = document.getElementById('m3u-grid'); - if(!grid) return; - var fragment = document.createDocumentFragment(); - pageChannels.forEach(function(ch){ - var idx = _m3uFiltered.indexOf(ch); - var logo = ch.logo || ''; - var imgTag = logo ? '' : ''; - var title = (ch.title || 'Kênh').replace(/\s{2,}/g, ' ').trim(); - var card = document.createElement('div'); - card.className = 'm3u-channel-card'; - card.dataset.group = (ch.group || ''); - card.onclick = function(){ openM3UPlayer(idx); }; - card.title = title; - card.innerHTML = '
'+imgTag+'
' - + '
'+esc(title)+'
'; - fragment.appendChild(card); - }); - grid.appendChild(fragment); - var moreBtn = document.getElementById('m3u-loadmore'); - if(moreBtn){ - moreBtn.style.display = (start + _m3uPageSize >= _m3uFiltered.length) ? 'none' : 'block'; - } -} - -function loadMoreM3U(){ - _m3uPage++; - _renderM3UGrid(); -} - -function filterM3UChannels(){ - var q = (document.getElementById('m3u-search') || {}).value || ''; - var qq = q.toLowerCase().trim(); - if(!qq){ - _m3uFiltered = _m3uChannels.slice(); - }else{ - _m3uFiltered = _m3uChannels.filter(function(c){ - return (c.title || '').toLowerCase().indexOf(qq) >= 0; - }); - } - _m3uPage = 0; - _renderM3UGrid(); -}async function openM3UPlayer(chIdx){ - var ch = _m3uChannels[chIdx]; - if(!ch) return; - var originalUrl = ch.url || ''; - if(!originalUrl) return toast('Không có link stream'); - // FIX: Force a fresh M3U refresh before playing so stalker play_tokens/ - // Authorization headers are not expired from the 3-min cache. Stalker tokens - // expire in ~3-7 min, and the old code reused cached URLs verbatim. - try{ - var rr = await fetch('/api/m3u/channels?refresh=1'); - var jj = await rr.json().catch(function(){return {};}); - if(jj.channels && jj.channels.length){ - _m3uChannels = jj.channels; - _m3uFiltered = _m3uChannels.slice(); - // FIX: re-resolve the clicked channel by URL after the refresh — the - // channel order may have shifted, so chIdx no longer points to the same - // channel. Find the fresh entry whose URL matches the one the user - // tapped, so we play the correct (and now-fresh-token) stream. - var found = -1; - for(var fi = 0; fi < _m3uChannels.length; fi++){ - if(_m3uChannels[fi].url === originalUrl){ found = fi; break; } - } - if(found >= 0) chIdx = found; + const pa=localStorage.getItem('pending_article'); + const pv=localStorage.getItem('pending_video'); + if(pa){ + localStorage.removeItem('pending_article'); + setTimeout(()=>{ + if(typeof readArticle==='function') readArticle(pa); + },1500); + } + if(pv){ + localStorage.removeItem('pending_video'); + try{ + const v=JSON.parse(pv); + if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500); + }catch(e){} } }catch(e){} - // Re-read channel from the (possibly refreshed) data in case it changed - ch = _m3uChannels[chIdx] || ch; - var streamUrl = (ch.url || originalUrl); - if(!streamUrl) return toast('Không có link stream'); - - // Build ordered list (clicked first) - var ordered = []; - for(var i = chIdx; i < _m3uChannels.length; i++) ordered.push(_m3uChannels[i]); - for(var i = 0; i < chIdx; i++) ordered.push(_m3uChannels[i]); +})(); - // Parse VLC opts for headers - var vlcopts = ch.vlcopts || {}; - var ua = vlcopts['http-user-agent'] || ''; - var cookie = ''; - var auth = ''; - if(vlcopts['http-cookie']){ - cookie = vlcopts['http-cookie']; - } - if(vlcopts['http-header']){ - // e.g. "Authorization: Bearer XXX" - auth = vlcopts['http-header'].replace(/^authorization:\s*/i, ''); - } - - // Proxy URL with stalker headers — use m3u_hls endpoint which wraps - // MPEG-TS streams into a proper HLS playlist so Hls.js can play them - var proxyUrl = '/api/proxy/m3u_hls?url=' + esc(streamUrl) + - (ua ? '&ua=' + esc(ua) : '') + - (cookie ? '&cookie=' + esc(cookie) : '') + - (auth ? '&auth=' + esc(auth) : ''); - - var h = ''; - h += '
'; - ordered.forEach(function(ch, i){ - var streamUrl = ch.url || ''; - var vopts = ch.vlcopts || {}; - var pua = vopts['http-user-agent'] || ''; - var pcookie = vopts['http-cookie'] || ''; - var pauth = vopts['http-header'] ? vopts['http-header'].replace(/^authorization:\s*/i, '') : ''; - var purl = '/api/proxy/m3u_hls?url=' + esc(streamUrl) + - (pua ? '&ua=' + esc(pua) : '') + - (pcookie ? '&cookie=' + esc(pcookie) : '') + - (pauth ? '&auth=' + esc(pauth) : ''); - var logo = ch.logo || ''; - var vtag = '
' - + '
'; - var title = (ch.title || 'Kênh').replace(/\s{2,}/g, ' ').trim(); - h += buildTikTokSlide({ - vtag: vtag, - title: title, - badge: 'LIVE', - badgeClass: 'badge-live', - videoId: 'm3u-' + i, - idx: i, - total: ordered.length, - shareUrl: streamUrl || location.href, - postId: '', - extraBtn: '' - }); +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', function() { + if (typeof loadHome === 'function') loadHome(); }); - h += '
'; - showView('view-tiktok'); - var el = document.getElementById('view-tiktok'); - if(el) el.innerHTML = h; - setTimeout(function(){ if(typeof initTikTokFeed === 'function') initTikTokFeed(); }, 200); +} else { + if (typeof loadHome === 'function') loadHome(); } - -function closeM3UViewer(){ - var feed = document.getElementById('tiktok-feed'); - if(feed){ feed.innerHTML = ''; } - document.querySelectorAll('video[data-hls]').forEach(function(v){ - if(v._hls){ v._hls.destroy(); v._hls = null; } - v.pause(); - v.src = ''; - }); - showView('view-m3u'); -} - -function copyStreamLink(idx){ - var ch = _m3uChannels[idx]; - if(!ch || !ch.url) return toast('Không có link stream'); - if(navigator.clipboard && navigator.clipboard.writeText){ - navigator.clipboard.writeText(ch.url).then(function(){ toast('📋 Đã sao chép link stream!'); }).catch(function(){ - prompt('📋 Link stream:', ch.url); - }); - }else{ - prompt('📋 Link stream:', ch.url); - } -} - -// M3U streams are MPEG-TS streams wrapped in HLS playlists via /api/proxy/m3u_hls. -// The data-hls attribute is handled by the existing initTikTokFeed Hls.js logic. -// No additional patch needed — initTikTokFeed already creates Hls.js instances -// for video[data-hls] elements when they become active. - diff --git a/static/app_v2_shorts_fix.js b/static/app_v2_shorts_fix.js index 488520ab2edc21927c2ef5b49f0839b01c13ff63..aa9eec6830b93514eb8b678862cffe1b390c18be 100644 --- a/static/app_v2_shorts_fix.js +++ b/static/app_v2_shorts_fix.js @@ -1,2 +1,383 @@ -// No-op - all functionality built into app_v2.js -(function(){})(); +// VNEWS Short AI Fix - Multilingual voices + emotion selector +// This file patches makeShortVideo and readWallPost to support full voice list + +(function(){ + // Full voice list + const VOICE_LIST = [ + {id:'hoaimy', label:'🎙️ Hoài My (VI)', lang:'vi'}, + {id:'namminh', label:'🎙️ Nam Minh (VI)', lang:'vi'}, + {id:'andrew', label:'🎙️ Andrew (Multilingual)', lang:'en'}, + {id:'jenny', label:'🎙️ Jenny (EN)', lang:'en'}, + {id:'thalita', label:'🎙️ Thalita (PT)', lang:'pt'}, + {id:'pt_francisco', label:'🎙️ Francisco (PT)', lang:'pt'}, + {id:'ela', label:'🎙️ Ela (ES)', lang:'es'}, + {id:'es_carlos', label:'🎙️ Carlos (ES)', lang:'es'}, + {id:'denise', label:'🎙️ Denise (FR)', lang:'fr'}, + {id:'katja', label:'🎙️ Katja (DE)', lang:'de'}, + {id:'nanami', label:'🎙️ Nanami (JA)', lang:'ja'}, + {id:'sunhee', label:'🎙️ SunHee (KO)', lang:'ko'}, + {id:'xiaochen', label:'🎙️ XiaoChen (ZH)', lang:'zh'}, + ]; + + const EMOTION_LIST = [ + {id:'neutral', label:'😐 Trung tính'}, + {id:'happy', label:'😊 Vui vẻ'}, + {id:'excited', label:'🔥 Hào hứng'}, + {id:'sad', label:'😢 Buồn'}, + {id:'humorous', label:'😂 Hài hước'}, + {id:'serious', label:'⚠️ Nghiêm túc'}, + {id:'urgent', label:'🚨 Khẩn cấp'}, + {id:'warm', label:'💖 Ấm áp'}, + ]; + + // Language detection (lightweight) + function detectLanguage(text) { + if (!text) return 'vi'; + var t = text.toLowerCase(); + var chars = new Set(t); + // Vietnamese + var vnChars = 'đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựỳỷỹỵý'; + var vnCount = 0; + for (var c of vnChars) { if (chars.has(c)) vnCount++; } + if (vnCount >= 2) return 'vi'; + + // Spanish markers + if (chars.has('ñ') || chars.has('¿') || chars.has('¡')) return 'es'; + + // Portuguese markers + if (chars.has('ã') || chars.has('õ')) return 'pt'; + + // English default + var words = t.split(/\s+/); + var enWords = ['the','is','at','which','on','and','or','but','this','that','with','from','have','been']; + var enCount = words.filter(function(w){return enWords.indexOf(w)>=0;}).length; + if (enCount >= 2) return 'en'; + + return 'vi'; + } + + // Auto-detect emotion + function detectEmotion(text) { + if (!text) return 'neutral'; + var t = text.toLowerCase(); + var kws = { + happy: ['vui','hạnh phúc','tuyệt','thành công','chiến thắng','feliz','maravilloso','happy','joy','wonderful','great','amazing','love','excellent'], + excited: ['hào hứng','phấn khích','đột phá','kỷ lục','đỉnh cao','emocionante','increíble','excited','thrilling','unbelievable','awesome','breakthrough'], + sad: ['buồn','đau','mất','thảm họa','khủng hoảng','triste','terrible','sad','unhappy','tragic','painful','death'], + humorous: ['hài hước','buồn cười','haha','đùa','engraçado','gracioso','funny','hilarious','joke','lol'], + serious: ['nghiêm trọng','khẩn cấp','quan trọng','lo ngại','sério','crítico','serious','critical','urgent','severe','crisis'], + urgent: ['khẩn cấp','báo động','ngay lập tức','urgent','breaking','alert','emergency'], + warm: ['ấm áp','tình cảm','yêu thương','warm','love','heart','touching','beautiful story'] + }; + var bestScore = 0; + var bestEmotion = 'neutral'; + for (var em in kws) { + var score = 0; + for (var kw of kws[em]) { + if (t.indexOf(kw) >= 0) score++; + } + if (score > bestScore) { bestScore = score; bestEmotion = em; } + } + return bestEmotion; + } + + // Auto-select voice based on language + function getAutoVoice(lang) { + var map = {vi:'hoaimy', pt:'thalita', es:'ela', en:'jenny', fr:'denise', de:'katja', ja:'nanami', ko:'sunhee', zh:'xiaochen'}; + return map[lang] || 'hoaimy'; + } + + // Build voice+emotion selector HTML + function buildVoiceEmotionSelector(post) { + var lang = post.language || detectLanguage(post.title + ' ' + post.text); + var autoVoice = post.voice || getAutoVoice(lang); + var autoEmotion = post.emotion || detectEmotion(post.title + ' ' + post.text); + + var h = '
'; + h += '
🎙️ Giọng đọc (ngôn ngữ: ' + lang.toUpperCase() + '):
'; + h += '
'; + VOICE_LIST.forEach(function(v){ + var sel = v.id === autoVoice ? 'border-color:#5cb87a;background:#1a2a1f' : 'border-color:#333;background:#222'; + h += ''; + }); + h += '
'; + h += '
😊 Cảm xúc:
'; + h += '
'; + EMOTION_LIST.forEach(function(e){ + var sel = e.id === autoEmotion ? 'border-color:#5cb87a;background:#1a2a1f' : 'border-color:#333;background:#222'; + h += ''; + }); + h += '
'; + h += '
⚡ Tốc độ:'; + h += '
'; + h += ''; + h += ''; + h += ''; + h += '
'; + return h; + } + + // Patch readWallPost to include full voice+emotion selector + var origReadWallPost = window.readWallPost; + window.readWallPost = function(i){ + var p = _wallPosts[i]; + if(!p) return; + showView('view-article'); + var images = p.images || []; + var imgGallery = ''; + if(images.length > 0){ + imgGallery = '
'; + images.slice(0,6).forEach(function(imgUrl){ + imgGallery += ''; + }); + imgGallery += '
'; + } + var hasVideo = p.video && p.video.length > 0; + var voiceEmotionHtml = ''; + if(!hasVideo){ + voiceEmotionHtml = buildVoiceEmotionSelector(p); + } else { + voiceEmotionHtml = '
🎬 Voice: ' + (p.voice||'hoaimy') + ' | 😊 Emotion: ' + (p.emotion||'neutral') + ' | ⚡ Speed: ' + (p.short_speed||'1.2') + 'x
'; + voiceEmotionHtml += buildVoiceEmotionSelector(p); + } + + document.getElementById('view-article').innerHTML = + '' + + '
AI

'+esc(p.title)+'

' + + imgGallery + + '

'+esc(p.text)+'

' + + (hasVideo ? '' : '') + + '
' + + (hasVideo ? '' : '') + + '
' + + voiceEmotionHtml + + '
'; + window.scrollTo(0,0); + + // Bind voice/emotion selectors + setTimeout(function(){ + var container = document.querySelector('.tts-selector'); + if(!container) return; + + container.querySelectorAll('.tts-voice-btn').forEach(function(btn){ + btn.addEventListener('click', function(){ + container.querySelectorAll('.tts-voice-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';}); + this.style.borderColor='#5cb87a'; + this.style.background='#1a2a1f'; + container.querySelector('.tts-selected-voice').value = this.dataset.voice; + }); + }); + container.querySelectorAll('.tts-emotion-btn').forEach(function(btn){ + btn.addEventListener('click', function(){ + container.querySelectorAll('.tts-emotion-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';}); + this.style.borderColor='#5cb87a'; + this.style.background='#1a2a1f'; + container.querySelector('.tts-selected-emotion').value = this.dataset.emotion; + }); + }); + var createBtn = container.querySelector('.tts-create-btn'); + if(createBtn){ + createBtn.addEventListener('click', function(){ + var postId = p.id; + var voice = container.querySelector('.tts-selected-voice').value; + var emotion = container.querySelector('.tts-selected-emotion').value; + var speed = parseFloat(container.querySelector('.tts-speed').value) || 1.2; + window.makeShortVideo(postId, this, voice, speed, emotion); + }); + } + }, 100); + }; + + // Patch makeShortVideo to accept emotion parameter + var origMakeShortVideo = window.makeShortVideo; + window.makeShortVideo = function(postId, btn, voice, speed, emotion){ + if(!postId) return; + var origText = btn ? btn.textContent : '🎬 Tạo Video'; + if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';} + toast('⏳ Đang tạo video shorts...'); + try{ + var url = '/api/ai/short/' + encodeURIComponent(postId); + var params = []; + if(voice) params.push('voice='+encodeURIComponent(voice)); + if(speed) params.push('speed='+encodeURIComponent(speed)); + if(emotion) params.push('emotion='+encodeURIComponent(emotion)); + if(params.length) url += '?' + params.join('&'); + + fetch(url, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({voice:voice||'hoaimy', emotion:emotion||'neutral', speed:speed||1.2})}) + .then(function(r){return r.json().then(function(j){return {ok:r.ok, j:j};});}) + .then(function(result){ + if(!result.ok || result.j.error) throw new Error(result.j.error||'Lỗi tạo video'); + toast('✅ Đã tạo video shorts!'); + var p = _wallPosts.find(function(x){return String(x.id)===String(postId);}); + if(p){ + p.video = result.j.video; + p.voice = result.j.voice; + p.emotion = result.j.emotion; + var itemId = 'wall-item-'+postId; + var el = document.getElementById(itemId); + if(el){ + var idx = _wallPosts.indexOf(p); + el.outerHTML = makeWallItem(p, idx); + var newEl = document.getElementById(itemId); + if(newEl) newEl.className = 'wall-item wall-item-new'; + } + } + refreshShortAISlider(); + }) + .catch(function(e){ + toast('❌ '+e.message); + if(btn){btn.disabled=false;btn.textContent=origText;} + }); + }catch(e){ + toast('❌ '+e.message); + if(btn){btn.disabled=false;btn.textContent=origText;} + } + }; + + // Also patch rewriteArticle in app_v2.js to use rewrite_share (not rewrite_slide) + window.rewriteArticle = async function(){ + var url = window._currentArticle && window._currentArticle.url; + if(!url) return; + toast('⏳ Đang tạo bài đăng Tường AI...'); + try { + var r = await fetch('/api/rewrite_share', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({url: url, context: document.querySelector('.article-view') ? document.querySelector('.article-view').innerText.slice(0,14000) : ''}) + }); + var j = await r.json(); + if (!r.ok || j.error) throw new Error(j.error); + toast('✅ Đã đăng Tường AI!'); + if (j.post) prependWallPost(j.post); + if (j.post && typeof goToWallPost === 'function') goToWallPost(j.post.id); + // Show slides if available + if (j.slides && j.slides.length) { + setTimeout(function(){ showSlidePreview(j.slides, j.post ? j.post.title : ''); }, 500); + } + // Show voice + emotion selector + if (j.post && !j.post.video) { + setTimeout(function(){ showVoiceEmotionSelector(j.post.id, j.post.title, j.post.text); }, 1000); + } + } catch(e) { + toast('❌ ' + e.message); + } + }; + + // Show voice+emotion selector popup (same as in rewrite_fix_v2.js) + window.showVoiceEmotionSelector = function(postId, title, text) { + var overlay = document.createElement('div'); + overlay.id = 'voice-emotion-selector'; + overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px'; + var box = document.createElement('div'); + box.style.cssText = 'background:#1a1a1a;border:2px solid #2d8659;border-radius:16px;padding:20px;max-width:400px;width:100%;max-height:80vh;overflow-y:auto'; + var lang = detectLanguage(title + ' ' + text); + var autoEmotion = detectEmotion(title + ' ' + text); + var h = '

🎬 Tạo Short AI (ngôn ngữ: '+lang.toUpperCase()+')

'; + h += '
🎙️ Chọn giọng đọc:
'; + VOICE_LIST.forEach(function(v){ + var sel = v.id === getAutoVoice(lang) ? 'border-color:#5cb87a;background:#1a2a1f' : 'border-color:#333;background:#222'; + h += ''; + }); + h += '
'; + h += '
😊 Chọn cảm xúc:
'; + EMOTION_LIST.forEach(function(e){ + var sel = e.id === autoEmotion ? 'border-color:#5cb87a;background:#1a2a1f' : 'border-color:#333;background:#222'; + h += ''; + }); + h += '
'; + h += '
⚡ Tốc độ:
'; + h += '
'; + h += '
'; + h += '
'; + h += ''; + box.innerHTML = h; + overlay.appendChild(box); + document.body.appendChild(overlay); + var selectedVoice = getAutoVoice(lang); + var selectedEmotion = autoEmotion; + box.querySelectorAll('.ve-voice-btn').forEach(function(btn){ + btn.addEventListener('click', function(){ + box.querySelectorAll('.ve-voice-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';}); + this.style.borderColor='#5cb87a';this.style.background='#1a2a1f'; + selectedVoice = this.dataset.voice; + }); + }); + box.querySelectorAll('.ve-emotion-btn').forEach(function(btn){ + btn.addEventListener('click', function(){ + box.querySelectorAll('.ve-emotion-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';}); + this.style.borderColor='#5cb87a';this.style.background='#1a2a1f'; + selectedEmotion = this.dataset.emotion; + }); + }); + box.querySelector('#ve-cancel-btn').addEventListener('click', function(){overlay.remove();}); + box.querySelector('#ve-create-btn').addEventListener('click', async function(){ + this.disabled = true; this.textContent = '⏳ Đang tạo...'; + box.querySelector('#ve-status').style.display = 'block'; + box.querySelector('#ve-status').textContent = 'Đang tạo video shorts...'; + try { + var speed = parseFloat(box.querySelector('#ve-speed').value) || 1.2; + var r = await fetch('/api/ai/short/' + encodeURIComponent(postId), { + method: 'POST', headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({voice: selectedVoice, emotion: selectedEmotion, speed: speed}) + }); + var j = await r.json(); + if (!r.ok || j.error) throw new Error(j.error || 'Lỗi tạo video'); + toast('✅ Đã tạo Short AI!'); + overlay.remove(); + var p = _wallPosts.find(function(x){return String(x.id)===String(postId);}); + if (p) { p.video = j.video; p.voice = j.voice; p.emotion = j.emotion; } + var track = document.getElementById('ai-wall-track'); + if (track) { + var idx = _wallPosts.findIndex(function(x){return String(x.id)===String(postId);}); + if (idx >= 0 && track.children[idx]) { + track.children[idx].outerHTML = makeWallItem(p, idx); + } + } + refreshShortAISlider(); + } catch(e) { + this.disabled = false; this.textContent = '🎬 Tạo Short'; + box.querySelector('#ve-status').textContent = '❌ ' + e.message; + } + }); + }; + + // Show slides fullscreen overlay + window.showSlidePreview = function(slides, title) { + if (!slides || !slides.length) return; + var overlay = document.createElement('div'); + overlay.id = 'slide-preview'; + overlay.style.cssText = 'position:fixed;inset:0;background:#000;z-index:99999;display:flex;flex-direction:column;overflow:hidden'; + var currentSlide = 0; + function renderSlide(idx) { + var s = slides[idx]; + overlay.innerHTML = '
' + + '' + + '' + (idx+1) + '/' + slides.length + '' + + '
' + + '
' + + (s.image ? '' : '') + + '
' + + '
' + + '

' + esc(s.text) + '

' + + '
' + + '
' + + '' + + '' + + '
'; + } + window.nextSlideRip = function(currentIdx) { if (currentIdx < slides.length - 1) { currentSlide = currentIdx + 1; renderSlide(currentSlide); } }; + window.prevSlide = function() { if (currentSlide > 0) { currentSlide--; renderSlide(currentSlide); } }; + renderSlide(0); + document.body.appendChild(overlay); + var startX = 0; + overlay.addEventListener('touchstart', function(e) { startX = e.touches[0].clientX; }); + overlay.addEventListener('touchend', function(e) { + var diff = e.changedTouches[0].clientX - startX; + if (diff < -50) nextSlideRip(currentSlide); + else if (diff > 50) prevSlide(); + }); + }; +})(); diff --git a/static/designer_v2.js b/static/designer_v2.js deleted file mode 100644 index 31ff59f42126dbbc350a4d7c94575b7083bdd2d6..0000000000000000000000000000000000000000 --- a/static/designer_v2.js +++ /dev/null @@ -1,903 +0,0 @@ -/* ========================================================================= - * designer_v2.js — Slide Designer nâng cấp cho VNEWS - * - Nhiều hiệu ứng độc đáo (gradient, blur, neon, top-banner, lower-third, - * card, corner-frame, stars, vignette, split, spotlight, diagonal, solid) - * - Bộ lọc màu (grayscale, sepia, saturate, warm, cool, invert) - * - Chữ phát sáng (neon/glow) - * - Vị trí chữ (trên/giữa/dưới) - * - Chọn 1 / nhiều / TẤT CẢ slide trong modal sửa ảnh - * - Đăng lên Tường AI là bài dạng slide gồm CÁC SLIDE ĐÃ CHỌN - * - * 2026-08-12 FIX (2 lỗi báo cáo): - * - Bug 1: upload ảnh preview + nút "Áp dụng ảnh". _dsHandleBgFile được gắn - * trực tiếp làm listener 'change' nên nhận Event object, `input.files` - * undefined -> upload im lặng không làm gì. Giờ đọc evt.target.files. - * Nút "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" luôn hiển thị. - * - Bug 2: chọn 1 ảnh rewrite áp dụng cho nhiều slide. Danh sách ảnh dùng - * data-index + delegated click (hết fragile inline onclick với URL thô). - * - * 2026-08-13 FIX (lỗi báo cáo tiếp): - * - Bug 3: "dùng 1 ảnh cho nhiều slide" vẫn chỉ áp dụng cho slide đầu. - * Giờ có _dsAppliedImg (ảnh đã áp dụng ở cấp thiết kế): khi chọn ảnh bất kỳ - * (rewrite / upload / URL) sẽ áp dụng cho TẤT CẢ slide đã chọn NGAY LẬP TỨC; - * khi đổi lựa chọn slide (chọn thêm / bỏ chọn / chọn tất cả) ảnh đó vẫn được - * áp dụng tự động cho các slide mới được chọn; khi lưu, mọi slide được chọn - * đều dùng ảnh đó. - * - Bug 4: ảnh preview hiển thị đúng tỉ lệ nhưng sau khi tạo ảnh xong hiển thị - * sai tỉ lệ + ảnh nền không định vị chính xác như preview. Preview và khi - * lưu giờ render Ở CÙNG một hàm `_dsRenderSlide(canvas, opts, cb)` (cùng - * resolution, cùng cover-fit, cùng filter, cùng text) nên file tạo ra khớp - * TUYỆT ĐỐI với preview. Ảnh trên Tường/slide viewer giữ đúng tỉ lệ khung - * (ko cắt xén bằng object-fit:cover nữa). - * - Thêm MÀU NỀN + nhiều ẢNH NỀN MẪU khi chọn "Nền đều (phủ màu tối)" — - * dải màu nền (solid color swatches) và bộ ảnh nền mẫu (gradient mờ) để - * người dùng tạo ảnh nền trơn thay vì chỉ phủ màu tối. - * ========================================================================= */ - -/* ---------------- state ---------------- */ -let _dsState = { - postIdx: -1, // index into _wallPosts - selected: [], // array of selected slide indices (into p.slides) -}; - -/* per-slide image override map: {si: imageUrl} set by the rewrite image list */ -let _dsImgMap = {}; - -/* srcs backing the rewrite image list (Bug 2 fix: index-based, no inline onclick) */ -let _dsRewriteImgSrcs = []; - -/* designer-level "applied image": the image the user picked (rewrite / upload / - URL). Applied to ALL selected slides, including slides selected LATER. - Bug 3 fix: keeps "1 ảnh cho nhiều slide" working when selection changes. */ -let _dsAppliedImg = ''; - -/* solid-color background for the 'solid' layout (map because _dsOptions reads it) */ -let _dsBgColor = ''; -/* sample background image (proxied URL) for the 'solid' layout */ -let _dsBgSample = ''; - -/* ---------------- ratio / layout helpers ---------------- */ -function designerGetRatioV2(){ - const v = document.getElementById('ds-ratio')?.value || '3:4'; - const m = v.split(':'); - return m.length === 2 ? {w: parseInt(m[0]), h: parseInt(m[1])} : {w:3,h:4}; -} -function designerGetLayoutV2(){ return document.getElementById('ds-layout')?.value || 'solid'; } -function designerGetFilterV2(){ return document.getElementById('ds-filter')?.value || 'none'; } -function designerGetGlowV2(){ return document.getElementById('ds-glow')?.value || 'none'; } -function designerGetPosV2(){ return document.getElementById('ds-pos')?.value || 'middle'; } - -/* ---------------- open modal (override) ---------------- */ -function openSlideDesigner(idx){ - const p = _wallPosts[idx]; if(!p || !p.slides || !p.slides.length) return; - _dsState.postIdx = idx; - // default: chỉ slide đầu tiên (slide 1 = ảnh đại diện bài đăng tường). - // Người dùng có thể chọn thêm bằng checkbox hoặc "Chọn tất cả". - _dsState.selected = p.slides.length ? [0] : []; - _dsBgDataUrl = null; // reset uploaded bg between opens - _dsTextColor = '#ffffff'; - _dsImgMode = 'rewrite'; // default: use rewrite image - _dsImgMap = {}; // reset per-slide image overrides - _dsRewriteImgSrcs = []; - _dsAppliedImg = ''; // reset designer-level applied image - _buildDesignerModal(p); -} - -function _buildDesignerModal(p){ - const overlay = document.createElement('div'); - overlay.id = 'slide-designer-overlay'; - overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.94);z-index:99999;display:flex;align-items:center;justify-content:center;padding:12px;overflow-y:auto'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - - /* ---- 1. Chọn slide (1 / nhiều / tất cả) ---- */ - h+='
'; - h+='
'; - h+=''; - h+=''; - h+='
'; - p.slides.forEach((s,i)=>{ - const preview = s.image ? `` : `
🖼️
`; - const isSel = _dsState.selected.includes(i); - h+=``; - }); - h+='
'; - - /* ---- 2. Nội dung từng slide đã chọn ---- */ - h+='
'; - - /* ---- 3. Cấu hình thiết kế ---- */ - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - - /* ---- 3b. Màu nền + ảnh nền mẫu (chỉ hiển thị khi chọn "Nền đều/solid") ---- */ - h+=''; - - /* ---- 4. Màu chữ + nền ---- */ - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00','#ffd700','#ff69b4'].forEach(c=>{h+=``;}); - h+='
'; - - /* ---- 5. Ảnh nền (source buttons + URL/upload) ---- */ - h+='
'; - h+='
'; - h+=''; - h+=''; - h+=''; - h+='
'; - /* URL + upload panel (only the URL/upload inputs collapse; apply button stays visible) */ - h+=''; - /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — ALWAYS visible (Bug 1 fix) */ - h+='
✓ Áp dụng để dùng 1 ảnh cho nhiều slide
'; - h+='
Ảnh tải lên/URL nhập từ ngoài (hoặc chọn từ danh sách dưới) sẽ thay thế ảnh bài rewrite và áp dụng cho TẤT CẢ slide đã chọn.
'; - h+=''; - h+='
'; - - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h; document.body.appendChild(overlay); - - /* button label update fn */ - window._dsUpdateSaveLabel = function(){ - const n = _dsState.selected.length; - const b = document.getElementById('ds-save-btn'); - if(b) b.textContent = '📤 Lưu & Đăng lên Tường AI ('+n+' slide)'; - }; - - /* ---- slide selection wiring ---- */ - overlay.querySelectorAll('.ds-slide-chk').forEach(chk=>{ - chk.addEventListener('change', _dsSyncSelection); - }); - document.getElementById('ds-sel-all').addEventListener('click', ()=>{ _setAllSelected(true); }); - document.getElementById('ds-sel-none').addEventListener('click', ()=>{ _setAllSelected(false); }); - document.getElementById('ds-slide-list').addEventListener('click', e=>{ - const lbl = e.target.closest('.ds-slide-chip'); - if(!lbl) return; - const chk = lbl.querySelector('.ds-slide-chk'); - if(e.target === chk) return; - chk.checked = !chk.checked; _dsSyncSelection(); - }); - - /* ---- inputs wiring ---- */ - document.getElementById('ds-preview-btn').addEventListener('click', _dsPreview); - document.getElementById('ds-save-btn').addEventListener('click', ()=>_dsSave(p)); - ['ds-texts','ds-ratio','ds-layout','ds-filter','ds-glow','ds-pos'].forEach(id=>{ - ['change','input'].forEach(evt=>{ - const el=document.getElementById(id); if(el) el.addEventListener(evt, ()=>_dsDebounce(_dsPreview, 150)); - }); - }); - // URL input: as user types a custom image URL, live-preview + apply to selected - const bgUrlInput=document.getElementById('ds-bg-url'); - if(bgUrlInput){ - bgUrlInput.addEventListener('input', ()=>{ - const v=bgUrlInput.value.trim(); - if(v && v.length>8){ - _dsSetImgMode('custom'); - const proxied=_dsImageSrc(v); - _dsAppliedImg = proxied; // Bug 3: applies to current + future selections - const sel=_dsState.selected; - if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=proxied; }); } - else { _dsImgMap[0]=proxied; } - } - _dsDebounce(_dsPreview,150); - }); - } - // Bug 1 fix: pass through the event; _dsHandleBgFile reads evt.target.files - document.getElementById('ds-bg-file').addEventListener('change', _dsHandleBgFile); - ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{ - const b=document.getElementById(id); - if(b) b.addEventListener('click', ()=>{ - _dsSetImgMode(id==='ds-img-src-rewrite'?'rewrite':id==='ds-img-src-custom'?'custom':'none'); - }); - }); - /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — always-visible apply button */ - const applyBtn=document.getElementById('ds-apply-img-btn'); - if(applyBtn){ - applyBtn.addEventListener('click', function(){ - let chosen = _dsBgDataUrl || (document.getElementById('ds-bg-url')?.value||''); - if(!chosen){ toast('⚠️ Chọn ảnh (tải lên hoặc nhập URL) trước khi áp dụng'); return; } - _dsSetImgMode('custom'); - let proxied = _dsImageSrc(chosen); - _dsAppliedImg = proxied; // Bug 3 fix - dsApplyImgToSelected(proxied); - }); - } - // Toggle the "nền trơn" (solid) color + sample-image panel when layout changes - const layoutSel=document.getElementById('ds-layout'); - if(layoutSel){ - const toggleSolidPanel=()=>{ - const wrap=document.getElementById('ds-bg-solid-wrap'); - if(wrap) wrap.style.display = layoutSel.value==='solid' ? 'block' : 'none'; - }; - layoutSel.addEventListener('change', toggleSolidPanel); - layoutSel.addEventListener('input', toggleSolidPanel); - toggleSolidPanel(); - } - // Solid background color swatches - const bgColorBox=document.getElementById('ds-bg-colors'); - if(bgColorBox){ - bgColorBox.addEventListener('click', e=>{ - const b=e.target.closest('.ds-bgcolor-btn'); if(!b) return; - document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#fff'; - _dsBgColor = b.dataset.color; - _dsBgSample = ''; // color takes precedence over sample image - document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333'); - _dsStatus('🎨 Đã chọn màu nền: '+_dsBgColor); - _dsDebounce(_dsPreview, 150); - }); - } - // Sample background images (only for solid layout) - const bgSampleBox=document.getElementById('ds-bg-samples'); - if(bgSampleBox){ - bgSampleBox.addEventListener('click', e=>{ - const b=e.target.closest('.ds-bgsample-btn'); if(!b) return; - const bi=parseInt(b.dataset.bi,10); - const src=_DS_BG_SAMPLES[bi]; - if(!src) return; - document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#ffd700'; - _dsBgSample = _dsImageSrc(src); - _dsBgColor = ''; // sample image takes precedence over color - document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333'); - _dsStatus('🖼️ Đã chọn ảnh nền mẫu'); - _dsDebounce(_dsPreview, 150); - }); - } - _syncImgModeBtns(); - _dsRefreshRewriteImgs(p); - document.getElementById('ds-colors').addEventListener('click', e=>{ - const b = e.target.closest('.ds-color-btn'); if(!b) return; - overlay.querySelectorAll('.ds-color-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#fff'; - _dsTextColor = b.dataset.color; - _dsDebounce(_dsPreview, 150); - }); - - _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsPreview(); -} - -/* ---------------- selection sync ---------------- */ -function _setAllSelected(on){ - _dsState.selected = []; - document.querySelectorAll('#ds-slide-list .ds-slide-chk').forEach(chk=>{ chk.checked = on; if(on) _dsState.selected.push(parseInt(chk.dataset.idx)); }); - // Bug 3 fix: if an image was already applied at designer level, push it to - // every slide that is (now) selected so "1 ảnh cho nhiều slide" also covers - // slides selected AFTER the image was picked. - if(on && _dsAppliedImg){ - _dsState.selected.forEach(si=>{ _dsImgMap[si] = _dsAppliedImg; }); - } - const p = _wallPosts[_dsState.postIdx]; - if(p) _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsDebounce(_dsPreview, 150); -} -function _dsSyncSelection(){ - _dsState.selected = []; - document.querySelectorAll('#ds-slide-list .ds-slide-chk:checked').forEach(chk=>{ _dsState.selected.push(parseInt(chk.dataset.idx)); }); - // Bug 3 fix: same propagation for checkbox changes. - if(_dsAppliedImg){ - _dsState.selected.forEach(si=>{ if(!_dsImgMap[si]) _dsImgMap[si] = _dsAppliedImg; }); - } - const p = _wallPosts[_dsState.postIdx]; - if(p) _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsDebounce(_dsPreview, 150); -} - -/* ---------------- per-slide text areas ---------------- */ -function _dsRefreshTexts(p){ - const box = document.getElementById('ds-texts'); if(!box) return; - if(!_dsState.selected.length){ box.innerHTML='
Chưa chọn slide nào.
'; return; } - let h='
'; - _dsState.selected.forEach((si, k)=>{ - const s = p.slides[si]; - h+=``; - }); - h+='
'; - box.innerHTML=h; - box.querySelectorAll('textarea').forEach(ta=>{ - ta.addEventListener('input', ()=>{ _dsDebounce(_dsPreview, 200); }); - }); -} - -/* ---------------- bg file ---------------- */ -let _dsBgDataUrl = null; -let _dsTextColor = '#ffffff'; -let _dsImgMode = 'rewrite'; // 'rewrite' | 'custom' | 'none' -/* Bug 1 fix: this is bound as a 'change' listener, so the first arg is the - Event. Read the from evt.target.files (previously input.files was - undefined, so the upload silently did nothing and the preview/apply button - never saw the image). */ -function _dsHandleBgFile(evt){ - const input = evt && evt.target ? evt.target : evt; - const file = (input && input.files && input.files[0]) ? input.files[0] : null; - if(!file) return; - _dsSetImgMode('custom'); // show the custom-img URL/upload panel - const reader=new FileReader(); - reader.onload=function(e){ - _dsBgDataUrl=e.target.result; - _dsImgMode='custom'; - _syncImgModeBtns(); - _dsStatus('✅ Đã chọn ảnh: '+(file.name||'').slice(0,30) + (file.size? ' ('+Math.round(file.size/1024)+'KB)':'')); - // Auto-apply uploaded image to ALL currently selected slides so the upload - // has an immediate, visible effect (preview + save will use it for every slide). - _dsAppliedImg = _dsBgDataUrl; // Bug 3 fix: applies to future selections too - const sel=_dsState.selected; - if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=_dsBgDataUrl; }); } - else { _dsImgMap[0]=_dsBgDataUrl; } - _dsDebounce(_dsPreview,150); - }; - reader.readAsDataURL(file); -} -/* Show a transient status line in the designer footer. */ -function _dsStatus(msg){ - const s=document.getElementById('ds-status'); if(s) s.textContent=msg; -} -function _syncImgModeBtns(){ - ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{ - const b=document.getElementById(id); - if(!b) return; - const on = (id==='ds-img-src-rewrite' && _dsImgMode==='rewrite') || - (id==='ds-img-src-custom' && _dsImgMode==='custom') || - (id==='ds-img-src-none' && _dsImgMode==='none'); - b.style.background = on ? '#2d8659' : '#333'; - b.style.color = on ? '#fff' : '#ccc'; - }); - const wrap=document.getElementById('ds-custom-img-url-wrap'); - if(wrap) wrap.style.display = _dsImgMode==='custom' ? 'block' : 'none'; -} -function _dsSetImgMode(m){ - _dsImgMode = m; - _syncImgModeBtns(); - _dsDebounce(_dsPreview, 150); -} - -/* Build a list of available rewrite images (post.img + each slide.image) - and render them so the user can pick 1 image to apply to the selected slides. - Bug 2 fix: uses data-index + a delegated click handler (no fragile inline - onclick embedding the raw URL, which broke on URLs containing quotes). */ -function _dsRefreshRewriteImgs(p){ - const box = document.getElementById('ds-rewrite-list'); - if(!box) return; - const imgs = []; - const seen = new Set(); - // post-level image first - if(p.img && typeof p.img === 'string' && p.img.length){ - const key = p.img.startsWith('/api/') ? p.img : _dsImageSrc(p.img); - if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: 'Ảnh bài (đại diện)'}); } - } - // then per-slide images - if(Array.isArray(p.slides)){ - p.slides.forEach((s, i)=>{ - const raw = s.image || s.img || ''; - if(raw && typeof raw === 'string' && raw.length){ - const key = raw.startsWith('/api/') ? raw : _dsImageSrc(raw); - if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: `Slide ${s.index||i+1}`}); } - } - }); - } - if(!imgs.length){ - box.innerHTML = '
Không có ảnh rewrite nào.
'; - const wrap = document.getElementById('ds-rewrite-imgs'); - if(wrap) wrap.style.display = 'none'; - return; - } - const wrap = document.getElementById('ds-rewrite-imgs'); - if(wrap) wrap.style.display = 'block'; - _dsRewriteImgSrcs = imgs.map(x=>x.src); // index -> src - let h=''; - imgs.forEach((img, idx)=>{ - h += '
' - + '' - + '
'+img.label+'
' - + '
'; - }); - box.innerHTML = h; - // Bug 2 fix: delegated click handler (event delegation, URL-safe) - box.onclick = function(e){ - const im = e.target.closest('img[data-ds-rw]'); - if(!im) return; - const idx = parseInt(im.getAttribute('data-ds-rw'), 10); - const src = _dsRewriteImgSrcs[idx]; - if(src) dsApplyImgToSelected(src); - }; -} - -/* Apply a chosen image src to ALL selected slides (or the current preview slide). */ -function dsApplyImgToSelected(imgSrc){ - _dsAppliedImg = imgSrc; // Bug 3 fix: remember at designer level (future selections too) - const sel = _dsState.selected; - if(sel.length){ - sel.forEach(si=>{ _dsImgMap[si] = imgSrc; }); - }else{ - _dsImgMap[0] = imgSrc; - } - _dsImgMode = 'custom'; // visually marks we are using a chosen image - _syncImgModeBtns(); - _dsStatus('✅ Đã áp dụng ảnh cho '+(sel.length? sel.length+' slide đã chọn':'slide hiện tại')); - // refresh preview immediately (selected slide 0 is what we preview) - const p=_wallPosts[_dsState.postIdx]; - if(p && sel.length){ _dsOptions(p, sel[0]); } - _dsPreview(); -} - -function _dsDebounce(fn,d){ clearTimeout(fn._t); fn._t=setTimeout(fn,d); } - -/* ---------------- get design options ---------------- */ -function _dsOptions(p, si){ - const s = p.slides[si]; - const ta = document.querySelector(`#ds-texts textarea[data-sidx="${si}"]`); - const text = ta ? ta.value : (s.text||''); - const bgInput = document.getElementById('ds-bg-url')?.value||''; - // Per-slide image override: when user picks an image from the rewrite list, - // it is stored in _dsImgMap[si] and applied to that specific slide. - let bgUrl = ''; - // Solid layout + user picked a SAMPLE background image -> use it as the - // background photo (dark overlay for readability) instead of a flat color. - const isSolid = designerGetLayoutV2()==='solid'; - const useSample = isSolid && _dsBgSample && !_dsAppliedImg; - if(useSample) bgUrl = _dsBgSample; - // Bug 3 fix: designer-level applied image wins for every selected slide. - // Applied when the user picked an image (rewrite picker / upload / URL / - // "Áp dụng" button) — even for slides selected AFTER the image was picked. - if(!bgUrl && _dsAppliedImg) bgUrl = _dsAppliedImg; - if(!bgUrl && _dsImgMap[si]) bgUrl = _dsImgMap[si]; - if(!bgUrl){ - if(_dsImgMode === 'custom'){ - bgUrl = _dsBgDataUrl || bgInput || ''; - } else if(_dsImgMode === 'rewrite'){ - bgUrl = s.image || p.img || ''; - } // none -> '' - } - return { - si, s, text, bgUrl, - ratio: designerGetRatioV2(), - layout: isSolid ? 'solid' : designerGetLayoutV2(), - filter: designerGetFilterV2(), - glow: designerGetGlowV2(), - pos: designerGetPosV2(), - color: _dsTextColor, - bgColor: _dsBgColor, // solid-layout background color ('' = default dark) - bgSample: useSample ? _dsBgSample : '', // 'sample' mode: img passed to draw - }; -} - -/* ---------------- drawing core ---------------- */ -function _dsImageSrc(url){ - if(!url) return ''; - if(url.startsWith('/api/') || url.startsWith('data:')) return url; - return '/api/proxy/img?url='+encodeURIComponent(url); -} -/* Only tag crossOrigin=anonymous for proxied EXTERNAL images. - Setting it on data: URLs or local /api/ paths can cause silent onload - failures (black preview) in some browser/CORS configurations. */ -function _dsMakeImg(url){ - const img=new Image(); - if(url && !url.startsWith('data:') && !url.startsWith('/api/')) img.crossOrigin='anonymous'; - return img; -} - -/* Sample background images for the "Nền đều (solid)" layout — abstract - gradients that look good with white text. Served through the /api/proxy/img - endpoint (same-origin, no crossOrigin needed — _dsMakeImg handles that). - Keyed for the modal background swatches and for _dsDrawLayout. */ -const _DS_BG_SAMPLES = [ - 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=900&q=60', // sơn hùng vĩ (núi) - 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=900&q=60', // sương mù rừng - 'https://images.unsplash.com/photo-1462331940025-496dfbfc7564?w=900&q=60', // vũ trụ - 'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=900&q=60', // núi rừng - 'https://images.unsplash.com/photo-1499002238440-d264edd596ec?w=900&q=60', // hoàng hôn - 'https://images.unsplash.com/photo-1448375240586-882707db888b?w=900&q=60', // rừng tối - 'https://images.unsplash.com/photo-1519681393784-d120267933ba?w=900&q=60', // trời sao - 'https://images.unsplash.com/photo-1518173946687-a4c8892bbd9f?w=900&q=60', // biển đêm - 'https://images.unsplash.com/photo-1497436072909-60f360e1d4b1?w=900&q=60', // đồng cỏ -]; - -/* draw bg image with cover-fit + color filter */ -function _dsDrawBg(ctx, W, H, bgUrl, filter, blur){ - ctx.save(); - ctx.fillStyle='#111'; ctx.fillRect(0,0,W,H); - // filter string - let f=''; - if(filter==='grayscale') f='grayscale(1)'; - else if(filter==='sepia') f='sepia(0.85)'; - else if(filter==='saturate') f='saturate(2.4)'; - else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(filter==='invert') f='invert(1)'; - else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - if(blur) f=(f?f+' ':'')+'blur('+blur+'px)'; - ctx.filter = f; - if(bgUrl){ - const img = new Image(); img.crossOrigin='anonymous'; - // Note: async path handled by caller via onload; this fn is synchronous draw of already-loaded img - } - ctx.restore(); -} - -/* ---------------- layout effects (with loaded bg image) ---------------- */ -function _dsDrawLayout(ctx, W, H, opts, img){ - const { layout, filter, bgUrl, bgColor } = opts; - // base: solid layout can use the chosen background color (no image needed) - let baseColor = '#141414'; - if(layout==='solid' && !img && bgColor) baseColor = bgColor; - ctx.fillStyle = baseColor; ctx.fillRect(0,0,W,H); - // draw bg image cover-fit if present & loaded - if(img){ - const blur = layout==='blur' ? Math.max(6, Math.round(W/90)) : 0; - ctx.save(); - let f=''; - if(filter==='grayscale') f='grayscale(1)'; - else if(filter==='sepia') f='sepia(0.85)'; - else if(filter==='saturate') f='saturate(2.4)'; - else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(filter==='invert') f='invert(1)'; - else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - if(blur) f=(f?f+' ':'')+'blur('+blur+'px)'; - ctx.filter = f; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - const dx=(W-dw)/2, dy=(H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // overlay per layout - if(layout==='gradient'){ - const g=ctx.createLinearGradient(0,0,W,H); - g.addColorStop(0,'rgba(50,20,90,0.75)'); g.addColorStop(0.5,'rgba(20,60,120,0.6)'); g.addColorStop(1,'rgba(120,30,60,0.75)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='vignette'){ - const g=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.62); - g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.78)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='split'){ - const g=ctx.createLinearGradient(0,0,0,H); - g.addColorStop(0,'rgba(0,0,0,0.85)'); g.addColorStop(0.5,'rgba(0,0,0,0.15)'); g.addColorStop(1,'rgba(0,0,0,0.85)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='spotlight'){ - ctx.fillStyle='rgba(0,0,0,0.72)'; ctx.fillRect(0,0,W,H); - const cx=W/2, cy=H*0.45, r=Math.max(W,H)*0.4; - const g=ctx.createRadialGradient(cx,cy,0,cx,cy,r); - g.addColorStop(0,'rgba(255,255,255,0.45)'); g.addColorStop(0.6,'rgba(255,255,255,0.12)'); g.addColorStop(1,'rgba(0,0,0,0.9)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='diagonal'){ - ctx.fillStyle='rgba(0,0,0,0.55)'; ctx.fillRect(0,0,W,H); - ctx.fillStyle='rgba(0,0,0,0.8)'; - ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(W*0.9,0); ctx.lineTo(0,H*0.9); ctx.closePath(); ctx.fill(); - } - else if(layout==='neon'){ - ctx.fillStyle='rgba(10,10,30,0.85)'; ctx.fillRect(0,0,W,H); - ctx.strokeStyle='rgba(80,220,255,0.5)'; ctx.lineWidth=Math.max(2,W/300); - ctx.strokeRect(W*0.03,H*0.03,W*0.94,H*0.94); - } - else if(layout==='top-banner'){ - ctx.fillStyle='rgba(0,0,0,0)'; - const g=ctx.createLinearGradient(0,0,0,H*0.5); - g.addColorStop(0,'rgba(0,0,0,0.8)'); g.addColorStop(1,'rgba(0,0,0,0)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H*0.5); - } - else if(layout==='lower-third'){ - const g=ctx.createLinearGradient(0,H*0.55,0,H); - g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.82)'); - ctx.fillStyle=g; ctx.fillRect(0,H*0.55,W,H*0.45); - } - else if(layout==='card'){ - ctx.fillStyle='rgba(0,0,0,0.35)'; ctx.fillRect(0,0,W,H); - // rounded card - const pad=Math.round(W*0.04); - ctx.fillStyle='rgba(0,0,0,0.65)'; - _dsRoundRect(ctx, pad, H*0.16, W-2*pad, H*0.68, Math.round(W*0.05)); - ctx.fill(); - ctx.strokeStyle='rgba(255,255,255,0.25)'; ctx.lineWidth=Math.max(2,W/400); _dsRoundRect(ctx,pad,H*0.16,W-2*pad,H*0.68,Math.round(W*0.05)); ctx.stroke(); - } - else if(layout==='corner'){ - ctx.fillStyle='rgba(0,0,0,0.3)'; ctx.fillRect(0,0,W,H); - ctx.strokeStyle='rgba(255,215,0,0.9)'; ctx.lineWidth=Math.max(4,W/160); - const L=Math.round(W*0.18), c=Math.round(W*0.04); - [[0,c],[c,0],[W,c],[W-c,0],[0,H-c],[c,H],[W,H-c],[W-c,H]].forEach(([x,y],i)=>{ - const top = y===0 || y===c; const left = x===0 || x===c; - ctx.beginPath(); - if(i<4){ // top corners - if(top && left){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); } - else if(top){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x-L,y); } - else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y+L); } - } else { // bottom corners - if(left){ ctx.moveTo(x,y-L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); } - else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y-L); } - } - ctx.stroke(); - }); - } - else if(layout==='stars'){ - ctx.fillStyle='rgba(8,8,30,0.82)'; ctx.fillRect(0,0,W,H); - const n=Math.round(W*H/18000); - for(let i=0;i dark overlay so text is readable - ctx.fillStyle='rgba(0,0,0,0.45)'; ctx.fillRect(0,0,W,H); - } else if(bgColor){ - // chosen solid color with a subtle gradient + soft vignette for depth - const g=ctx.createLinearGradient(0,0,W,H); - g.addColorStop(0, bgColor); - g.addColorStop(1, _dsShadeColor(bgColor, -0.25)); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - const vg=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.66); - vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(0,0,0,0.42)'); - ctx.fillStyle=vg; ctx.fillRect(0,0,W,H); - } else { - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - } - } -} - -/* Darken (n<0) or lighten (n>0) a hex color by n*100% (for solid bg gradient). */ -function _dsShadeColor(hex, n){ - try{ - hex=String(hex||'').replace('#',''); - if(hex.length===3) hex=hex.split('').map(c=>c+c).join(''); - if(hex.length!==6) return hex; - const num=parseInt(hex,16); - let r=(num>>16)&255, g=(num>>8)&255, b=num&255; - const t = n<0 ? 0 : 255; - const p = Math.abs(n); - r=Math.round((t-r)*p)+r; g=Math.round((t-g)*p)+g; b=Math.round((t-b)*p)+b; - return '#'+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1); - }catch(e){ return hex; } -} - -function _dsRoundRect(ctx,x,y,w,h,r){ - ctx.beginPath(); - ctx.moveTo(x+r,y); - ctx.arcTo(x+w,y,x+w,y+h,r); - ctx.arcTo(x+w,y+h,x,y+h,r); - ctx.arcTo(x,y+h,x,y,r); - ctx.arcTo(x,y,x+w,y,r); - ctx.closePath(); -} - -/* ---------------- text drawing ---------------- */ -function _dsDrawText(ctx, W, H, opts, baseFontScale){ - const { text, pos, glow, color } = opts; - if(!text || !text.trim()) return; - const base = Math.max(28, Math.round(W*baseFontScale)); - const fs = Math.min(base, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - // split lines - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } - }); - if(line) lines.push(line.trim()); - const lh=Math.round(fs*1.25); - const blockH=lines.length*lh; - let y; - if(pos==='top') y=Math.round(H*0.14)+lh/2; - else if(pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2; - else y=Math.round(H/2)-blockH/2+lh/2; - // glow - if(glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); } - else if(glow==='color'){ ctx.shadowColor=color; ctx.shadowBlur=Math.max(10,fs*0.6); } - else if(glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); } - ctx.fillStyle=color; - // subtle stroke for legibility at top/bottom - if(pos==='top'||pos==='bottom'){ ctx.strokeStyle='rgba(0,0,0,0.6)'; ctx.lineWidth=Math.max(2,fs*0.12); ctx.strokeText(textLine(text),W/2,y); } - lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); }); - ctx.shadowBlur=0; -} -function textLine(t){ return t; } - -/* ---------------- compute final canvas size for a design ---------------- */ -function _dsFinalSize(opts){ - const r=opts.ratio; - const w = (r.w>=r.h) ? 1800 : 1350; - const h = Math.round(w*r.h/r.w); - return { w, h }; -} - -/* Shared renderer (Bug 4 fix): renders a slide onto `canvas` using the SAME - code path and SAME resolution for BOTH preview and final save, so the - published image is pixel-identical to what the user saw in the preview — - same cover-fit, same filter, same text placement, same background. */ -function _dsRenderSlide(canvas, opts, done){ - const ctx = canvas.getContext('2d'); - const bgUrl = _dsImageSrc(opts.bgUrl); - function draw(img){ - _dsDrawLayout(ctx, canvas.width, canvas.height, opts, img||null); - _dsDrawText(ctx, canvas.width, canvas.height, opts, 0.052); - if(done) done(img||null); - } - if(bgUrl){ - const img=_dsMakeImg(bgUrl); - img.onload=function(){ draw(img); }; - img.onerror=function(){ console.warn('[designer] bg image failed to load:', bgUrl); draw(null); }; - img.src=bgUrl; - } else { - draw(null); - } -} - -/* ---------------- preview ---------------- */ -function _dsPreview(){ - const p=_wallPosts[_dsState.postIdx]; if(!p) return; - const area=document.getElementById('ds-preview-area'); if(!area) return; - const sel=_dsState.selected; - if(!sel.length){ area.style.display='block'; area.innerHTML='
Chưa chọn slide nào để xem trước.
'; return; } - area.style.display='block'; - area.innerHTML='
⏳ Đang tạo xem trước...
'; - // display-scale: cap visible width at 300px, keep aspect ratio per slide - const dispW=Math.min(300, Math.floor((Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540))*0.5)); - const cans=[]; - sel.forEach((si, k)=>{ - const opts=_dsOptions(p, si); - const { w, h }=_dsFinalSize(opts); - const canvas=document.createElement('canvas'); - canvas.width=w; canvas.height=h; - canvas.style.width=dispW+'px'; canvas.style.height='auto'; - canvas.style.borderRadius='12px'; canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; canvas.style.display='block'; canvas.style.margin='0 auto 14px auto'; - cans.push({opts, canvas}); - }); - let remaining=cans.length; - function allDone(){ - if(--remaining>0) return; - let out=''; - if(cans.length>1) out+='
Xem trước '+(cans.length)+' slide đã chọn (cuộn xuống để xem hết):
'; - area.innerHTML=out; - cans.forEach((c,k)=>{ - if(k>0) area.appendChild(document.createElement('br')); - area.appendChild(c.canvas); - }); - } - cans.forEach(c=>{ _dsRenderSlide(c.canvas, c.opts, allDone); }); -} - -/* ---------------- save: render + upload each selected slide, then post ---------------- */ -async function _dsSave(p){ - const statusEl=document.getElementById('ds-status'); if(statusEl) statusEl.textContent='⏳ Đang tạo ảnh các slide...'; - const sel=_dsState.selected; - if(!sel.length){ if(statusEl) statusEl.textContent='⚠️ Chưa chọn slide nào để đăng.'; return; } - const saveBtn=document.getElementById('ds-save-btn'); if(saveBtn){ saveBtn.disabled=true; saveBtn.textContent='⏳ Đang xử lý...'; } - - const uploaded = []; // {si, url} - try{ - // render each selected slide at final resolution - for(let k=0;k{ - _dsRenderSlide(canvas, opts, function(){ - // Nén JPEG thay PNG: dung lượng rất nhỏ (thường 5-10x nhỏ hơn), - // ảnh tải nhanh hơn nhiều trên Tường AI. Chất lượng 0.82 giữ chữ sắc nét. - canvas.toBlob(async function(blob){ - const fd=new FormData(); - fd.append('file', blob, 'slide_'+(si+1)+'.jpg'); - fd.append('post_id', p.id||''); - try{ - const r=await fetch('/api/wall/img',{method:'POST',body:fd}); - const j=await r.json(); - if(!r.ok || j.error) throw new Error(j.error||'Lỗi upload'); - resolve(j.url); - }catch(e){ resolve({error:e.message}); } - },'image/jpeg', 0.82); - }); - }); - if(url && url.error) throw new Error(url.error); - uploaded.push({si, url}); - // update slide image live - if(p.slides[si]) p.slides[si].image = url; - } - - if(statusEl) statusEl.textContent='⏳ Đang đăng lên Tường AI...'; - - // build updated slides array (keep unselected unchanged) - const newSlides = p.slides.map((s,i)=>{ - const up = uploaded.find(u=>u.si===i); - // ensure text edits are applied too - const ta = document.querySelector(`#ds-texts textarea[data-sidx="${i}"]`); - return { - text: ta ? ta.value : (s.text||''), - image: up ? up.url : (s.image||''), - index: s.index || (i+1), - }; - }); - - // pick selected slides only -> the wall post is a SLIDE-IMAGE post of selected slides - const selSlides = newSlides.filter((_,i)=> sel.includes(i)); - - const post = { - id: p.id, - title: p.title||'', - text: selSlides.map(s=>'• '+s.text).join('\n\n'), - img: selSlides[0] ? selSlides[0].image : p.img||'', - url: p.url||'', - slides: selSlides, // <-- bài đăng bao gồm chỉ các slide đã chọn - images: selSlides.map(s=>s.image), - kind: p.kind||'slide_summary', - video: p.video||'', - voice: p.voice||'', - emotion: p.emotion||'', - language: p.language||'', - ts: p.ts||Math.floor(Date.now()/1000), - }; - - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json(); - if(wr.ok && wj.post){ - prependWallPost(wj.post); - toast('✅ Đã đăng bài slide lên Tường AI ('+selSlides.length+' slide)!'); - } else { - toast('✅ Đã lưu ảnh slide!'); - } - document.getElementById('slide-designer-overlay').remove(); - }catch(e){ - if(statusEl) statusEl.textContent='❌ '+e.message; - toast('❌ '+e.message); - if(saveBtn){ saveBtn.disabled=false; saveBtn.textContent='📤 Lưu & Đăng lên Tường AI ('+sel.length+' slide)'; } - } -} - -/* keep old helper names harmless for any other caller */ -function updateDesignerText(){} -function designerGetRatio(){ return designerGetRatioV2(); } -function designerGetLayout(){ return designerGetLayoutV2(); } -function designerDebounce(fn,d){ _dsDebounce(fn,d); } -function handleDesignerBgFile(){} -function previewDesignerSlide(){ _dsPreview(); } \ No newline at end of file diff --git a/static/fm_fix.css b/static/fm_fix.css index 88f4ac678007aee1c4c24ce2679f96cc3151cd2d..61e207172265b071cb75259375f87c253922a2fe 100644 --- a/static/fm_fix.css +++ b/static/fm_fix.css @@ -168,262 +168,3 @@ min-width:100%!important;max-width:none!important;max-height:none!important; object-fit:cover!important; } - -/* ============================================================ - BXH / BÅNG XẼP HẠNG (standing league table) FIX - Bongda returns div-based Tailwind rows (.ranking-table .leaderboard - .leaderboard-item / .head / .team / .copy). The old CSS only styled - so the standings rendered broken. Style the divs directly. - ============================================================ */ -#ls-content .ranking-table, -#ls-content .leaderboard{display:block!important;width:100%!important} -#ls-content .ranking-table .head, -#ls-content .leaderboard .head{display:flex!important;width:100%!important;background:#222!important;border-bottom:1px solid #333!important;padding:5px 0!important;font-size:10px!important;color:#999!important} -#ls-content .ranking-table .head .team, -#ls-content .leaderboard .head .team{flex:1 1 auto!important;min-width:0!important} -#ls-content .ranking-table .head .team span, -#ls-content .leaderboard .head .team span{display:inline-block!important;width:18px!important;text-align:center!important;color:#888!important} -#ls-content .ranking-table .head .team .link, -#ls-content .leaderboard .head .team .link{font-size:10px!important;color:#999!important;font-weight:700!important} -#ls-content .ranking-table .head .copy, -#ls-content .leaderboard .head .copy{display:flex!important;gap:2px!important;align-items:center!important;justify-content:flex-end!important;min-width:0!important} -#ls-content .ranking-table .head .copy p, -#ls-content .leaderboard .head .copy p{font-size:9px!important;color:#888!important;min-width:16px!important;text-align:center!important;margin:0!important} -#ls-content .ranking-table .head .copy p.form, -#ls-content .leaderboard .head .copy p.form{display:none!important} -#ls-content .ranking-table .leaderboard-item, -#ls-content .ranking-table #team_, -#ls-content .leaderboard .leaderboard-item{ - display:table!important;width:100%!important;table-layout:fixed!important; - border-collapse:collapse!important;border-bottom:1px solid #1a1a1a!important; - font-size:11px!important;color:#ccc!important;background:transparent!important -} -#ls-content .ranking-table .leaderboard-item>div.team, -#ls-content .ranking-table .leaderboard-item>.team, -#ls-content .leaderboard .leaderboard-item .team{ - display:table-cell!important;vertical-align:middle!important; - padding:5px 4px!important;text-align:left!important;min-width:0!important -} -#ls-content .ranking-table .leaderboard-item>div.team span, -#ls-content .ranking-table .leaderboard-item>.team span{ - display:inline-block!important;width:18px!important;min-width:18px!important; - text-align:center!important;font-size:10px!important;color:#888!important;font-weight:600!important -} -#ls-content .ranking-table .leaderboard-item>div.team a.link, -#ls-content .ranking-table .leaderboard-item>.team a.link{ - display:inline-flex!important;align-items:center!important;gap:4px!important; - min-width:0!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important -} -#ls-content .ranking-table .leaderboard-item>div.team a.link img, -#ls-content .ranking-table .leaderboard-item>.team a.link img{width:16px!important;height:16px!important;object-fit:contain!important;flex:0 0 auto!important} -#ls-content .ranking-table .leaderboard-item>div.team a.link p, -#ls-content .ranking-table .leaderboard-item>.team a.link p{ - font-size:11px!important;color:#ccc!important;margin:0!important; - white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important -} -#ls-content .ranking-table .leaderboard-item>div.copy, -#ls-content .ranking-table .leaderboard-item>.copy, -#ls-content .leaderboard .leaderboard-item .copy{ - display:table-cell!important;vertical-align:middle!important; - padding:5px 2px!important;text-align:center!important;white-space:nowrap!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p, -#ls-content .ranking-table .leaderboard-item>.copy p{ - display:inline-block!important;min-width:22px!important;text-align:center!important; - font-size:11px!important;color:#ccc!important;margin:0 1px!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p strong, -#ls-content .ranking-table .leaderboard-item>.copy p strong{ - display:inline-block!important;min-width:22px!important;text-align:center!important; - font-weight:800!important;color:#f0c040!important;font-size:12px!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p.form, -#ls-content .ranking-table .leaderboard-item>.copy p.form{display:inline-flex!important;flex-wrap:nowrap!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span, -#ls-content .ranking-table .leaderboard-item>.copy p.form span{ - display:inline-block!important;min-width:14px!important;height:14px!important; - line-height:14px!important;text-align:center!important;font-size:9px!important; - border-radius:2px!important;margin:0 1px!important;color:#fff!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-green, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-green{background:#2d8659!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-gray-5, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-gray-5, -#ls-content .leaderboard .leaderboard-item .copy p.form span.bg-gray-5, -#ls-content .ranking-table .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-red, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-red{background:#c0392b!important} -/* hide the bongda left accent bar that floats absolutely */ -#ls-content .ranking-table .leaderboard-item>div[class*="w-["], -#ls-content .ranking-table .leaderboard-item div.relative{display:none!important} -/* top row = champion accent can stay, but clean layout */ -#ls-content .leaderboard-item{margin:0!important} -#ls-content .rank-table{width:100%!important;overflow-x:auto!important} -/* fallback generic so ANY div-based standings table gets readable */ -#ls-content .team .name,#ls-content .team .logo{font-size:11px!important;color:#ccc!important} -#ls-content .copy p{font-size:11px!important;color:#ccc!important} -/* injected BXH header + row layout (see _decorateStandings in app_v2.js) */ -#ls-content .ls-bxh-head{ - display:flex!important;width:100%!important;align-items:center!important;gap:4px!important; - background:#222!important;border-bottom:1px solid #333!important; - padding:5px 2px!important;position:sticky!important;top:0!important;z-index:2!important -} -#ls-content .ls-bxh-head .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important} -#ls-content .ls-bxh-head .team span{display:inline-block!important;width:18px!important;min-width:18px!important;text-align:center!important;color:#888!important;font-size:10px!important;font-weight:700!important} -#ls-content .ls-bxh-head .team p{font-size:10px!important;color:#999!important;font-weight:700!important;margin:0!important;text-transform:uppercase!important} -#ls-content .ls-bxh-head .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important} -#ls-content .ls-bxh-head .copy p{display:inline-block!important;min-width:20px!important;text-align:center!important;font-size:9px!important;color:#888!important;font-weight:700!important;margin:0!important} -#ls-content .leaderboard-item{display:flex!important;width:100%!important;align-items:center!important;gap:4px!important;border-bottom:1px solid #1a1a1a!important;padding:4px 2px!important;background:transparent!important} -#ls-content .leaderboard-item .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important} -#ls-content .leaderboard-item .team span{display:inline-block!important;width:18px!important;min-width:18px!important;text-align:center!important;color:#888!important;font-size:10px!important;font-weight:600!important} -#ls-content .leaderboard-item .team a{display:inline-flex!important;align-items:center!important;gap:4px!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important;overflow:hidden!important;min-width:0!important} -#ls-content .leaderboard-item .team a img{width:16px!important;height:16px!important;object-fit:contain!important;flex:0 0 auto!important} -#ls-content .leaderboard-item .team a p{font-size:11px!important;color:#ccc!important;margin:0!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important} -#ls-content .leaderboard-item .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important} -#ls-content .leaderboard-item .copy p{display:inline-block!important;min-width:20px!important;text-align:center!important;font-size:11px!important;color:#ccc!important;margin:0!important} -#ls-content .leaderboard-item .copy p strong{font-weight:800!important;color:#f0c040!important;min-width:20px!important;text-align:center!important} -#ls-content .leaderboard-item .copy p.form{display:inline-flex!important;flex-wrap:nowrap!important} -#ls-content .leaderboard-item .copy p.form span{width:14px!important;height:14px!important;line-height:14px!important;font-size:9px!important;border-radius:2px!important;color:#fff!important;margin:0 1px!important;text-align:center!important} -#ls-content .leaderboard-item .copy p.form span.bg-green{background:#2d8659!important;display:inline-block!important} -#ls-content .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important;display:inline-block!important} -#ls-content .leaderboard-item .copy p.form span.bg-red{background:#c0392b!important;display:inline-block!important} -#ls-content .leaderboard-item>div[class*="w-["]{display:none!important}#ls-content .leaderboard-item>div[class*="w-["]{display:none!important} - -/* ============================================================ - FPT PLAY / HIGHLIGHT VIDEO OVERFLOW FIX v2 - fptplay videos open in the TikTok-style feed inside .yt-thumb-wrap > - iframe (YouTube) or