bep40 commited on
Commit
2df5077
·
verified ·
1 Parent(s): f62825b

Restore to commit 60e310a — full revert

Browse files
Files changed (5) hide show
  1. app_v2_entry.py +8 -2
  2. main.py +11 -4
  3. match_detail_v2.py +47 -1
  4. static/index.html +768 -1
  5. vtv_api.py +11 -205
app_v2_entry.py CHANGED
@@ -1,6 +1,11 @@
1
  """VNEWS v2 Entry Point - with fast bongda proxy"""
2
  import sys, os
3
- from main import app, HEADERS, BONGDA_HEADERS, fetch_bongda_api, HL_LEAGUES
 
 
 
 
 
4
 
5
  try:
6
  import ai_ext
@@ -418,8 +423,9 @@ def _get_hot_topics():
418
  @app.get('/api/hot_topics')
419
  def api_hot_topics():return JSONResponse({'topics':_get_hot_topics()})
420
  @app.get('/')
 
421
  async def serve_index():
422
- p=os.path.join(STATIC_DIR,'index_v2.html')
423
  if os.path.exists(p):return FileResponse(p,media_type='text/html')
424
  return HTMLResponse('<h1>VNEWS</h1>')
425
  @app.get('/api/hashtag/sources')
 
1
  """VNEWS v2 Entry Point - with fast bongda proxy"""
2
  import sys, os
3
+ from main import app, HEADERS, fetch_bongda_api, HL_LEAGUES
4
+ # Bongda headers — try both names for compatibility
5
+ try:
6
+ from main import BONGDA_HEADERS as _BDH
7
+ except ImportError:
8
+ from main import BONGDA_API_HEADERS as _BDH
9
 
10
  try:
11
  import ai_ext
 
423
  @app.get('/api/hot_topics')
424
  def api_hot_topics():return JSONResponse({'topics':_get_hot_topics()})
425
  @app.get('/')
426
+ # Serve v3
427
  async def serve_index():
428
+ p=os.path.join(STATIC_DIR,'index_v3.html')
429
  if os.path.exists(p):return FileResponse(p,media_type='text/html')
430
  return HTMLResponse('<h1>VNEWS</h1>')
431
  @app.get('/api/hashtag/sources')
main.py CHANGED
@@ -4,7 +4,7 @@ import html as html_lib
4
  from datetime import datetime
5
  from concurrent.futures import ThreadPoolExecutor, as_completed
6
  from fastapi import FastAPI, Query, Request
7
- from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response
8
  from fastapi.staticfiles import StaticFiles
9
  from urllib.parse import unquote, quote, urlencode
10
  import requests
@@ -127,7 +127,13 @@ def _parse_match_from_li(li, status_type="live"):
127
  if len(spans)>=4:minute=spans[3].get_text(strip=True)
128
  if not score and status_el and status_el.select_one(".vs"):score="VS"
129
  league=league_el.get_text(strip=True) if league_el else ""
130
- return{"home":home_el.get_text(strip=True),"away":away_el.get_text(strip=True),"score":score or"VS","minute":minute,"league":league,"time":time_el.get_text(strip=True) if time_el else "","event_id":event_id,"home_logo":home_logo.get("src","") if home_logo else "","away_logo":away_logo.get("src","") if away_logo else "","status":status_type}
 
 
 
 
 
 
131
 
132
  # ===== VIDEO PROXY =====
133
  @app.get("/api/proxy/m3u8")
@@ -938,8 +944,9 @@ async def video_share(url:str=Query(default=""),title:str=Query(default="VNEWS V
938
  @app.get("/s")
939
  async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default="")):
940
  decoded_url=unquote(url)
941
- redirect_script=f'<script>localStorage.setItem("pending_article","{decoded_url}");location.href="{SPACE_URL}";</script>' if decoded_url else f'<script>location.href="{SPACE_URL}";</script>'
942
- return HTMLResponse(f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>{unquote(title)}</title></head><body>{redirect_script}</body></html>')
 
943
  @app.get("/")
944
  async def index():
945
  with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
 
4
  from datetime import datetime
5
  from concurrent.futures import ThreadPoolExecutor, as_completed
6
  from fastapi import FastAPI, Query, Request
7
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response, RedirectResponse
8
  from fastapi.staticfiles import StaticFiles
9
  from urllib.parse import unquote, quote, urlencode
10
  import requests
 
127
  if len(spans)>=4:minute=spans[3].get_text(strip=True)
128
  if not score and status_el and status_el.select_one(".vs"):score="VS"
129
  league=league_el.get_text(strip=True) if league_el else ""
130
+ # Extract full URL with slug for direct scraping
131
+ match_url = ""
132
+ if status_el:
133
+ href = status_el.get("href", "")
134
+ if href:
135
+ match_url = "https://bongda.com.vn" + href if href.startswith("/") else href
136
+ return{"home":home_el.get_text(strip=True),"away":away_el.get_text(strip=True),"score":score or"VS","minute":minute,"league":league,"time":time_el.get_text(strip=True) if time_el else "","event_id":event_id,"url":match_url,"home_logo":home_logo.get("src","") if home_logo else "","away_logo":away_logo.get("src","") if away_logo else "","status":status_type}
137
 
138
  # ===== VIDEO PROXY =====
139
  @app.get("/api/proxy/m3u8")
 
944
  @app.get("/s")
945
  async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default="")):
946
  decoded_url=unquote(url)
947
+ if decoded_url and decoded_url.startswith("http"):
948
+ return RedirectResponse(url=decoded_url, status_code=302)
949
+ return RedirectResponse(url=SPACE_URL, status_code=302)
950
  @app.get("/")
951
  async def index():
952
  with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
match_detail_v2.py CHANGED
@@ -133,6 +133,39 @@ def parse_events(sp):
133
  return events
134
 
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  def fetch_match_detail(event_id: int) -> dict:
137
  import concurrent.futures
138
  result = {"event_id": event_id, "found": False, "sections": []}
@@ -155,6 +188,20 @@ def fetch_match_detail(event_id: int) -> dict:
155
  except Exception:
156
  continue
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  if not html:
159
  return result
160
 
@@ -284,7 +331,6 @@ def fetch_match_detail(event_id: int) -> dict:
284
 
285
 
286
  def fetch_match_detail_by_url(url: str) -> dict:
287
- import concurrent.futures
288
  eid_match = re.search(r'/tran-dau/(\d+)/', url)
289
  if not eid_match:
290
  return {"event_id": 0, "found": False, "error": "Cannot extract event_id from URL"}
 
133
  return events
134
 
135
 
136
+ def _get_slug_from_api(event_id: int) -> str:
137
+ """Fetch match slug from bongda API to build full URL."""
138
+ endpoints = [
139
+ f"/api/fixtures/live",
140
+ f"/api/fixtures/get-by-date?date=__today__",
141
+ f"/api/fixtures/incoming",
142
+ ]
143
+ import datetime
144
+ today = datetime.date.today().strftime("%Y-%m-%d")
145
+ for ep in endpoints:
146
+ ep = ep.replace("__today__", today)
147
+ try:
148
+ resp = requests.get(
149
+ f"https://bongda.com.vn{ep}",
150
+ headers=API_HEADERS, timeout=6
151
+ )
152
+ if resp.status_code == 200:
153
+ data = resp.json()
154
+ html = data.get("html", "")
155
+ if html:
156
+ sp = _mk(html)
157
+ for li in sp.select("li.match-detail"):
158
+ status_a = li.select_one(".status a")
159
+ if status_a:
160
+ href = status_a.get("href", "")
161
+ m = re.search(r'/tran-dau/(\d+)/', href)
162
+ if m and int(m.group(1)) == event_id:
163
+ return href # e.g. /tran-dau/123/preview/slug-name
164
+ except Exception:
165
+ continue
166
+ return ""
167
+
168
+
169
  def fetch_match_detail(event_id: int) -> dict:
170
  import concurrent.futures
171
  result = {"event_id": event_id, "found": False, "sections": []}
 
188
  except Exception:
189
  continue
190
 
191
+ # If no slug URL worked, try to get slug from API
192
+ if not html:
193
+ slug_path = _get_slug_from_api(event_id)
194
+ if slug_path:
195
+ try:
196
+ resp = requests.get(
197
+ f"https://bongda.com.vn{slug_path}",
198
+ headers=HEADERS, timeout=10, allow_redirects=True
199
+ )
200
+ if resp.status_code == 200 and len(resp.text) > 1000:
201
+ html = resp.text
202
+ except Exception:
203
+ pass
204
+
205
  if not html:
206
  return result
207
 
 
331
 
332
 
333
  def fetch_match_detail_by_url(url: str) -> dict:
 
334
  eid_match = re.search(r'/tran-dau/(\d+)/', url)
335
  if not eid_match:
336
  return {"event_id": 0, "found": False, "error": "Cannot extract event_id from URL"}
static/index.html CHANGED
@@ -1,2 +1,769 @@
1
  <!DOCTYPE html>
2
- <html><head><meta http-equiv="refresh" content="0;url=/"></head><body>Loading VNEWS...</body></html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!DOCTYPE html>
2
+ <html lang="vi">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
6
+ <title>VNEWS - Tin Tức Việt Nam</title>
7
+ <meta name="description" content="Tin tức tổng hợp, bóng đá trực tiếp, video highlight, AI tóm tắt.">
8
+ <meta property="og:title" content="VNEWS - Tin Tức Việt Nam">
9
+ <meta property="og:image" content="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg">
10
+ <link rel="canonical" href="https://bep40-vnews.hf.space">
11
+ <link rel="stylesheet" href="/static/wc2026.css">
12
+ <script src="https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js"></script>
13
+ <style>
14
+ *{box-sizing:border-box;margin:0;padding:0}body{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;overflow-x:hidden}
15
+ .header{background:linear-gradient(135deg,#0d1117,#1a3a2a 50%,#8b7500);padding:12px;text-align:center}.header h1{font-size:18px;color:#fff}.header p{font-size:10px;color:#aaa}
16
+ .cats{display:flex;overflow-x:auto;background:#1a1a1a;border-bottom:1px solid #333;padding:0 4px;position:sticky;top:0;z-index:50;scrollbar-width:none}.cats::-webkit-scrollbar{display:none}
17
+ .cat{padding:9px 11px;color:#888;font-size:11px;white-space:nowrap;border-bottom:2px solid transparent;cursor:pointer;flex-shrink:0}.cat.active{color:#5cb87a;border-bottom-color:#5cb87a;font-weight:700}
18
+ .view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}
19
+ .slider-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.slider-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.slider-label{color:#f0c040;font-size:13px;font-weight:800}.slider-note{font-size:10px;color:#777}.slider-track{display:flex;overflow-x:auto;gap:8px;padding:4px 10px 10px;scrollbar-width:none}.slider-track::-webkit-scrollbar{display:none}.slider-item{flex:0 0 160px;cursor:pointer}.shorts-item{flex:0 0 110px!important}.slider-thumb{position:relative;width:100%;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#333}.shorts-thumb{aspect-ratio:3/4!important;border-radius:8px!important}.slider-thumb img,.slider-thumb video{width:100%;height:100%;object-fit:cover}.slider-title{font-size:10px;color:#ccc;margin-top:3px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
20
+ .card-play{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:30px;height:30px;border-radius:50%;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px}
21
+ .grid{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;padding:6px 4px}@media(min-width:650px){.grid{grid-template-columns:repeat(3,1fr)}}
22
+ .card{background:#1a1a1a;border:1px solid #222;border-radius:8px;overflow:hidden;cursor:pointer}.card-img{position:relative;aspect-ratio:16/9;background:#333}.card-img img{width:100%;height:100%;object-fit:cover}.card-body{padding:6px 8px}.card-title{font-size:11px;line-height:1.35;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
23
+ .badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700;display:inline-block;margin-bottom:2px;color:#fff}.badge-vne{background:#c0392d}.badge-bbc{background:#b80000}.badge-dt{background:#1565c0}.badge-genk{background:#6a1b9a}.badge-fpt{background:#f26522}.badge-ai{background:#2d8659}.badge-wc{background:#0b6bcb}
24
+ .section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}
25
+ .back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}
26
+ .article-view{padding:12px 8px 40px;max-width:760px;margin:0 auto}.article-title{font-size:18px;font-weight:800;line-height:1.3;margin-bottom:8px}.article-summary{background:#1a2a1f;border-left:3px solid #2d8659;padding:10px;margin-bottom:14px;color:#ccc;font-size:13px}.article-p{font-size:14px;line-height:1.7;color:#ccc;margin-bottom:10px}.article-img{width:100%;border-radius:6px;margin:10px 0}.article-h2{font-size:16px;margin:16px 0 8px;color:#eee}.article-actions{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid #333;margin-top:16px;padding-top:10px}.article-actions button{background:#1a1a1a;border:1px solid #333;color:#ccc;padding:7px 12px;border-radius:14px;font-size:11px;cursor:pointer}.article-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px;font-size:12px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px;font-size:11px;cursor:pointer}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}
27
+ .tiktok-container{width:100%;height:80vh;max-height:680px;min-height:400px;background:#000}.tiktok-feed{height:100%;overflow-y:scroll;scroll-snap-type:y mandatory;scrollbar-width:none}.tiktok-feed::-webkit-scrollbar{display:none}.tiktok-slide{height:80vh;max-height:680px;min-height:400px;scroll-snap-align:start;position:relative;background:#000;display:flex;align-items:center;justify-content:center}.tiktok-slide video,.tiktok-slide iframe{width:100%;height:100%;object-fit:cover;border:none}.tiktok-slide.ratio-wide video,.tiktok-slide.ratio-wide iframe{object-fit:contain}.tiktok-bottom{position:absolute;bottom:0;left:0;right:60px;padding:12px 10px 16px;background:linear-gradient(transparent,rgba(0,0,0,.85));z-index:3}.tiktok-title{font-size:12px;color:#fff}.tiktok-counter{position:absolute;top:8px;left:8px;background:rgba(0,0,0,.5);font-size:9px;padding:2px 7px;border-radius:8px;color:#fff;z-index:4}.tiktok-right{position:absolute;right:8px;bottom:100px;display:flex;flex-direction:column;align-items:center;gap:14px;z-index:5}.tiktok-right-btn{display:flex;flex-direction:column;align-items:center;gap:2px;background:none;border:0;color:#fff;cursor:pointer;font-size:10px}.tiktok-right-btn .icon{width:42px;height:42px;border-radius:50%;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;font-size:20px}.tiktok-right-btn .count{font-size:10px;color:#ddd}
28
+ .inline-comments{position:absolute;bottom:0;left:0;right:0;max-height:50%;background:rgba(18,18,18,.95);border-radius:14px 14px 0 0;z-index:10;overflow:hidden;display:flex;flex-direction:column}.inline-cmt-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid #333;color:#5cb87a;font-size:12px;font-weight:700}.inline-cmt-header button{background:none;border:0;color:#fff;font-size:16px;cursor:pointer}.inline-cmt-list{flex:1;overflow-y:auto;padding:6px 10px;max-height:180px}.inline-cmt-item{background:#222;border-radius:8px;padding:6px 8px;margin:4px 0;color:#ccc;font-size:11px;line-height:1.3}.inline-cmt-time{font-size:9px;color:#777;margin-right:6px}.inline-cmt-input{display:flex;gap:6px;padding:8px 10px;border-top:1px solid #333}.inline-cmt-input input{flex:1;background:#222;border:1px solid #444;color:#eee;border-radius:16px;padding:7px 12px;font-size:11px}.inline-cmt-input button{background:#2d8659;border:0;color:#fff;border-radius:16px;padding:7px 12px;font-size:11px;cursor:pointer}
29
+ .wc2026-section{margin:6px 4px;background:linear-gradient(135deg,#0d1117,#1a1a3a);border:1px solid #1a3a5a;border-radius:10px;overflow:hidden}.wc-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;background:linear-gradient(90deg,#0b2e4a,#1a3a5a)}.wc-header h2{font-size:15px;color:#fff;margin:0}.wc-live-badge{font-size:10px;color:#e74c3c;font-weight:700;animation:wc-pulse 1.5s infinite}@keyframes wc-pulse{0%,100%{opacity:1}50%{opacity:.4}}.wc-tabs{display:flex;gap:4px;padding:8px 10px;overflow-x:auto;scrollbar-width:none}.wc-tabs::-webkit-scrollbar{display:none}.wc-tab{padding:5px 10px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:12px;color:#8ab4d8;font-size:10px;cursor:pointer;white-space:nowrap;flex-shrink:0}.wc-tab.active{background:#0b6bcb;border-color:#0b6bcb;color:#fff;font-weight:700}.wc-content{padding:8px 10px;max-height:500px;overflow-y:auto}.wc-news-grid{display:flex;flex-direction:column;gap:8px}.wc-news-item{display:flex;gap:8px;padding:8px;background:#1a2030;border-radius:8px;cursor:pointer}.wc-news-item:active{opacity:.8}.wc-news-img{flex:0 0 70px;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#222}.wc-news-img img{width:100%;height:100%;object-fit:cover}.wc-news-text{flex:1;min-width:0}.wc-news-title{font-size:11px;font-weight:700;color:#eee;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wc-news-via{font-size:9px;color:#6a9fca;margin-top:2px}
30
+ .ls-section{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.ls-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.ls-header h3{color:#f0c040;font-size:13px;font-weight:800}.ls-tabs{display:flex;gap:4px;padding:0 10px 8px;overflow-x:auto;scrollbar-width:none}.ls-tabs::-webkit-scrollbar{display:none}.ls-tab{padding:4px 10px;background:#222;border:1px solid #333;border-radius:12px;color:#999;font-size:10px;white-space:nowrap;cursor:pointer;flex-shrink:0}.ls-tab.active{background:#2d8659;border-color:#2d8659;color:#fff;font-weight:700}.ls-content{max-height:420px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}.ls-content ul{list-style:none;padding:0;margin:0}.ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}.ls-content .title-content img{width:18px;height:18px}.ls-content .title-content strong{font-size:11px;color:#ccc}.ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}.ls-content .match-detail:hover{background:#1a2a1f}.ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.ls-content .datetime{width:100%;font-size:9px;color:#888}.ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}.ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0;text-decoration:none}.ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ls-content .team .logo img{width:18px;height:18px}.ls-content .home-team{justify-content:flex-end;text-align:right}.ls-content .status{flex:0 0 54px;text-align:center}.ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}.ls-content .status .label{font-size:8px;color:#888;display:block}.ls-content .status .label.live{color:#e74c3c}.ls-content .info,.ls-content .btns{display:none}.ls-content table{width:100%;border-collapse:collapse;font-size:11px;color:#ccc}.ls-content table th{background:#222;color:#999;padding:5px 4px;font-size:10px;border-bottom:1px solid #333}.ls-content table td{padding:4px 3px;border-bottom:1px solid #1a1a1a}.ls-content table .team-name{display:flex;align-items:center;gap:4px}.ls-content table .team-name img{width:16px;height:16px}.ls-content table .pts{font-weight:800;color:#f0c040}
31
+ .match-overlay{position:fixed;inset:0;background:#111;z-index:9999;display:none;flex-direction:column;overflow:auto}.match-overlay.active{display:flex}.mo-header{padding:10px;background:#1a1a1a;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:1}.mo-header h3{font-size:13px;color:#eee}.mo-close{background:none;border:0;color:#fff;font-size:22px;cursor:pointer}.mo-tabs{display:flex;gap:4px;padding:8px 10px;background:#1a1a1a;overflow-x:auto}.mo-tab{padding:5px 12px;background:#222;border:1px solid #333;border-radius:10px;color:#999;font-size:10px;cursor:pointer;white-space:nowrap}.mo-tab.active{background:#2d8659;color:#fff}.mo-body{padding:8px;overflow-x:auto;font-size:12px;color:#ddd}.mo-body ul{list-style:none;padding:0;margin:0}.mo-body li{padding:5px 0;border-bottom:1px solid #222}
32
+ .featured-match{margin:6px 4px;background:linear-gradient(135deg,#1a2a1f,#0d1117);border:1px solid #2d8659;border-radius:10px;padding:12px;cursor:pointer}.fm-league{text-align:center;color:#5cb87a;font-size:9px;font-weight:700;text-transform:uppercase}.fm-teams{display:flex;align-items:center;justify-content:center;gap:10px;margin-top:6px}.fm-team{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px}.fm-team img{width:32px;height:32px;object-fit:contain}.fm-team span{font-size:10px;color:#ccc;text-align:center}.fm-score{font-size:22px;font-weight:900;min-width:60px;text-align:center;color:#fff}.fm-status{text-align:center;margin-top:6px;font-size:9px;color:#e74c3c;font-weight:700}.fm-status.upcoming{color:#f0c040}
33
+ .ai-compose{margin:6px 4px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.ai-compose-title{font-size:13px;font-weight:800;color:#5cb87a;margin-bottom:8px}.ai-compose-row{display:flex;gap:6px;margin-top:6px}.ai-compose input{flex:1;background:#222;border:1px solid #333;color:#eee;border-radius:18px;padding:9px 12px;font-size:12px;min-width:0}.ai-compose button{background:#2d8659;border:0;color:#fff;border-radius:18px;padding:9px 12px;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.ai-compose button.secondary{background:#333}.hot-topic-row{display:flex;gap:6px;overflow-x:auto;padding:4px 0;scrollbar-width:none}.hot-topic-row::-webkit-scrollbar{display:none}.hot-chip{flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer;white-space:nowrap}.hot-chip:active{transform:scale(.96)}
34
+ .hashtag-sources{margin:8px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.hashtag-sources h3{font-size:13px;color:#5cb87a;margin-bottom:8px}.hashtag-src-item{display:flex;gap:8px;padding:8px;background:#202020;border-radius:8px;margin:6px 0;cursor:pointer}.hashtag-src-item:active{opacity:.8}.hashtag-src-img{flex:0 0 80px;aspect-ratio:16/9;background:#333;border-radius:6px;overflow:hidden}.hashtag-src-img img{width:100%;height:100%;object-fit:cover}.hashtag-src-text{flex:1;min-width:0}.hashtag-src-title{font-size:12px;font-weight:700;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.hashtag-src-via{font-size:10px;color:#888;margin-top:2px}.hashtag-rewrite-btn{width:100%;margin-top:8px;background:#2d8659;border:0;color:#fff;padding:9px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer}.hashtag-load-more{width:100%;margin-top:8px;background:#222;border:1px solid #333;color:#ccc;padding:9px;border-radius:10px;font-size:12px;cursor:pointer}.hashtag-loading{display:flex;align-items:center;gap:8px;padding:12px;color:#888;font-size:12px}.hashtag-spinner{width:16px;height:16px;border:2px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:ht-spin .8s linear infinite}@keyframes ht-spin{to{transform:rotate(360deg)}}
35
+ .wall-item{flex:0 0 260px;background:#141414;border:1px solid #2b2b2b;border-radius:10px;padding:8px}.wall-item-new{animation:wall-flash 1.8s ease-out}@keyframes wall-flash{0%{border-color:#f0c040;box-shadow:0 0 18px rgba(240,192,64,.35)}30%{border-color:#f0c040;box-shadow:0 0 12px rgba(240,192,64,.2)}100%{border-color:#2b2b2b;box-shadow:none}}.wall-thumb{width:100%;aspect-ratio:16/9;border-radius:8px;background:#222;overflow:hidden;margin-bottom:6px;position:relative}.wall-thumb img{width:100%;height:100%;object-fit:cover}.wall-video-badge{position:absolute;top:4px;right:4px;background:rgba(45,134,89,.9);color:#fff;font-size:10px;padding:2px 6px;border-radius:6px;font-weight:700}.wall-title{font-size:12px;color:#5cb87a;font-weight:800;line-height:1.3;margin-bottom:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wall-text{font-size:11px;color:#bbb;line-height:1.4;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.wall-actions{display:flex;gap:6px;margin-top:8px}.wall-actions button{flex:1;border:1px solid #333;background:#222;color:#ddd;border-radius:14px;padding:6px 8px;font-size:10px;cursor:pointer}.wall-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}
36
+ #progress-toast{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);background:#2d8659;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.4);display:none;white-space:nowrap}
37
+ .storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
38
+ /* VTV styles */
39
+ .vtv-wrap{margin:6px 4px;background:#111;border:1px solid #0066cc;border-radius:10px;overflow:hidden}
40
+ .vtv-head{display:flex;align-items:center;gap:8px;padding:8px 10px;background:linear-gradient(90deg,#003366,#1a1a1a)}
41
+ .vtv-title{font-size:13px;font-weight:800;color:#00ccff}
42
+ .vtv-badge{font-size:10px;font-weight:800;color:#00ccff;animation:vtvp 1.3s infinite}
43
+ @keyframes vtvp{0%,100%{opacity:1}50%{opacity:.3}}
44
+ .vtv-tabs{display:flex;gap:3px;padding:6px 8px;overflow-x:auto;scrollbar-width:none;background:#0d1a2a}
45
+ .vtv-tabs::-webkit-scrollbar{display:none}
46
+ .vtv-tab{padding:4px 8px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:10px;color:#8ab4d8;font-size:9px;cursor:pointer;white-space:nowrap;flex-shrink:0;transition:all .2s}
47
+ .vtv-tab:hover{background:#0b4a7a;color:#fff}
48
+ .vtv-tab.on{background:#0066cc;border-color:#00ccff;color:#fff;font-weight:700}
49
+ .vtv-tab.off{opacity:.35;pointer-events:none}
50
+ .vtv-frame{position:relative;width:100%;aspect-ratio:16/9;background:#000;min-height:180px}
51
+ .vtv-frame video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
52
+ .vtv-err{display:flex;align-items:center;justify-content:center;height:180px;color:#888;font-size:12px;text-align:center;padding:20px;flex-direction:column;gap:8px}
53
+ .vtv-err button{background:#0066cc;border:none;color:#fff;padding:6px 14px;border-radius:8px;font-size:11px;cursor:pointer}
54
+ .vtv-load{display:flex;align-items:center;justify-content:center;height:180px;color:#00ccff;font-size:12px;flex-direction:column;gap:8px}
55
+ .vtv-spinner{width:24px;height:24px;border:2px solid #333;border-top-color:#00ccff;border-radius:50%;animation:vtvspin .8s linear infinite}
56
+ @keyframes vtvspin{to{transform:rotate(360deg)}}
57
+ .vtv-epg{margin:0;padding:6px 10px;background:#0a1628;border-top:1px solid #1a2a3a}
58
+ .vtv-epg-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:4px}
59
+ .vtv-epg-title{font-size:10px;font-weight:700;color:#00ccff}
60
+ .vtv-epg-toggle{background:none;border:1px solid #2a3a4a;color:#8ab4d8;font-size:9px;padding:2px 8px;border-radius:6px;cursor:pointer}
61
+ .vtv-epg-list{display:flex;gap:4px;overflow-x:auto;scrollbar-width:none;padding-bottom:4px}
62
+ .vtv-epg-list::-webkit-scrollbar{display:none}
63
+ .vtv-epg-item{flex:0 0 auto;padding:3px 6px;background:#1a2a3a;border-radius:4px;font-size:8px;color:#8ab4d8;white-space:nowrap}
64
+ .vtv-epg-item.now{background:#0066cc;color:#fff;font-weight:700}
65
+ .vtv-epg-item .epg-t{font-size:7px;color:#6a8aaa}
66
+ .vtv-epg-item.now .epg-t{color:#aaccee}
67
+ .vtv-epg-item .epg-n{color:#ccc;font-size:8px}
68
+ .vtv-epg-item.now .epg-n{color:#fff}
69
+ </style>
70
+ </head>
71
+ <body>
72
+ <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · Video · AI · World Cup 2026</p></div>
73
+ <div class="cats" id="cat-bar"></div>
74
+ <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
75
+ <div id="view-cat" class="view"></div>
76
+ <div id="view-video" class="view"></div>
77
+ <div id="view-tiktok" class="view"></div>
78
+ <div id="view-article" class="view"></div>
79
+ <div class="match-overlay" id="match-overlay">
80
+ <div class="mo-header"><h3 id="mo-title">Chi tiết trận đấu</h3><button class="mo-close" onclick="closeMatch()">✕</button></div>
81
+ <div class="mo-tabs"><span class="mo-tab active" onclick="loadMatchTab('detail')">📋 Chi tiết</span><span class="mo-tab" onclick="loadMatchTab('comm')">Diễn biến</span><span class="mo-tab" onclick="loadMatchTab('stats')">Thống kê</span></div>
82
+ <div class="mo-body" id="mo-body"><div class="loading">Đang tải...</div></div>
83
+ </div>
84
+ <div id="progress-toast"></div>
85
+ <script>
86
+ var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
87
+ function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
88
+ function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
89
+ 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=''});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}}
90
+ function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
91
+ function doShare(title,url,img){const shareUrl=SPACE+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||'');if(navigator.share)navigator.share({title,url:shareUrl}).catch(()=>{});else navigator.clipboard.writeText(shareUrl).then(()=>alert('Đã sao chép!')).catch(()=>{})}
92
+ var SPACE=location.origin;
93
+ </script>
94
+ <script>
95
+ // === VNEWS Frontend v2 - Full Functions ===
96
+ // Updated: Voice selector + speed control + image gallery + auto voice detect
97
+
98
+ // === LOAD HOME ===
99
+ async function loadHome(){
100
+ const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
101
+ fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
102
+ fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
103
+ fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
104
+ fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
105
+ fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
106
+ fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
107
+ ]);
108
+ _hlLeagueData=hlLeagues;
109
+ _wc2026Data=wcData;
110
+ _shortsData=interleaveShorts(sh||[]);
111
+ _wallPosts=(wall&&wall.posts)||[];
112
+ let h='';
113
+ if(featured&&featured.home){
114
+ const sc=featured.status==='live'?'':'upcoming';
115
+ const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
116
+ // Safely encode for HTML attribute: escape quotes, angle brackets, ampersands
117
+ const eid = String(featured.event_id||'').replace(/[<>&"']/g,'');
118
+ const mUrl = String(featured.url||'').replace(/[<>&"']/g,'');
119
+ const fHome = String(featured.home||'').replace(/[<>&"']/g,'');
120
+ const fAway = String(featured.away||'').replace(/[<>&"']/g,'');
121
+ const fLeague = String(featured.league||'').replace(/[<>&"']/g,'');
122
+ const fScore = String(featured.score||'VS').replace(/[<>&"']/g,'');
123
+ const fHomeLogo = String(featured.home_logo||'').replace(/[<>&"']/g,'');
124
+ const fAwayLogo = String(featured.away_logo||'').replace(/[<>&"']/g,'');
125
+ const safeTitle = `${fHome} vs ${fAway} — ${fLeague}`;
126
+ h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${safeTitle}">`+
127
+ `<div class="fm-league">${fLeague}</div>`+
128
+ `<div class="fm-teams">`+
129
+ `<div class="fm-team"><img src="${fHomeLogo}" onerror="this.style.display='none'"><span>${fHome}</span></div>`+
130
+ `<div class="fm-score">${fScore}</div>`+
131
+ `<div class="fm-team"><img src="${fAwayLogo}" onerror="this.style.display='none'"><span>${fAway}</span></div>`+
132
+ `</div>`+
133
+ `<div class="fm-status ${sc}">${st}</div>`+
134
+ `</div>`;
135
+ }
136
+ h+=`<div class="ai-compose"><div class="ai-compose-title">🤖 AI viết bài</div><div class="ai-compose-row"><input id="topic-input" placeholder="Nhập chủ đề..."><button onclick="searchTopic()">Tìm nguồn</button></div><div class="ai-compose-row"><input id="url-input" placeholder="Dán URL bài viết..."><button class="secondary" onclick="rewriteUrl()">Rewrite</button></div><div id="hot-topics" class="hot-topic-row"></div></div>`;
137
+ h+='<div id="hashtag-box"></div>';
138
+ h+=`<div class="ls-section"><div class="ls-header"><h3>⚽ Livescore</h3></div><div class="ls-tabs"><span class="ls-tab active" data-tab="today" onclick="loadLivescore('today')">📅 Hôm nay</span><span class="ls-tab" data-tab="live" onclick="loadLivescore('live')">🔴 Live</span><span class="ls-tab" data-tab="incoming" onclick="loadLivescore('incoming')">⏰ Sắp tới</span><span class="ls-tab" data-tab="results" onclick="loadLivescore('results')">✅ Kết quả</span><span class="ls-tab" data-tab="bxh_nha" onclick="loadLivescore('bxh_nha')">🏆 NHA</span><span class="ls-tab" data-tab="bxh_laliga" onclick="loadLivescore('bxh_laliga')">🏆 La Liga</span></div><div class="ls-content" id="ls-content"><div class="loading">Đang tải...</div></div></div>`;
139
+ h+=`<div id="wc2026-live-section" class="wc2026-section"><div class="wc-header"><h2>🏆 World Cup 2026</h2><span class="wc-live-badge">● LIVE</span></div><div class="wc-tabs"><span class="wc-tab active" onclick="switchWCTab('news')">📰 Tin tức</span><span class="wc-tab" onclick="switchWCTab('fixtures')">📅 Lịch thi đấu</span><span class="wc-tab" onclick="switchWCTab('standings')">🏆 BXH</span><span class="wc-tab" onclick="switchWCTab('highlights')">🎬 Highlight</span><span class="wc-tab" onclick="switchWCTab('stats')">📊 Thống kê</span></div><div class="wc-content" id="wc-content"><div class="loading">Đang tải World Cup 2026...</div></div></div>`;
140
+ const wallPosts=_wallPosts;
141
+ const aiShorts=wallPosts.filter(p=>p.video);
142
+ if(aiShorts.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">';aiShorts.slice(0,20).forEach((p,i)=>{h+=`<div class="slider-item shorts-item" onclick="openShortAIFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`});h+='</div></div>';}
143
+ if(_shortsData.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">📱 Shorts Dân trí & SKĐS</span><span class="slider-note">Mới nhất · xen kẽ</span></div><div class="slider-track">';_shortsData.slice(0,30).forEach((a,i)=>{const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';h+=`<div class="slider-item shorts-item" onclick="openYTShortsFeed(${i})"><div class="slider-thumb shorts-thumb">${a.img?`<img src="${a.img}">`:''}<div class="card-play">▶</div></div><div class="slider-title"><span style="color:#f0c040;font-size:8px">${badge}</span> ${esc(a.title)}</div></div>`});h+='</div></div>';}
144
+ if(wallPosts.length){h+=`<div class="slider-wrap" id="ai-wall-wrap"><div class="slider-header"><span class="slider-label">🧱 Tường AI</span></div><div class="slider-track" id="ai-wall-track">`;wallPosts.slice(0,20).forEach((p,i)=>{h+=makeWallItem(p,i)});h+='</div></div>';}
145
+ const HL_CONFIG={"world-cup":{name:"World Cup 2026",emoji:"🌍"},"premier-league":{name:"Premier League",emoji:"🏴"},"champions-league":{name:"Champions League",emoji:"⭐"},"la-liga":{name:"La Liga",emoji:"🇪🇸"},"serie-a":{name:"Serie A",emoji:"🇮🇹"},"bundesliga":{name:"Bundesliga",emoji:"🇩🇪"},"friendly":{name:"Giao hữu",emoji:"🤝"}};
146
+ for(const[key,cfg] of Object.entries(HL_CONFIG)){const vids=hlLeagues[key];if(!vids||!vids.length)continue;h+=`<div class="slider-wrap"><div class="slider-header"><span class="slider-label">${cfg.emoji} ${cfg.name}</span></div><div class="slider-track">`;vids.slice(0,8).forEach((a,i)=>{h+=`<div class="slider-item" onclick="openHighlightFeed('${key}',${i})"><div class="slider-thumb">${a.img?`<img src="${a.img}">`:''}<div class="card-play">▶</div></div><div class="slider-title">${esc(a.title)}</div></div>`});h+='</div></div>';}
147
+ if(ai&&ai.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">🤖 Ứng dụng AI</span></div><div class="slider-track">';ai.slice(0,12).forEach(a=>{h+=`<div class="slider-item" onclick="readArticle('${esc(a.link)}')"><div class="slider-thumb">${a.img?`<img src="${a.img}">`:''}</div><div class="slider-title">${esc(a.title)}</div></div>`});h+='</div></div>';}
148
+ document.getElementById('view-home').innerHTML=h;
149
+ loadLivescore('today');loadHotTopics();
150
+ if(_wc2026Data)switchWCTab('news');
151
+ }
152
+
153
+ // === WALL POST HELPERS ===
154
+ function makeWallItem(p,i){
155
+ const hasVideo = p.video && p.video.length > 0;
156
+ const thumbContent = p.img
157
+ ? `<img src="${esc(p.img)}" onerror="this.style.display='none'">`
158
+ : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
159
+ const videoBadge = hasVideo
160
+ ? `<div class="wall-video-badge">🎬</div>`
161
+ : '';
162
+ const videoBtn = hasVideo
163
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
164
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
165
+
166
+ return `<div class="wall-item" id="wall-item-${esc(p.id||i)}">
167
+ <div class="wall-thumb">
168
+ ${thumbContent}
169
+ ${videoBadge}
170
+ </div>
171
+ <div class="wall-title">${esc(p.title)}</div>
172
+ <div class="wall-text">${esc((p.text||'').slice(0,180))}</div>
173
+ <div class="wall-actions">
174
+ <button class="primary" onclick="readWallPost(${i})">Xem</button>
175
+ ${videoBtn}
176
+ </div>
177
+ </div>`;
178
+ }
179
+
180
+ // === GENERATE SHORT VIDEO FOR A WALL POST ===
181
+ async function makeShortVideo(postId, btn, voice, speed){
182
+ if(!postId)return;
183
+ const origText = btn ? btn.textContent : '🎬 Tạo Video';
184
+ if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
185
+ toast('⏳ Đang tạo video shorts...');
186
+ try{
187
+ let url = '/api/ai/short/'+encodeURIComponent(postId);
188
+ const params = [];
189
+ if(voice) params.push('voice='+encodeURIComponent(voice));
190
+ if(speed) params.push('speed='+encodeURIComponent(speed));
191
+ if(params.length) url += '?' + params.join('&');
192
+ const r = await fetch(url, {method:'POST'});
193
+ const j = await r.json();
194
+ if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video');
195
+ toast('✅ Đã tạo video shorts!');
196
+ const p = _wallPosts.find(x => String(x.id) === String(postId));
197
+ if(p){
198
+ p.video = j.video;
199
+ const itemId = 'wall-item-'+postId;
200
+ const el = document.getElementById(itemId);
201
+ if(el){
202
+ const idx = _wallPosts.indexOf(p);
203
+ el.outerHTML = makeWallItem(p, idx);
204
+ const newEl = document.getElementById(itemId);
205
+ if(newEl) newEl.className = 'wall-item wall-item-new';
206
+ }
207
+ }
208
+ refreshShortAISlider();
209
+ }catch(e){
210
+ toast('❌ '+e.message);
211
+ if(btn){btn.disabled=false;btn.textContent=origText;}
212
+ }
213
+ }
214
+
215
+ // Refresh Short AI slider after video generation
216
+ function refreshShortAISlider(){
217
+ const aiShorts = _wallPosts.filter(p=>p.video);
218
+ let shortAISection = document.getElementById('short-ai-section');
219
+ if(aiShorts.length === 0){
220
+ if(shortAISection) shortAISection.remove();
221
+ return;
222
+ }
223
+ if(shortAISection){
224
+ const track = shortAISection.querySelector('.slider-track');
225
+ if(track){
226
+ let h = '';
227
+ aiShorts.slice(0,20).forEach((p,i)=>{
228
+ h+=`<div class="slider-item shorts-item" onclick="openShortAIFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${esc(p.video)}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`;
229
+ });
230
+ track.innerHTML = h;
231
+ }
232
+ }
233
+ }
234
+
235
+ function prependWallPost(post){
236
+ _wallPosts.unshift(post);
237
+ const track=document.getElementById('ai-wall-track');
238
+ const wrap=document.getElementById('ai-wall-wrap');
239
+ const homeEl=document.getElementById('view-home');
240
+ if(!track||!wrap){
241
+ if(homeEl){
242
+ let insertBefore=homeEl.querySelector('.slider-wrap');
243
+ const newWrap=document.createElement('div');
244
+ newWrap.className='slider-wrap';
245
+ newWrap.id='ai-wall-wrap';
246
+ newWrap.innerHTML=`<div class="slider-header"><span class="slider-label">🧱 Tường AI</span></div><div class="slider-track" id="ai-wall-track">${makeWallItem(post,0)}</div>`;
247
+ if(insertBefore){
248
+ homeEl.insertBefore(newWrap,insertBefore);
249
+ }else{
250
+ homeEl.appendChild(newWrap);
251
+ }
252
+ const firstItem=newWrap.querySelector('.wall-item');
253
+ if(firstItem)firstItem.className='wall-item wall-item-new';
254
+ }
255
+ return;
256
+ }
257
+ const div=document.createElement('div');
258
+ div.className='wall-item wall-item-new';
259
+ div.id='wall-item-'+(post.id||'new-'+Date.now());
260
+ const hasVideo = post.video && post.video.length > 0;
261
+ const thumbContent = post.img
262
+ ? `<img src="${esc(post.img)}" onerror="this.style.display='none'">`
263
+ : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
264
+ const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
265
+ const videoBtn = hasVideo
266
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
267
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
268
+ div.innerHTML=`<div class="wall-thumb">${thumbContent}${videoBadge}</div><div class="wall-title">${esc(post.title)}</div><div class="wall-text">${esc((post.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(0)">Xem</button>${videoBtn}</div>`;
269
+ track.prepend(div);
270
+ track.scrollTo({left:0,behavior:'smooth'});
271
+ if(hasVideo) refreshShortAISlider();
272
+ }
273
+
274
+ // === REST OF FUNCTIONS ===
275
+ let _shortsData=[];
276
+ let _wallPosts=[];
277
+ let _currentView='home';
278
+ let _currentEventId=null;
279
+ let _currentMatchUrl=null;
280
+ 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<dt.length||j<sk.length){if(i<dt.length)result.push(dt[i++]);if(j<sk.length)result.push(sk[j++]);}return result;}
281
+ let _htPage=0,_htTopic='';
282
+ 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`<button class="hot-chip" onclick="searchTopic('${topicText.replace(/'/g,"\\'")}')">${esc(t.label)}</button>`;}).join('');if(j.topics&&j.topics[0]){const firstTopic=j.topics[0].topic||j.topics[0].label.replace(/^#/,'');setTimeout(()=>searchTopic(firstTopic),800);}}
283
+ 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);}
284
+ async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div class="hashtag-loading"><div class="hashtag-spinner"></div>Đang tìm...</div></div>`;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=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div style="color:#888;padding:8px">Không tìm được bài viết liên quan</div></div>`;return;}let h='';if(page===0)h=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)} <span style="font-size:10px;color:#888">(${j.total} bài từ 8 nguồn)</span></h3><div id="ht-list">`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`<div class="hashtag-src-item" onclick="readArticle('${esc(s.url)}')"><div class="hashtag-src-img" id="ht-img-${idx}"></div><div class="hashtag-src-text"><div class="hashtag-src-title">${esc(s.title)}</div><div class="hashtag-src-via">${esc(s.via||'')}</div></div></div>`;});if(page===0){h+=`</div><button class="hashtag-rewrite-btn" onclick="rewriteHashtag('${esc(topic).replace(/'/g,"\\'")}')">🤖 Rewrite AI tổng hợp & đăng tường</button>`;if(j.has_more)h+=`<button class="hashtag-load-more" id="ht-more" onclick="loadMoreHashtag()">Tải thêm ▼</button>`;h+=`</div>`;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=`<img src="${esc(d.og_image||d.img)}" onerror="this.style.display='none'">`;}}).catch(()=>{});});}catch(e){box.innerHTML=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div style="color:#e74c3c;padding:8px">Lỗi: ${esc(e.message)}</div></div>`;}}
285
+ function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
286
+ 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';}}}
287
+ 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='<div class="loading">Đang tải...</div>';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:'<div class="loading">Không có dữ liệu</div>';bindMatchClicks(el);}catch(e){el.innerHTML='<div class="loading">Lỗi</div>';}}
288
+ function bindMatchClicks(el){
289
+ if(!el) return;
290
+ el.querySelectorAll('.match-detail').forEach(md=>{
291
+ md.style.cursor='pointer';
292
+ // Remove old listeners to avoid duplicates (mark as bound)
293
+ if(md._bound) return;
294
+ md._bound = true;
295
+ md.addEventListener('click',function(e){
296
+ // Don't intercept clicks on interactive elements inside the row
297
+ const tag = e.target.tagName?.toLowerCase();
298
+ if(tag === 'a' || tag === 'button' || tag === 'input') {
299
+ e.preventDefault();
300
+ e.stopPropagation();
301
+ }
302
+ // Find ANY link with /tran-dau/ inside this match-detail row
303
+ const links = this.querySelectorAll('a[href*="/tran-dau/"]');
304
+ let bestA = null;
305
+ links.forEach(a => {
306
+ const href = a.getAttribute('href') || '';
307
+ // Prefer links with both event_id AND slug (fuller URL)
308
+ if(href.match(/\/tran-dau\/\d+\/(centre|preview|quan-cau|video)\//)) {
309
+ bestA = a;
310
+ } else if(!bestA && href.match(/\/tran-dau\/\d+\//)) {
311
+ bestA = a;
312
+ }
313
+ });
314
+ if(!bestA) return;
315
+ e.preventDefault();
316
+ e.stopPropagation();
317
+ const href = bestA.getAttribute('href') || '';
318
+ const m = href.match(/\/tran-dau\/(\d+)\//);
319
+ if(m){
320
+ const fullUrl = href.startsWith('http') ? href : 'https://bongda.com.vn' + href;
321
+ openMatch(m[1], fullUrl);
322
+ }
323
+ });
324
+ });
325
+ // Prevent default navigation on all links inside livescore (but let match-detail click handler work)
326
+ el.querySelectorAll('a').forEach(a=>{
327
+ a.addEventListener('click',e=>{
328
+ e.preventDefault();
329
+ e.stopPropagation();
330
+ });
331
+ });
332
+ }
333
+ 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')}
334
+ function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
335
+ 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='<div class="loading">Đang tải...</div>';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='<div class="loading">Lỗi máy chủ ('+r.status+')</div>';return}const d=await r.json();if(d.error){el.innerHTML='<div class="loading">'+esc(d.error)+'</div>';return}if(tab==='detail'&&typeof renderMatchDetail==='function'){renderMatchDetail(el,d);return}el.innerHTML=d.html||'<div class="loading">Không có dữ liệu</div>'}catch(e){el.innerHTML='<div class="loading">Lỗi</div>'}}
336
+ 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;}}
337
+ 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};}}
338
+ 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[];}}
339
+ 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[];}}
340
+ function buildTikTokSlide(opts){return`<div class="tiktok-slide" data-vid="${esc(opts.videoId)}">${opts.vtag}<div class="tiktok-bottom"><span class="badge ${opts.badgeClass||'badge-fpt'}">${opts.badge||''}</span><p class="tiktok-title">${esc(opts.title)}</p></div><div class="tiktok-right"><button class="tiktok-right-btn" onclick="event.stopPropagation();doView('${esc(opts.videoId)}',this)"><div class="icon">👁</div><div class="count" id="vc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();doLike('${esc(opts.videoId)}',this)"><div class="icon">❤️</div><div class="count" id="lc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();toggleComments('${esc(opts.videoId)}',${opts.idx})"><div class="icon">💬</div><div class="count" id="cc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();doShare('${esc(opts.title)}','${esc(opts.shareUrl||'')}','')"><div class="icon">📤</div></button>${opts.extraBtn||''}</div><span class="tiktok-counter">${opts.idx+1}/${opts.total}</span><div class="inline-comments" id="cmt-inline-${opts.idx}" style="display:none"></div></div>`;}
341
+ 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);}}
342
+ 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);}}
343
+ 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);}
344
+ async function loadCounters(videoIds){for(let i=0;i<videoIds.length;i++){const id=videoIds[i];if(!id)continue;const j=await getInteractions(id);const vc=document.getElementById('vc-'+i);if(vc)vc.textContent=fmtNum(j.views);const lc=document.getElementById('lc-'+i);if(lc)lc.textContent=fmtNum(j.likes);const cc=document.getElementById('cc-'+i);if(cc)cc.textContent=fmtNum(j.comments);}}
345
+ 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='<div style="padding:8px;color:#888;font-size:11px">Đang tải...</div>';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);}
346
+ function renderInlineComments(panel,videoId,idx,cmts){let h='<div class="inline-cmt-header"><span>💬 Bình luận</span><button onclick="document.getElementById(\'cmt-inline-'+idx+'\').style.display=\'none\'">✕</button></div><div class="inline-cmt-list">';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`<div class="inline-cmt-item"><span class="inline-cmt-time">${c.time||''}</span>${esc(c.text)}</div>`;});}else{h+='<div style="color:#777;font-size:11px;padding:4px">Chưa có bình luận</div>';}h+=`</div><div class="inline-cmt-input"><input id="cmt-input-${idx}" placeholder="Viết bình luận..." onkeydown="if(event.key==='Enter')submitInlineCmt('${esc(videoId)}',${idx})"><button onclick="submitInlineCmt('${esc(videoId)}',${idx})">Gửi</button></div>`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;}
347
+ 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);}
348
+ 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<bestD){bestD=d;best=i}});if(best>=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)}
349
+ async function openHighlightFeed(league,idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';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='<div class="loading">Không có video</div>';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='<div class="loading">Không tìm thấy video</div>';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=`<button class="back-btn" onclick="switchCat('home')">← Highlight</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${v.poster}"`:'';const vtag=isYT?`<iframe data-yt-src="${v.src}" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"></iframe>`:isHLS?`<video playsinline preload="none"${poster} data-hls="${v.src}" loop controls></video>`:`<video playsinline preload="none"${poster} loop controls><source src="${v.src}" type="video/mp4"></video>`;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:`<button class="tiktok-right-btn" onclick="event.stopPropagation();this.closest('.tiktok-slide').classList.toggle('ratio-wide')"><div class="icon">⬜</div><div class="count">16:9</div></button>`});});h+='</div></div>';el.innerHTML=h;initTikTokFeed();}
350
+ async function openYTShortsFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';const arts=_shortsData.length?_shortsData:await fetch('/api/shorts').then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='<div class="loading">Không có shorts</div>';return}const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;let h=`<button class="back-btn" onclick="switchCat('home')">← Shorts</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((v,i)=>{const id=v.id||'';const src=`https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;const vtag=`<iframe data-yt-src="${src}" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"></iframe>`;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+='</div></div>';el.innerHTML=h;initTikTokFeed();}
351
+ async function openShortAIFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';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='<div class="loading">Chưa có Short AI</div>';return}const ordered=startIdx>0?[...vids.slice(startIdx),...vids.slice(0,startIdx)]:vids;let h=`<button class="back-btn" onclick="switchCat('home')">← Short AI</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((p,i)=>{const vtag=`<video src="${p.video}" playsinline loop controls></video>`;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+='</div></div>';el.innerHTML=h;initTikTokFeed();}
352
+ async function readArticle(url){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='<div class="loading">Đang tải...</div>';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=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><h1 class="article-title">${esc(data.title)}</h1>`;if(data.summary)h+=`<div class="article-summary">${esc(data.summary)}</div>`;const seen={};data.body.forEach(b=>{if(b.type==='p')h+=`<p class="article-p">${b.text}</p>`;else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+=`<img class="article-img" src="${esc(b.src)}" onerror="this.style.display='none'">`}else if(b.type==='heading')h+=`<h2 class="article-h2">${esc(b.text)}</h2>`});h+=`<div class="article-actions"><button class="primary" onclick="rewriteArticle()">🤖 Rewrite AI đăng tường</button><button onclick="doShare('${esc(data.title)}','${esc(url)}','${esc(data.og_image||'')}')">📤</button><button onclick="window.open('${esc(url)}','_blank')">🔗 Gốc</button></div><div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="ask-q" placeholder="Hỏi về bài viết..."></textarea><button onclick="askAI()">Hỏi</button><div id="ask-a" class="article-ai-answer"></div></div></div>`;el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}el.innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="loading"><p>Không đọc được.</p><a href="${esc(url)}" target="_blank" style="color:#5cb87a">Mở gốc →</a></div>`;}
353
+ 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)}}
354
+ 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)}}
355
+ 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}}
356
+ async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
357
+ const images = p.images || [];
358
+ let imgGallery = '';
359
+ if(images.length > 0){
360
+ imgGallery = '<div class="article-image-gallery">';
361
+ images.forEach((imgUrl, idx) => {
362
+ if(idx === 0){
363
+ imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;
364
+ } else {
365
+ if(idx === 1) imgGallery += '<div class="gallery-thumbs">';
366
+ imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;
367
+ }
368
+ });
369
+ if(images.length > 1) imgGallery += '</div>';
370
+ imgGallery += '</div>';
371
+ }
372
+ const hasVideo = p.video && p.video.length > 0;
373
+ const voiceOptions = [
374
+ {id:'hoaimy', label:'🎙️ Nữ — Hoài My'},
375
+ {id:'namminh', label:'🎙️ Nam — Nam Minh'},
376
+ ];
377
+ let voiceSelector = '';
378
+ if(!hasVideo){
379
+ voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
380
+ voiceOptions.forEach(v=>{
381
+ voiceSelector += `<button class="tts-voice-btn" onclick="document.querySelectorAll('.tts-voice-btn').forEach(b=>b.classList.remove('active'));this.classList.add('active');document.getElementById('selected-voice').value='${v.id}'">${v.label}</button>`;
382
+ });
383
+ voiceSelector += `</div><div class="tts-speed-row"><span>Tốc độ:</span><select id="selected-speed"><option value="1.0">1.0x — Bình thường</option><option value="1.2" selected>1.2x — Nhanh</option><option value="1.5">1.5x — Rất nhanh</option><option value="0.8">0.8x — Chậm</option></select></div>`;
384
+ voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
385
+ }
386
+ document.getElementById('view-article').innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${esc(p.title)}</h1>${imgGallery}<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>${hasVideo?`<video class="article-img" src="${esc(p.video)}" controls playsinline style="max-height:400px"></video>`:''}<div class="article-actions">${hasVideo?`<button onclick="openShortAIFeed(${i})">🎬 Xem Short</button>${voiceSelector}<button class="primary" onclick="makeShortVideo('${esc(p.id)}',this,document.getElementById('selected-voice')?.value,parseFloat(document.getElementById('selected-speed')?.value)||1.2)">🔄 Tạo lại Short</button>`:`${voiceSelector}<button class="primary" onclick="makeShortVideo('${esc(p.id)}',this,document.getElementById('selected-voice')?.value,parseFloat(document.getElementById('selected-speed')?.value)||1.2)">🎬 Tạo Video Shorts</button>`}<button onclick="doShare('${esc(p.title)}','${SPACE}','${esc(p.img||'')}')">📤</button></div></div>`;
387
+ const firstVoiceBtn = document.querySelector('.tts-voice-btn');
388
+ if(firstVoiceBtn) firstVoiceBtn.classList.add('active');
389
+ window.scrollTo(0,0)}
390
+ async function loadNewsTab(){const el=document.getElementById('view-cat');el.innerHTML='<div class="loading">Đang tải...</div>';try{const r=await fetch('/api/homepage');const news=await r.json();if(!news.length){el.innerHTML='<div class="loading">Không có tin</div>';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+=`<div class="section-title">${g}</div><div class="grid">`;arts.slice(0,6).forEach(a=>{h+=`<div class="card" onclick="readArticle('${esc(a.link)}')"><div class="card-img">${a.img?`<img src="${a.img}">`:''}</div><div class="card-body"><span class="badge badge-vne">${esc(a.source||'VnE')}</span><div class="card-title">${esc(a.title)}</div></div></div>`});h+='</div>'}el.innerHTML=h}catch(e){el.innerHTML='<div class="loading">Lỗi</div>'}}
391
+ async function loadCat(id){const el=document.getElementById('view-cat');el.innerHTML='<div class="loading">Đang tải...</div>';const arts=await fetch('/api/category/'+id).then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='<div class="loading">Không có tin</div>';return}let h='<div class="grid">';arts.forEach(a=>{h+=`<div class="card" onclick="readArticle('${esc(a.link)}')"><div class="card-img">${a.img?`<img src="${a.img}">`:''}</div><div class="card-body"><span class="badge badge-vne">${esc(a.source||'')}</span><div class="card-title">${esc(a.title)}</div></div></div>`});h+='</div>';el.innerHTML=h}
392
+ 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(()=>{});
393
+
394
+ // === AUTO-OPEN SHARE LINKS (/s?url=... sets pending_article) ===
395
+ (function(){
396
+ try{
397
+ const pa=localStorage.getItem('pending_article');
398
+ const pv=localStorage.getItem('pending_video');
399
+ if(pa){
400
+ localStorage.removeItem('pending_article');
401
+ setTimeout(()=>{
402
+ if(typeof readArticle==='function') readArticle(pa);
403
+ },1500);
404
+ }
405
+ if(pv){
406
+ localStorage.removeItem('pending_video');
407
+ try{
408
+ const v=JSON.parse(pv);
409
+ if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500);
410
+ }catch(e){}
411
+ }
412
+ }catch(e){}
413
+ })();
414
+ </script>
415
+ <script>
416
+ // === VNEWS — VTV1-VTV10 + VTVPrime LIVE CHANNELS + EPG ===
417
+ // Uses backend /api/vtv/streams for stream URLs
418
+ // Default channel: VTV6 | No double-load | EPG schedule
419
+
420
+ (function(){
421
+ if(window._ytLiveLoaded) return;
422
+ window._ytLiveLoaded = true;
423
+
424
+ const CHANNELS = [
425
+ {id:'vtv1', name:'VTV1', badge:'Tin tức'},
426
+ {id:'vtv2', name:'VTV2', badge:'Khoa học'},
427
+ {id:'vtv3', name:'VTV3', badge:'Giải trí'},
428
+ {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
429
+ {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
430
+ {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
431
+ {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
432
+ {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
433
+ {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
434
+ {id:'vtv10', name:'VTV10', badge:'VTV10'},
435
+ {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
436
+ ];
437
+
438
+ // ===== EPG — Lịch phát sóng mẫu cho từng kênh =====
439
+ const EPG = {
440
+ vtv1: [
441
+ {t:'06:00',n:'Nhật ký ngày mai'},{t:'07:00',n:'Thời sự sáng'},{t:'09:00',n:'Thời sự'},
442
+ {t:'12:00',n:'Thời sự trưa'},{t:'15:00',n:'Thời sự chiều'},{t:'19:00',n:'Thời sự tối'},
443
+ {t:'21:00',n:'Thời sự đêm'},{t:'23:00',n:'Nhật ký ngày mai'},
444
+ ],
445
+ vtv2: [
446
+ {t:'06:00',n:'Khoa học & Công nghệ'},{t:'08:00',n:'Thế giới tự nhiên'},{t:'10:00',n:'Khoa học 360'},
447
+ {t:'12:00',n:'Đi tìm giải pháp'},{t:'14:00',n:'Sức khỏe & Cuộc sống'},{t:'16:00',n:'Khoa học cho mọi nhà'},
448
+ {t:'18:00',n:'Thế giới động vật'},{t:'20:00',n:'Khoa học & Tương lai'},{t:'22:00',n:'Tài liệu khoa học'},
449
+ ],
450
+ vtv3: [
451
+ {t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'10:00',n:'Gameshow'},
452
+ {t:'12:00',n:'Âm nhạc'},{t:'14:00',n:'Phim truyện'},{t:'16:00',n:'Giải trí chiều'},
453
+ {t:'18:00',n:'Tạp kỹ thuật số'},{t:'20:00',n:'Phim truyện đặc biệt'},{t:'22:00',n:'Đêm giải trí'},
454
+ ],
455
+ vtv4: [
456
+ {t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'10:00',n:'Culture'},
457
+ {t:'12:00',n:'Midday News'},{t:'14:00',n:'Documentary'},{t:'16:00',n:'Sports'},
458
+ {t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'},{t:'22:00',n:'Nightline'},
459
+ ],
460
+ vtv5: [
461
+ {t:'06:00',n:'Thời sự miền Nam'},{t:'08:00',n:'Chương trình thiếu nhi'},{t:'10:00',n:'Phim truyện'},
462
+ {t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao miền Nam'},
463
+ {t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'},{t:'22:00',n:'Thời sự tối'},
464
+ ],
465
+ vtv6: [
466
+ {t:'06:00',n:'Khởi động ngày mới'},{t:'08:00',n:'Thanh niên & Sáng tạo'},{t:'10:00',n:'Thế giới trẻ'},
467
+ {t:'12:00',n:'Nhịp sống trẻ'},{t:'14:00',n:'Thể thao tuổi trẻ'},{t:'16:00',n:'Giải trí thanh niên'},
468
+ {t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'},{t:'22:00',n:'Thanh niên & Đêm'},
469
+ ],
470
+ vtv7: [
471
+ {t:'06:00',n:'Giáo dục sáng'},{t:'08:00',n:'Học mọi lúc'},{t:'10:00',n:'Kỹ năng sống'},
472
+ {t:'12:00',n:'Giáo dục trưa'},{t:'14:00',n:'Học trực tuyến'},{t:'16:00',n:'Thiếu nhi'},
473
+ {t:'18:00',n:'Giáo dục chiều'},{t:'20:00',n:'Tài liệu giáo dục'},{t:'22:00',n:'Học suốt đời'},
474
+ ],
475
+ vtv8: [
476
+ {t:'06:00',n:'Thời sự miền Trung'},{t:'08:00',n:'Văn hóa miền Trung'},{t:'10:00',n:'Phim truyện'},
477
+ {t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao miền Trung'},
478
+ {t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'},{t:'22:00',n:'Thời sự tối'},
479
+ ],
480
+ vtv9: [
481
+ {t:'06:00',n:'Thời sự miền Bắc'},{t:'08:00',n:'Văn hóa miền Bắc'},{t:'10:00',n:'Phim truyện'},
482
+ {t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao miền Bắc'},
483
+ {t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'},{t:'22:00',n:'Thời sự tối'},
484
+ ],
485
+ vtv10: [
486
+ {t:'06:00',n:'Thời sự Tây Nam Bộ'},{t:'08:00',n:'Văn hóa đồng bằng'},{t:'10:00',n:'Phim truyện'},
487
+ {t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao Tây Nam Bộ'},
488
+ {t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'},{t:'22:00',n:'Thời sự tối'},
489
+ ],
490
+ vtvprime: [
491
+ {t:'06:00',n:'Prime Morning'},{t:'08:00',n:'Prime Cinema'},{t:'10:00',n:'Prime Sports'},
492
+ {t:'12:00',n:'Prime News'},{t:'14:00',n:'Prime Drama'},{t:'16:00',n:'Prime Entertainment'},
493
+ {t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'},{t:'22:00',n:'Prime Late'},
494
+ ],
495
+ };
496
+
497
+ // ALL external streams need proxy — VTVGo/fptplay CDNs don't send CORS headers
498
+ const STREAMS = {};
499
+ let _currentCh = null;
500
+ let _hls = null;
501
+ let _loading = false;
502
+ let _epgVisible = false;
503
+
504
+ const s = document.createElement('style');
505
+ s.textContent = `
506
+ .vtv-wrap{margin:6px 4px;background:#111;border:1px solid #0066cc;border-radius:10px;overflow:hidden}
507
+ .vtv-head{display:flex;align-items:center;gap:8px;padding:8px 10px;background:linear-gradient(90deg,#003366,#1a1a1a)}
508
+ .vtv-title{font-size:13px;font-weight:800;color:#00ccff}
509
+ .vtv-badge{font-size:10px;font-weight:800;color:#00ccff;animation:vtvp 1.3s infinite}
510
+ @keyframes vtvp{0%,100%{opacity:1}50%{opacity:.3}}
511
+ .vtv-tabs{display:flex;gap:3px;padding:6px 8px;overflow-x:auto;scrollbar-width:none;background:#0d1a2a}
512
+ .vtv-tabs::-webkit-scrollbar{display:none}
513
+ .vtv-tab{padding:4px 8px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:10px;color:#8ab4d8;font-size:9px;cursor:pointer;white-space:nowrap;flex-shrink:0;transition:all .2s}
514
+ .vtv-tab:hover{background:#0b4a7a;color:#fff}
515
+ .vtv-tab.on{background:#0066cc;border-color:#00ccff;color:#fff;font-weight:700}
516
+ .vtv-tab.off{opacity:.35;pointer-events:none}
517
+ .vtv-frame{position:relative;width:100%;aspect-ratio:16/9;background:#000;min-height:180px}
518
+ .vtv-frame video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
519
+ .vtv-err{display:flex;align-items:center;justify-content:center;height:180px;color:#888;font-size:12px;text-align:center;padding:20px;flex-direction:column;gap:8px}
520
+ .vtv-err button{background:#0066cc;border:none;color:#fff;padding:6px 14px;border-radius:8px;font-size:11px;cursor:pointer}
521
+ .vtv-load{display:flex;align-items:center;justify-content:center;height:180px;color:#00ccff;font-size:12px;flex-direction:column;gap:8px}
522
+ .vtv-spinner{width:24px;height:24px;border:2px solid #333;border-top-color:#00ccff;border-radius:50%;animation:vtvspin .8s linear infinite}
523
+ @keyframes vtvspin{to{transform:rotate(360deg)}}
524
+ .vtv-epg{margin:0;padding:6px 10px;background:#0a1628;border-top:1px solid #1a2a3a}
525
+ .vtv-epg-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:4px}
526
+ .vtv-epg-title{font-size:10px;font-weight:700;color:#00ccff}
527
+ .vtv-epg-toggle{background:none;border:1px solid #2a3a4a;color:#8ab4d8;font-size:9px;padding:2px 8px;border-radius:6px;cursor:pointer}
528
+ .vtv-epg-list{display:flex;gap:4px;overflow-x:auto;scrollbar-width:none;padding-bottom:4px}
529
+ .vtv-epg-list::-webkit-scrollbar{display:none}
530
+ .vtv-epg-item{flex:0 0 auto;padding:3px 6px;background:#1a2a3a;border-radius:4px;font-size:8px;color:#8ab4d8;white-space:nowrap}
531
+ .vtv-epg-item.now{background:#0066cc;color:#fff;font-weight:700}
532
+ .vtv-epg-item .epg-t{font-size:7px;color:#6a8aaa}
533
+ .vtv-epg-item.now .epg-t{color:#aaccee}
534
+ .vtv-epg-item .epg-n{color:#ccc;font-size:8px}
535
+ .vtv-epg-item.now .epg-n{color:#fff}
536
+ `;
537
+ document.head.appendChild(s);
538
+
539
+ function getCurrentHour(){
540
+ return new Date().getHours();
541
+ }
542
+
543
+ function buildEPGHTML(chId){
544
+ const epg = EPG[chId] || [];
545
+ if(!epg.length) return '';
546
+ const curH = getCurrentHour();
547
+ let items = '';
548
+ epg.forEach(item => {
549
+ const itemH = parseInt(item.t.split(':')[0], 10);
550
+ const isNow = itemH <= curH && (itemH + 2) > curH;
551
+ items += `<div class="vtv-epg-item${isNow?' now':''}"><div class="epg-t">${item.t}</div><div class="epg-n">${item.n}</div></div>`;
552
+ });
553
+ return `<div class="vtv-epg" id="vtv-epg">' +
554
+ '<div class="vtv-epg-header"><span class="vtv-epg-title">📋 Lịch phát sóng</span>' +
555
+ '<button class="vtv-epg-toggle" onclick="window._vtvToggleEPG()">Ẩn/Hiện</button></div>' +
556
+ '<div class="vtv-epg-list" id="vtv-epg-list">' + items + '</div></div>';
557
+ }
558
+
559
+ window._vtvToggleEPG = function(){
560
+ const list = document.getElementById('vtv-epg-list');
561
+ if(list) list.style.display = list.style.display === 'none' ? 'flex' : 'none';
562
+ };
563
+
564
+ async function loadAllStreams(){
565
+ if(_loading) return;
566
+ _loading = true;
567
+ const loadEl = document.getElementById('vtv-load');
568
+ if(loadEl) loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang tải danh sách kênh...';
569
+
570
+ try {
571
+ const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(10000)});
572
+ if(r.ok){
573
+ const data = await r.json();
574
+ CHANNELS.forEach(ch => {
575
+ const info = data[ch.id];
576
+ if(info && info.stream_url){
577
+ // Always proxy through backend to avoid CORS issues
578
+ const url = '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(info.stream_url);
579
+ STREAMS[ch.id] = [url];
580
+ } else {
581
+ STREAMS[ch.id] = [];
582
+ }
583
+ });
584
+ }
585
+ } catch(e) {
586
+ console.warn('VTV API error:', e);
587
+ }
588
+
589
+ CHANNELS.forEach(ch => {
590
+ const tab = document.getElementById('vtvt-'+ch.id);
591
+ if(tab){
592
+ if(STREAMS[ch.id] && STREAMS[ch.id].length > 0){
593
+ tab.classList.remove('off');
594
+ tab.textContent = ch.name;
595
+ } else {
596
+ tab.style.opacity = '0.35';
597
+ tab.textContent = ch.name + ' ✕';
598
+ }
599
+ }
600
+ });
601
+ _loading = false;
602
+ }
603
+
604
+ function buildBlock(){
605
+ const w = document.createElement('div');
606
+ w.className = 'vtv-wrap';
607
+ w.id = 'vtv-block';
608
+ let tabs = '';
609
+ CHANNELS.forEach(ch => {
610
+ tabs += '<button class="vtv-tab off" id="vtvt-'+ch.id+'" onclick="window._vtvPlay(\''+ch.id+'\')">'+ch.name+'</button>';
611
+ });
612
+ w.innerHTML =
613
+ '<div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>' +
614
+ '<div class="vtv-tabs">' + tabs + '</div>' +
615
+ '<div class="vtv-frame">' +
616
+ '<div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>' +
617
+ '<video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>' +
618
+ '<div class="vtv-err" id="vtv-err" style="display:none"><span id="vtv-err-msg">Không thể tải kênh</span><button onclick="window._vtvRetry()">Thử lại</button></div>' +
619
+ '</div>';
620
+ return w;
621
+ }
622
+
623
+ // ===== PIN BLOCK — called only once via loadHome wrapper =====
624
+ function pinBlock(){
625
+ const h = document.getElementById('view-home');
626
+ if(!h || document.getElementById('vtv-block')) return;
627
+ h.insertBefore(buildBlock(), h.firstChild);
628
+ loadAllStreams().then(() => {
629
+ // Default to VTV6 if available, otherwise first available channel
630
+ const tryOrder = ['vtv6','vtv1','vtv2','vtv3','vtv4','vtv5','vtv7','vtv8','vtv9','vtv10'];
631
+ for(const chId of tryOrder){
632
+ if(STREAMS[chId] && STREAMS[chId].length > 0){
633
+ setTimeout(() => window._vtvPlay(chId), 300);
634
+ return;
635
+ }
636
+ }
637
+ });
638
+ }
639
+
640
+ window._vtvRetry = function(){
641
+ if(_currentCh) window._vtvPlay(_currentCh);
642
+ };
643
+
644
+ window._vtvPlay = function(chId){
645
+ const ch = CHANNELS.find(c => c.id === chId);
646
+ if(!ch) return;
647
+ _currentCh = chId;
648
+ document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
649
+ const tab = document.getElementById('vtvt-'+chId);
650
+ if(tab) tab.classList.add('on');
651
+ const video = document.getElementById('vtv-player');
652
+ const errEl = document.getElementById('vtv-err');
653
+ const loadEl = document.getElementById('vtv-load');
654
+ const errMsg = document.getElementById('vtv-err-msg');
655
+ video.style.display = 'none';
656
+ errEl.style.display = 'none';
657
+ loadEl.style.display = 'flex';
658
+ loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
659
+ if(_hls){ _hls.destroy(); _hls = null; }
660
+ const urls = STREAMS[chId] || [];
661
+ if(urls.length === 0){
662
+ loadEl.style.display = 'none';
663
+ errEl.style.display = 'flex';
664
+ if(chId === 'vtvprime'){
665
+ errMsg.textContent = 'VTVPrime: Kênh trả phí, không có luồng miễn phí.';
666
+ } else {
667
+ errMsg.textContent = ch.name + ': Không tìm thấy luồng. Thử lại sau.';
668
+ }
669
+ return;
670
+ }
671
+ // Update EPG
672
+ const epgEl = document.getElementById('vtv-epg');
673
+ if(epgEl) epgEl.remove();
674
+ const frame = document.querySelector('.vtv-frame');
675
+ if(frame){
676
+ const epgDiv = document.createElement('div');
677
+ epgDiv.innerHTML = buildEPGHTML(chId);
678
+ frame.appendChild(epgDiv.firstElementChild);
679
+ }
680
+ _tryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
681
+ };
682
+
683
+ function _tryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
684
+ if(idx >= urls.length){
685
+ loadEl.style.display = 'none';
686
+ errEl.style.display = 'flex';
687
+ errMsg.textContent = name + ': Tất cả nguồn đều lỗi. Thử lại sau.';
688
+ return;
689
+ }
690
+ const src = urls[idx];
691
+ const sourceLabel = ' (' + (idx+1) + '/' + urls.length + ')';
692
+ loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + sourceLabel + '...';
693
+ if(typeof Hls !== 'undefined' && Hls.isSupported()){
694
+ const hls = new Hls({
695
+ enableWorker: true,
696
+ lowLatencyMode: true,
697
+ startLevel: -1,
698
+ capLevelToPlayerSize: true,
699
+ maxBufferLength: 20,
700
+ xhrSetup: function(xhr, url){
701
+ if(url.includes('fptplay')){
702
+ xhr.setRequestHeader('Referer', 'https://fptplay.vn/');
703
+ xhr.setRequestHeader('Origin', 'https://fptplay.vn');
704
+ }
705
+ }
706
+ });
707
+ _hls = hls;
708
+ hls.loadSource(src);
709
+ hls.attachMedia(video);
710
+ hls.on(Hls.Events.MANIFEST_PARSED, () => {
711
+ video.play().catch(() => {});
712
+ loadEl.style.display = 'none';
713
+ video.style.display = 'block';
714
+ });
715
+ let recoverAttempts = 0;
716
+ hls.on(Hls.Events.ERROR, (ev, data) => {
717
+ if(data.fatal){
718
+ if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
719
+ recoverAttempts++;
720
+ if(recoverAttempts <= 3){
721
+ setTimeout(() => hls.startLoad(), 2000);
722
+ } else {
723
+ hls.destroy();
724
+ _hls = null;
725
+ _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
726
+ }
727
+ } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
728
+ try { hls.recoverMediaError(); } catch(e) {}
729
+ } else {
730
+ hls.destroy();
731
+ _hls = null;
732
+ _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
733
+ }
734
+ }
735
+ });
736
+ } else if(video.canPlayType('application/vnd.apple.mpegurl')){
737
+ video.src = src;
738
+ video.addEventListener('loadedmetadata', () => {
739
+ video.play().catch(() => {});
740
+ loadEl.style.display = 'none';
741
+ video.style.display = 'block';
742
+ }, {once: true});
743
+ video.addEventListener('error', () => {
744
+ _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
745
+ }, {once: true});
746
+ } else {
747
+ loadEl.style.display = 'none';
748
+ errEl.style.display = 'flex';
749
+ errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
750
+ }
751
+ }
752
+
753
+ // ===== ONLY wrap loadHome — no DOMContentLoaded listener to avoid double-load =====
754
+ const orig = window.loadHome;
755
+ if(orig && !orig.__vtvWrapped){
756
+ window.loadHome = async function(){
757
+ const r = await orig.apply(this, arguments);
758
+ try{ pinBlock(); }catch(e){}
759
+ return r;
760
+ };
761
+ window.loadHome.__vtvWrapped = true;
762
+ }
763
+ })();
764
+ </script>
765
+ <!-- hot_multi.js --><script src="/static/hot_multi.js"></script>
766
+ <!-- wc2026_v2.js --><script src="/static/wc2026_v2.js"></script>
767
+ <!-- live_mode.js --><script src="/static/live_mode.js"></script>
768
+ <!-- match_detail_v6.js --><script src="/static/match_detail_v6.js"></script>
769
+ <script>init();</script><!-- v1781058532 --></body></html>
vtv_api.py CHANGED
@@ -1,13 +1,11 @@
1
  """
2
  VTV Channels API - Backend endpoints for VTV1-VTV10 + VTVPrime
3
  Fetches stream URLs from hd.xemtv.net PHP endpoints and VTVPrime
4
- EPG schedule scraped from vtv.vn
5
  """
6
- import re, time, threading, datetime
7
  import requests
8
  from fastapi import APIRouter, Query
9
  from fastapi.responses import JSONResponse, Response
10
- from bs4 import BeautifulSoup
11
 
12
  router = APIRouter()
13
 
@@ -60,6 +58,7 @@ VTVGO_FAILOVER = {
60
  }
61
 
62
  # ===== Channels that should use xemtv.net scraping (not VTVGo failover) =====
 
63
  XEMTV_ONLY_CHANNELS = {"vtv6", "vtv10"}
64
 
65
  # ===== LAST RESORT: fptplay CDN URLs (need proxy for referer) =====
@@ -76,167 +75,6 @@ FPTPLAY_URLS = {
76
  "vtv10": "https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/vtv10-avc1_5600000=10000-mp4a_131600=20000.m3u8",
77
  }
78
 
79
- # ===== EPG: Lịch phát sóng thực tế =====
80
- EPG_SCHEDULE = {
81
- "vtv1": [
82
- {"t":"06:00","n":"Nhật ký ngày mai"},
83
- {"t":"06:30","n":"Thời sự sáng"},
84
- {"t":"07:30","n":"Thời sự"},
85
- {"t":"09:00","n":"Thời sự"},
86
- {"t":"10:00","n":"Chương trình đặc biệt"},
87
- {"t":"11:30","n":"Thời sự"},
88
- {"t":"12:00","n":"Thời sự trưa"},
89
- {"t":"14:00","n":"Thời sự chiều"},
90
- {"t":"16:00","n":"Thời sự"},
91
- {"t":"17:00","n":"Thời sự"},
92
- {"t":"18:00","n":"Thời sự tối"},
93
- {"t":"19:00","n":"Thời sự tối (chính)"},
94
- {"t":"20:00","n":"Chương trình đặc biệt"},
95
- {"t":"21:00","n":"Thời sự đêm"},
96
- {"t":"22:00","n":"Thời sự tóm tắt"},
97
- {"t":"23:00","n":"Nhật ký ngày mai"},
98
- ],
99
- "vtv2": [
100
- {"t":"06:00","n":"Khoa học & Công nghệ"},
101
- {"t":"07:00","n":"Thế giới tự nhiên"},
102
- {"t":"08:00","n":"Khoa học 360"},
103
- {"t":"09:00","n":"Đi tìm giải pháp"},
104
- {"t":"10:00","n":"Sức khỏe & Cuộc sống"},
105
- {"t":"11:00","n":"Khoa học cho mọi nhà"},
106
- {"t":"12:00","n":"Thế giới động vật"},
107
- {"t":"13:00","n":"Khoa học & Tương lai"},
108
- {"t":"14:00","n":"Tài liệu khoa học"},
109
- {"t":"15:00","n":"Khám phá thế giới"},
110
- {"t":"16:00","n":"Khoa học & Công nghệ"},
111
- {"t":"17:00","n":"Thế giới tự nhiên"},
112
- {"t":"18:00","n":"Khoa học 360"},
113
- {"t":"19:00","n":"Đi tìm giải pháp"},
114
- {"t":"20:00","n":"Khoa học & Tương lai"},
115
- {"t":"21:00","n":"Tài liệu khoa học"},
116
- {"t":"22:00","n":"Khám phá thế giới"},
117
- ],
118
- "vtv3": [
119
- {"t":"06:00","n":"Sáng vui"},
120
- {"t":"07:00","n":"Phim truyện"},
121
- {"t":"09:00","n":"Gameshow"},
122
- {"t":"11:00","n":"Âm nhạc"},
123
- {"t":"12:00","n":"Phim truyện"},
124
- {"t":"14:00","n":"Giải trí chiều"},
125
- {"t":"16:00","n":"Tạp kỹ thuật số"},
126
- {"t":"18:00","n":"Phim truyện"},
127
- {"t":"20:00","n":"Phim truyện đặc biệt"},
128
- {"t":"22:00","n":"Đêm giải trí"},
129
- ],
130
- "vtv4": [
131
- {"t":"06:00","n":"News"},
132
- {"t":"07:00","n":"World News"},
133
- {"t":"08:00","n":"Culture"},
134
- {"t":"09:00","n":"Sports"},
135
- {"t":"10:00","n":"Documentary"},
136
- {"t":"11:00","n":"Midday News"},
137
- {"t":"12:00","n":"World Today"},
138
- {"t":"14:00","n":"Culture"},
139
- {"t":"15:00","n":"Sports"},
140
- {"t":"16:00","n":"Documentary"},
141
- {"t":"17:00","n":"Evening News"},
142
- {"t":"18:00","n":"World News"},
143
- {"t":"19:00","n":"World Today"},
144
- {"t":"20:00","n":"Culture"},
145
- {"t":"21:00","n":"Nightline"},
146
- {"t":"22:00","n":"World News"},
147
- ],
148
- "vtv5": [
149
- {"t":"06:00","n":"Thời sự miền Nam"},
150
- {"t":"07:00","n":"Chương trình thiếu nhi"},
151
- {"t":"08:00","n":"Phim truyện"},
152
- {"t":"10:00","n":"Giải trí"},
153
- {"t":"12:00","n":"Thời sự trưa"},
154
- {"t":"14:00","n":"Thể thao miền Nam"},
155
- {"t":"16:00","n":"Phim truyện"},
156
- {"t":"18:00","n":"Thời sự chiều"},
157
- {"t":"20:00","n":"Phim truyện"},
158
- {"t":"22:00","n":"Thời sự tối"},
159
- ],
160
- "vtv6": [
161
- {"t":"06:00","n":"Khởi động ngày mới"},
162
- {"t":"07:00","n":"Thanh niên & Sáng tạo"},
163
- {"t":"08:00","n":"Thế giới trẻ"},
164
- {"t":"09:00","n":"Nhịp sống trẻ"},
165
- {"t":"10:00","n":"Thể thao tuổi trẻ"},
166
- {"t":"11:00","n":"Giải trí thanh niên"},
167
- {"t":"12:00","n":"Thời sự trẻ"},
168
- {"t":"14:00","n":"Đêm nhạc"},
169
- {"t":"16:00","n":"Thanh niên & Sáng tạo"},
170
- {"t":"18:00","n":"Thế giới trẻ"},
171
- {"t":"20:00","n":"Nhịp sống trẻ"},
172
- {"t":"22:00","n":"Thanh niên & Đêm"},
173
- ],
174
- "vtv7": [
175
- {"t":"06:00","n":"Giáo dục sáng"},
176
- {"t":"07:00","n":"Học mọi lúc"},
177
- {"t":"08:00","n":"Kỹ năng sống"},
178
- {"t":"09:00","n":"Giáo dục trưa"},
179
- {"t":"10:00","n":"Học trực tuyến"},
180
- {"t":"11:00","n":"Thiếu nhi"},
181
- {"t":"12:00","n":"Giáo dục chiều"},
182
- {"t":"14:00","n":"Tài liệu giáo dục"},
183
- {"t":"15:00","n":"Học suốt đời"},
184
- {"t":"16:00","n":"Kỹ năng sống"},
185
- {"t":"17:00","n":"Giáo dục sáng"},
186
- {"t":"18:00","n":"Học mọi lúc"},
187
- {"t":"19:00","n":"Giáo dục trưa"},
188
- {"t":"20:00","n":"Tài liệu giáo dục"},
189
- {"t":"21:00","n":"Học suốt đời"},
190
- ],
191
- "vtv8": [
192
- {"t":"06:00","n":"Thời sự miền Trung"},
193
- {"t":"07:00","n":"Văn hóa miền Trung"},
194
- {"t":"08:00","n":"Phim truyện"},
195
- {"t":"10:00","n":"Giải trí"},
196
- {"t":"12:00","n":"Thời sự trưa"},
197
- {"t":"14:00","n":"Thể thao miền Trung"},
198
- {"t":"16:00","n":"Phim truyện"},
199
- {"t":"18:00","n":"Thời sự chiều"},
200
- {"t":"20:00","n":"Phim truyện"},
201
- {"t":"22:00","n":"Thời sự tối"},
202
- ],
203
- "vtv9": [
204
- {"t":"06:00","n":"Thời sự miền Bắc"},
205
- {"t":"07:00","n":"Văn hóa miền Bắc"},
206
- {"t":"08:00","n":"Phim truyện"},
207
- {"t":"10:00","n":"Giải trí"},
208
- {"t":"12:00","n":"Thời sự trưa"},
209
- {"t":"14:00","n":"Thể thao miền Bắc"},
210
- {"t":"16:00","n":"Phim truyện"},
211
- {"t":"18:00","n":"Thời sự chiều"},
212
- {"t":"20:00","n":"Phim truyện"},
213
- {"t":"22:00","n":"Thời sự tối"},
214
- ],
215
- "vtv10": [
216
- {"t":"06:00","n":"Thời sự Tây Nam Bộ"},
217
- {"t":"07:00","n":"Văn hóa đồng bằng"},
218
- {"t":"08:00","n":"Phim truyện"},
219
- {"t":"10:00","n":"Giải trí"},
220
- {"t":"12:00","n":"Thời sự trưa"},
221
- {"t":"14:00","n":"Thể thao Tây Nam Bộ"},
222
- {"t":"16:00","n":"Phim truyện"},
223
- {"t":"18:00","n":"Thời sự chiều"},
224
- {"t":"20:00","n":"Phim truyện"},
225
- {"t":"22:00","n":"Thời sự tối"},
226
- ],
227
- "vtvprime": [
228
- {"t":"06:00","n":"Prime Morning"},
229
- {"t":"08:00","n":"Prime Cinema"},
230
- {"t":"10:00","n":"Prime Sports"},
231
- {"t":"12:00","n":"Prime News"},
232
- {"t":"14:00","n":"Prime Drama"},
233
- {"t":"16:00","n":"Prime Entertainment"},
234
- {"t":"18:00","n":"Prime Evening"},
235
- {"t":"20:00","n":"Prime Night"},
236
- {"t":"22:00","n":"Prime Late"},
237
- ],
238
- }
239
-
240
  _vtv_cache = {}
241
  _vtv_lock = threading.Lock()
242
  _CACHE_TTL = 180
@@ -311,7 +149,7 @@ def fetch_vtv_stream(channel_id):
311
  Fetch m3u8 stream URL for a VTV channel.
312
  Priority:
313
  1. VTV1-VTV5, VTV7-VTV9: VTVGo failover CDN (no referer needed)
314
- 2. VTV6, VTV10: xemtv.net scraping -> fptplay URL (proxied)
315
  3. VTVPrime: try xemtv, else None (paid channel)
316
  """
317
  channel_id = channel_id.lower().strip()
@@ -328,8 +166,11 @@ def fetch_vtv_stream(channel_id):
328
  if cached is not None:
329
  return cached
330
 
 
 
331
  if channel_id in XEMTV_ONLY_CHANNELS:
332
  if channel_id == "vtv10":
 
333
  fpt_url = FPTPLAY_URLS.get(channel_id)
334
  if fpt_url:
335
  _set_cache(channel_id, fpt_url)
@@ -347,11 +188,13 @@ def fetch_vtv_stream(channel_id):
347
  _set_cache(channel_id, None)
348
  return None
349
 
 
350
  if channel_id in VTVGO_FAILOVER:
351
  result = VTVGO_FAILOVER[channel_id]
352
  _set_cache(channel_id, result)
353
  return result
354
 
 
355
  if channel_id == 'vtvprime':
356
  xemtv_url = fetch_xemtv_stream('vtvprime')
357
  if xemtv_url:
@@ -360,11 +203,13 @@ def fetch_vtv_stream(channel_id):
360
  _set_cache(channel_id, None)
361
  return None
362
 
 
363
  xemtv_url = fetch_xemtv_stream(channel_id)
364
  if xemtv_url:
365
  _set_cache(channel_id, xemtv_url)
366
  return xemtv_url
367
 
 
368
  fpt_url = fetch_fptplay_stream(channel_id)
369
  if fpt_url:
370
  _set_cache(channel_id, fpt_url)
@@ -397,45 +242,6 @@ def api_vtv_stream(channel_id: str):
397
  return JSONResponse({"error": "stream not found", "status": "offline"}, status_code=404)
398
 
399
 
400
- @router.get("/api/vtv/epg/{channel_id}")
401
- def api_vtv_epg(channel_id: str):
402
- """Get EPG schedule for a specific VTV channel."""
403
- channel_id = channel_id.lower().strip()
404
- name_map = {
405
- 'vtvct': 'vtv10', 'vtv-can-tho': 'vtv10', 'vtv can tho': 'vtv10',
406
- 'vtv_can_tho': 'vtv10', 'cantho': 'vtv10',
407
- }
408
- channel_id = name_map.get(channel_id, channel_id)
409
- schedule = EPG_SCHEDULE.get(channel_id, [])
410
-
411
- now = datetime.datetime.now()
412
- current_minutes = now.hour * 60 + now.minute
413
-
414
- result = []
415
- for i, item in enumerate(schedule):
416
- parts = item['t'].split(':')
417
- is_now = False
418
- if len(parts) == 2:
419
- item_minutes = int(parts[0]) * 60 + int(parts[1])
420
- is_now = item_minutes <= current_minutes
421
- if i + 1 < len(schedule):
422
- next_parts = schedule[i + 1]['t'].split(':')
423
- if len(next_parts) == 2:
424
- next_minutes = int(next_parts[0]) * 60 + int(next_parts[1])
425
- is_now = item_minutes <= current_minutes < next_minutes
426
- else:
427
- is_now = item_minutes <= current_minutes
428
-
429
- result.append({"time": item['t'], "name": item['n'], "is_now": is_now})
430
-
431
- return JSONResponse({
432
- "channel_id": channel_id,
433
- "channel_name": CHANNEL_NAMES.get(channel_id, channel_id),
434
- "date": now.strftime("%Y-%m-%d"),
435
- "schedule": result
436
- })
437
-
438
-
439
  @router.get("/api/proxy/page")
440
  def proxy_page(url: str = Query(...)):
441
  """Proxy a web page."""
@@ -510,4 +316,4 @@ def proxy_vtv_segment(url: str = Query(...)):
510
  headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=3600"}
511
  )
512
  except:
513
- return Response(status_code=502, content="proxy error")
 
1
  """
2
  VTV Channels API - Backend endpoints for VTV1-VTV10 + VTVPrime
3
  Fetches stream URLs from hd.xemtv.net PHP endpoints and VTVPrime
 
4
  """
5
+ import re, time, threading
6
  import requests
7
  from fastapi import APIRouter, Query
8
  from fastapi.responses import JSONResponse, Response
 
9
 
10
  router = APIRouter()
11
 
 
58
  }
59
 
60
  # ===== Channels that should use xemtv.net scraping (not VTVGo failover) =====
61
+ # VTV6, VTV10: xemtv.net scraping (returns fptplay CDN URLs that need proxying)
62
  XEMTV_ONLY_CHANNELS = {"vtv6", "vtv10"}
63
 
64
  # ===== LAST RESORT: fptplay CDN URLs (need proxy for referer) =====
 
75
  "vtv10": "https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/vtv10-avc1_5600000=10000-mp4a_131600=20000.m3u8",
76
  }
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  _vtv_cache = {}
79
  _vtv_lock = threading.Lock()
80
  _CACHE_TTL = 180
 
149
  Fetch m3u8 stream URL for a VTV channel.
150
  Priority:
151
  1. VTV1-VTV5, VTV7-VTV9: VTVGo failover CDN (no referer needed)
152
+ 2. VTV6, VTV10: xemtv.net scraping (user requirement) -> fptplay URL (proxied)
153
  3. VTVPrime: try xemtv, else None (paid channel)
154
  """
155
  channel_id = channel_id.lower().strip()
 
166
  if cached is not None:
167
  return cached
168
 
169
+ # --- VTV6: xemtv.net scraping (returns working fptplay URL) ---
170
+ # --- VTV10: xemtv returns vtvcantho (403), skip to fptplay CDN directly ---
171
  if channel_id in XEMTV_ONLY_CHANNELS:
172
  if channel_id == "vtv10":
173
+ # VTV10: xemtv.net returns dead vtvcantho URL (403), use fptplay CDN directly
174
  fpt_url = FPTPLAY_URLS.get(channel_id)
175
  if fpt_url:
176
  _set_cache(channel_id, fpt_url)
 
188
  _set_cache(channel_id, None)
189
  return None
190
 
191
+ # --- VTV1-VTV5, VTV7-VTV9: VTVGo failover ---
192
  if channel_id in VTVGO_FAILOVER:
193
  result = VTVGO_FAILOVER[channel_id]
194
  _set_cache(channel_id, result)
195
  return result
196
 
197
+ # --- VTVPrime ---
198
  if channel_id == 'vtvprime':
199
  xemtv_url = fetch_xemtv_stream('vtvprime')
200
  if xemtv_url:
 
203
  _set_cache(channel_id, None)
204
  return None
205
 
206
+ # --- Fallback: xemtv scraping ---
207
  xemtv_url = fetch_xemtv_stream(channel_id)
208
  if xemtv_url:
209
  _set_cache(channel_id, xemtv_url)
210
  return xemtv_url
211
 
212
+ # --- Last resort: fptplay ---
213
  fpt_url = fetch_fptplay_stream(channel_id)
214
  if fpt_url:
215
  _set_cache(channel_id, fpt_url)
 
242
  return JSONResponse({"error": "stream not found", "status": "offline"}, status_code=404)
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  @router.get("/api/proxy/page")
246
  def proxy_page(url: str = Query(...)):
247
  """Proxy a web page."""
 
316
  headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=3600"}
317
  )
318
  except:
319
+ return Response(status_code=502, content="proxy error")