bep40 commited on
Commit
11eefb4
·
verified ·
1 Parent(s): cccc5d6

Delete static/app_v3.js, static/app_v4.js, static/app_v5.js, static/core_1781056782.js, static/rewrite_fix.js, static/tv_player.js, static/yt_live_v2.js, static/index_v3.html, static/index_v4.html, ai_runtime_patch_fast.py, main_patch.py, vtv_scraper.py, match_detail.py

Browse files
ai_runtime_patch_fast.py DELETED
@@ -1,188 +0,0 @@
1
- """Final patch v2: fix topic rewrite, remove duplicate short slide, full short interaction buttons."""
2
- import re, threading, time, json, os, asyncio
3
- import ai_runtime_final6 as f6
4
- from ai_runtime_final6 import app, rt, f5, HTMLResponse, JSONResponse, Request, Query
5
- import html as html_lib
6
- from urllib.parse import urlparse
7
-
8
- def clean(s):return re.sub(r"\s+"," ",html_lib.unescape(str(s or ""))).strip()
9
- def _domain(u):
10
- try:return urlparse(u or '').netloc.replace('www.','')
11
- except:return ''
12
- DATA_DIR="/data" if os.path.isdir('/data') else "/app/data"
13
- os.makedirs(DATA_DIR,exist_ok=True)
14
- SHORT_COMMENTS_FILE=os.path.join(DATA_DIR,'short_comments.json')
15
- TTL_24H=86400;HAS_PERSISTENT=os.path.isdir('/data')
16
- def _lj(p,d):
17
- try:
18
- if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
19
- except:pass
20
- return d
21
- def _sj(p,d):
22
- try:os.makedirs(os.path.dirname(p),exist_ok=True);open(p+'.tmp','w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False));os.replace(p+'.tmp',p)
23
- except:pass
24
- def _cleanup():
25
- n=int(time.time());ps=f5.base._load_ai_wall();f=[p for p in ps if n-int(p.get('ts') or 0)<TTL_24H]
26
- if len(f)<len(ps):f5.base._save_ai_wall(f)
27
- def _scrape(url,mc=8000):
28
- try:d=f5.base.scrape_any_url(url);return(d.get('title',''),((d.get('summary','')+'\n'+d.get('text','')).strip())[:mc],d.get('image') or d.get('og_image') or '')
29
- except:return('','','')
30
- _bg_home={"t":0,"d":[]};_bg_shorts={"t":0,"d":[]};_bg_lock=False
31
- def _bg():
32
- global _bg_lock
33
- if _bg_lock:return
34
- _bg_lock=True
35
- try:
36
- if hasattr(f6,'_fast_homepage'):d=f6._fast_homepage();(_bg_home.update({"t":time.time(),"d":d}) if d else None)
37
- raw=[];[raw.extend(f6._yt_ytdlp(h,20) or f6._yt_html(h,20)) for h in f6.YOUTUBE_HANDLES];raw.extend(f6._fallback_shorts())
38
- seen=set();out=[v for v in raw if v.get('id') and v['id'] not in seen and not seen.add(v['id'])]
39
- if out:_bg_shorts.update({"t":time.time(),"d":out[:40]})
40
- _cleanup()
41
- except:pass
42
- finally:_bg_lock=False
43
- @app.on_event("startup")
44
- async def _s():threading.Thread(target=_bg,daemon=True).start()
45
- threading.Thread(target=lambda:[time.sleep(600) or _bg() for _ in iter(int,1)],daemon=True).start()
46
- app.router.routes=[r for r in app.router.routes if not (getattr(r,'path',None) in ('/api/homepage','/api/shorts','/api/ai_wall','/api/topic_post','/api/article/ask','/api/topic/rewrite','/api/rewrite_share','/api/url_wall','/api/short/comments','/api/short/comment','/api/storage_status','/') and any(m in getattr(r,'methods',set()) for m in ('GET','POST')))]
47
- @app.get('/api/homepage')
48
- def _h():
49
- n=time.time()
50
- if _bg_home['d']:(threading.Thread(target=_bg,daemon=True).start() if n-_bg_home['t']>300 else None);return JSONResponse(_bg_home['d'])
51
- if hasattr(f6,'_fast_homepage'):d=f6._fast_homepage();_bg_home.update({"t":n,"d":d or []});return JSONResponse(d or [])
52
- return JSONResponse([])
53
- @app.get('/api/shorts')
54
- def _sh(refresh:int=Query(default=0)):
55
- n=time.time()
56
- if _bg_shorts['d'] and (not refresh or n-_bg_shorts['t']<120):(threading.Thread(target=_bg,daemon=True).start() if n-_bg_shorts['t']>600 else None);return JSONResponse(_bg_shorts['d'])
57
- return f6.api_shorts_final6(refresh=refresh) if hasattr(f6,'api_shorts_final6') else JSONResponse([])
58
- @app.get('/api/ai_wall')
59
- def _w():n=int(time.time());return JSONResponse({'posts':[p for p in f5.base._load_ai_wall() if n-int(p.get('ts') or 0)<TTL_24H],'persistent':HAS_PERSISTENT})
60
- @app.get('/api/storage_status')
61
- def _st():return JSONResponse({'persistent':HAS_PERSISTENT})
62
- @app.get('/api/short/comments')
63
- def _gc(id:str=Query(...)):return JSONResponse({'comments':_lj(SHORT_COMMENTS_FILE,{}).get(id,[])})
64
- @app.post('/api/short/comment')
65
- async def _pc(request:Request):
66
- b=await request.json();v=str(b.get('id','')).strip();t=clean(b.get('text',''))
67
- if not v or not t:return JSONResponse({'error':'missing'},status_code=400)
68
- db=_lj(SHORT_COMMENTS_FILE,{});c=db.get(v,[]);c.insert(0,{'text':t[:300],'ts':int(time.time())});db[v]=c[:100];_sj(SHORT_COMMENTS_FILE,db);return JSONResponse({'comments':db[v]})
69
- @app.post('/api/article/ask')
70
- async def _ask(request:Request):
71
- b=await request.json();q=clean(b.get('question',''));ctx=clean(b.get('context',''));url=clean(b.get('url',''))
72
- if not q:return JSONResponse({'error':'missing question'},status_code=400)
73
- title='';raw=''
74
- if url:title,raw,_=_scrape(url,10000)
75
- if not raw:raw=ctx[:12000]
76
- ans=await f5.base.qwen_generate(f'Bạn là VNEWS AI. Nội dung: "{title}"\n{raw[:9000]}\n\nHỏi: "{q}"\n\nTrả lời tự nhiên bằng tiếng Việt.',max_tokens=1200)
77
- return JSONResponse({'answer':ans or 'Chưa trả lời được.','title':title})
78
- @app.post('/api/rewrite_share')
79
- @app.post('/api/url_wall')
80
- async def _rw(request:Request):
81
- b=await request.json();url=clean(b.get('url',''));ctx=clean(b.get('context',''))
82
- if not url.startswith('http'):return JSONResponse({'error':'URL không hợp lệ'},status_code=400)
83
- title,raw,img=_scrape(url,14000)
84
- if len(raw)<50:raw=ctx[:14000]
85
- if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
86
- text=None
87
- try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Tóm tắt đăng Tường AI:\nTiêu đề: {title}\n{raw[:14000]}\n\n4-6 ý chính. Cuối ghi nguồn.',image_url=img or None,max_tokens=1000),timeout=30)
88
- except:pass
89
- if not text or len(text)<80:text=f"Tóm tắt: {title}\n\n{raw[:1200]}\n\nNguồn: {_domain(url)}"
90
- post=f5.base.make_post(title or 'Bài viết',text,img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
91
- ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
92
- @app.post('/api/topic/rewrite')
93
- async def _tr(request:Request):
94
- b=await request.json();pid=str(b.get('post_id','')).strip()
95
- if not pid:return JSONResponse({'error':'missing post_id'},status_code=400)
96
- ps=f5.base._load_ai_wall();p=next((x for x in ps if str(x.get('id'))==pid),None)
97
- if not p:return JSONResponse({'error':'Bài không tồn tại'},status_code=404)
98
- urls=list(dict.fromkeys([s['url'] for s in (p.get('source_details') or []) if s.get('url')]+[s['url'] for s in (p.get('sources') or []) if s.get('url')]))[:5]
99
- parts=[]
100
- for u in urls:t,r,_=_scrape(u,6000);(parts.append(f"[{_domain(u)}] {t}\n{r}") if r and len(r)>150 else None)
101
- ac='\n---\n'.join(parts) if parts else (p.get('text') or '')
102
- title=p.get('title','')
103
- text=None
104
- try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Viết lại:\nChủ đề: {title}\n{ac[:16000]}\n\nTiêu đề mới + 4-6 ý + nguồn.',image_url=p.get('img'),max_tokens=1200),timeout=35)
105
- except:pass
106
- if not text or len(text)<100:text=f"Tóm tắt: {title}\n\n{ac[:1500]}\n\nNguồn: VNEWS AI"
107
- np=f5.base.make_post('Rewrite: '+title,text,p.get('img',''),'','rewrite_topic',sources=p.get('sources',[]));np['images']=p.get('images',[])
108
- all_p=f5.base._load_ai_wall();all_p.insert(0,np);f5.base._save_ai_wall(all_p);return JSONResponse({'post':np})
109
- @app.post('/api/topic_post')
110
- async def _tp(request:Request):
111
- b=await request.json();topic=clean(b.get('topic',''))
112
- if not topic:return JSONResponse({'error':'missing topic'},status_code=400)
113
- img=f6._topic_image(topic);research=f6._fast_context(topic) if hasattr(f6,'_fast_context') else f6._web_research_context(topic)
114
- ctx=research.get('context','');src=research.get('sources',[]);det=f6._extract_source_details_from_context(ctx,src) if hasattr(f6,'_extract_source_details_from_context') else []
115
- if not ctx or not src:return JSONResponse({'error':'Không tìm được nội dung.'},status_code=422)
116
- sb='\n\n'.join([f"[{i+1}] {d.get('title','')} ({d.get('via','')})\n{d.get('content','')[:1400]}" for i,d in enumerate(det)]) if det else ctx[:18000]
117
- text=None
118
- try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Viết bài tiếng Việt VỀ: "{topic}"\nNGUỒN:\n{sb[:18000]}\nCHỈ viết về "{topic}". 5-8 đoạn. Cuối có nguồn.',image_url=img,max_tokens=1700),timeout=35)
119
- except:pass
120
- if not text or len(text)<300:text=f"{topic}: tổng hợp\n\n"+'\n'.join([f"• {d['title']}: {d.get('content','')[:300]}" for d in (det or [])[:6]])+"\n\nNguồn: "+', '.join(sorted({d.get('via','') for d in (det or []) if d.get('via')}))
121
- post=f5.base.make_post(topic,text,img,'','topic_focused',sources=[s for s in src if s.get('url')]);post['images']=[img];post['source_details']=det
122
- ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
123
-
124
- PATCH_INJECT=r'''
125
- <style>
126
- .short-cmt-panel{position:fixed;bottom:0;left:0;right:0;max-height:55vh;background:#181818;border-radius:16px 16px 0 0;z-index:99999;padding:14px;display:none;overflow-y:auto}.short-cmt-panel.active{display:block}.short-cmt-panel textarea{width:100%;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px;margin:6px 0;min-height:60px}.short-cmt-panel button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin:4px}.cmt-item{background:#222;border-radius:8px;padding:7px;margin:5px 0;color:#ccc;font-size:12px}
127
- .source-detail-box{margin-top:14px;background:#151515;border:1px solid #2b2b2b;border-radius:10px;padding:10px}.source-detail-item{background:#202020;border-radius:8px;padding:9px;margin:7px 0;cursor:pointer}.source-detail-title{font-size:12px;font-weight:700;color:#eee}.source-detail-content{font-size:12px;color:#bbb;line-height:1.5;white-space:pre-wrap;max-height:120px;overflow:hidden}.source-detail-item img{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:6px;margin-bottom:6px;background:#222}.source-vnews-btn{display:inline-block;margin-top:6px;background:#2d8659;color:#fff;padding:5px 10px;border-radius:12px;font-size:11px;font-weight:700}
128
- .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}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}
129
- .storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
130
- button[onclick*="rewriteCurrentArticle"]{display:none!important}
131
- /* Hide ALL old Short AI slides from previous layers */
132
- #ai-short-home,.ai-short-home,.ai-short-card-final{display:none!important}
133
- .source-detail-box a[target="_blank"]{display:none!important}
134
- </style>
135
- <div id="short-cmt-panel" class="short-cmt-panel"></div>
136
- <script>
137
- (function(){
138
- function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
139
- fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){let h=document.getElementById('view-home');if(h){let w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ <b>Persistent Storage chưa bật.</b> Bật: Space Settings → Persistent Storage → Small.';h.prepend(w);}}});
140
-
141
- // === Short AI Slide on homepage (same as Dantri shorts) ===
142
- async function renderShortAISlide(){let home=document.getElementById('view-home');if(!home)return;document.getElementById('short-ai-final-slide')?.remove();let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let vids=wall.filter(p=>p.video);if(!vids.length)return;let wrap=document.createElement('div');wrap.id='short-ai-final-slide';wrap.className='slider-wrap';wrap.innerHTML='<div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">'+vids.slice(0,30).map((p,i)=>`<div class="slider-item shorts-item" onclick="openAIShortFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata" style="width:100%;height:100%;object-fit:cover"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`).join('')+'</div>';let comp=home.querySelector('.ai-compose');if(comp&&comp.nextSibling)comp.parentNode.insertBefore(wrap,comp.nextSibling);else home.prepend(wrap);}
143
- setTimeout(renderShortAISlide,2500);
144
-
145
- // === Source Details ===
146
- function renderSourceDetails(post,container){let det=post.source_details||[];if(!det.length)return;container.querySelectorAll('.source-detail-box').forEach(e=>e.remove());let box=document.createElement('div');box.className='source-detail-box';box.innerHTML='<h3 style="font-size:14px;color:#5cb87a;margin-bottom:8px">📚 Bài nguồn</h3>'+det.map((s,i)=>`<div class="source-detail-item" data-url="${esc(s.url||'')}"><div class="source-detail-title">${i+1}. ${esc(s.title)}</div><div class="source-detail-content">${esc((s.content||'').slice(0,300))}</div><span class="source-vnews-btn">📖 Xem trên VNEWS</span></div>`).join('');container.appendChild(box);box.querySelectorAll('.source-detail-item').forEach(el=>{el.onclick=function(){let u=el.dataset.url;if(u&&typeof readArticle==='function')readArticle(u);}});det.forEach((s,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)){let items=box.querySelectorAll('.source-detail-item');if(items[i]){let img=document.createElement('img');img.src=d.og_image||d.img;img.loading='lazy';img.onerror=function(){this.style.display='none'};items[i].prepend(img);}}}).catch(()=>{});});}
147
-
148
- // === AI Wall Post View ===
149
- async function readAIWallPost(i){let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let p=wall[i];if(!p)return;showView('view-article');let h=`<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>${p.img?`<img class="article-img" src="${p.img}">`:''}`;h+=`<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>`;h+=`<div class="article-actions"><button class="primary" onclick="doRewriteTopic(this,'${esc(p.id)}')">🤖 Rewrite AI đăng tường</button>${p.video?`<button onclick="openAIShortFeed(${i})">🎬 Xem Short</button>`:''}<button onclick="doShare('${esc(p.title)}','${location.origin}','${esc(p.img||'')}')">📤</button></div>`;h+=`<div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="article-ai-q" placeholder="Hỏi về nội dung..."></textarea><button onclick="askAIWall(${i})">Hỏi</button><div id="article-ai-ans" class="article-ai-answer"></div></div></div>`;document.getElementById('view-article').innerHTML=h;let art=document.querySelector('.article-view');if(art)renderSourceDetails(p,art);window.scrollTo(0,0);}
150
- window.readAIWallPost=readAIWallPost;window.aiReadWallPatched=window.aiReadWall=window.readWallPost=function(i){readAIWallPost(i)};
151
-
152
- // === Short AI Feed: FULL interaction buttons like Dantri Shorts ===
153
- window.openAIShortFeed=async function(startIdx){let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let vids=wall.filter(p=>p.video);if(!vids.length)return alert('Chưa có Short AI');let ordered=startIdx>0?vids.slice(startIdx).concat(vids.slice(0,startIdx)):vids;showView('view-tiktok');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)=>{h+=`<div class="tiktok-slide" data-id="${p.id}"><video src="${p.video}" playsinline loop></video><div class="tiktok-bottom"><span class="badge badge-ai">AI Short</span><p class="tiktok-title">${esc(p.title)}</p></div><div class="tiktok-right"><button class="tiktok-right-btn" onclick="event.stopPropagation()"><div class="icon">👁</div><div class="count">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();likeShort('${p.id}',this)"><div class="icon">❤️</div><div class="count">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();openShortComments('${p.id}')"><div class="icon">💬</div><div class="count" id="cc-${p.id}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();shareShort('${esc(p.title)}')"><div class="icon">📤</div><div class="count">Share</div></button></div><span class="tiktok-counter">${i+1}/${ordered.length}</span></div>`});h+='</div></div>';document.getElementById('view-tiktok').innerHTML=h;initShortFeed();ordered.forEach(p=>{fetch('/api/short/comments?id='+encodeURIComponent(p.id)).then(r=>r.json()).then(j=>{let el=document.getElementById('cc-'+p.id);if(el)el.textContent=(j.comments||[]).length}).catch(()=>{});});}
154
- window.likeShort=function(id,btn){let c=btn.querySelector('.count');c.textContent=parseInt(c.textContent||0)+1;}
155
- window.shareShort=function(title){if(navigator.share)navigator.share({title,url:location.href}).catch(()=>{});else{navigator.clipboard.writeText(location.href);alert('Đã sao chép link!');}}
156
- function initShortFeed(){let feed=document.getElementById('tiktok-feed');if(!feed)return;let slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{let v=sl.querySelector('video');let fr=sl.querySelector('iframe');if(idx===i){if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;}else{if(v)v.pause();if(fr&&fr.src)fr.src='';}});cur=i}let t;feed.addEventListener('scroll',()=>{clearTimeout(t);t=setTimeout(()=>{let rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2,b=-1,d=1e9;slides.forEach((sl,i)=>{let dd=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(dd<d){d=dd;b=i}});if(b>=0)act(b)},130)});setTimeout(()=>act(0),300);slides.forEach(sl=>{let v=sl.querySelector('video');if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});}
157
-
158
- // === Handlers ===
159
- window.doRewriteTopic=async function(btn,pid){btn.disabled=true;btn.textContent='Đang rewrite...';try{let r=await fetch('/api/topic/rewrite',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({post_id:pid})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');alert('Rewrite thành công!');showRewriteResult(j.post);}catch(e){alert(e.message)}finally{btn.disabled=false;btn.textContent='🤖 Rewrite AI đăng tường';}};
160
- window.doRewriteArticle=async function(btn){let url=(window._currentArticle&&window._currentArticle.url)||'';if(!url){let a=document.querySelector('#view-article a[href*="://"]');if(a)url=a.href;}if(!url){let text=document.querySelector('.article-view')?.innerText?.slice(0,14000)||'';if(text.length<100){alert('Không tìm được nội dung để rewrite');return;}btn.disabled=true;btn.textContent='Đang rewrite...';try{let r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:'https://vnews.local/inline',context:text})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error);alert('Rewrite thành công!');showRewriteResult(j.post);}catch(e){alert(e.message)}finally{btn.disabled=false;btn.textContent='🤖 Rewrite AI đăng tường';}return;}btn.disabled=true;btn.textContent='Đang rewrite...';try{let ctx=document.querySelector('.article-view')?.innerText?.slice(0,14000)||'';let r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,context:ctx})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');alert('Rewrite thành công!');showRewriteResult(j.post);}catch(e){alert(e.message)}finally{btn.disabled=false;btn.textContent='🤖 Rewrite AI đăng tường';}};
161
- function showRewriteResult(post){if(!post)return;showView('view-article');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">Rewrite</span><h1 class="article-title">${esc(post.title)}</h1>${post.img?`<img class="article-img" src="${post.img}">`:''}` +`<p class="article-p" style="white-space:pre-wrap">${esc(post.text)}</p><div class="article-actions"><button class="primary" onclick="makeShortFromPost('${esc(post.id)}',this)">🎬 Tạo Short AI</button><button onclick="doShare('${esc(post.title)}','${location.origin}','${esc(post.img||'')}')">📤</button></div></div>`;window.scrollTo(0,0);}
162
- window.makeShortFromPost=async function(pid,btn){if(btn){btn.disabled=true;btn.textContent='Đang tạo...';}try{let r=await fetch('/api/ai/short/'+pid,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'nu',emotion:'neutral',speed:1.2})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');alert('Đã tạo Short AI!');renderShortAISlide();}catch(e){alert(e.message)}finally{if(btn){btn.disabled=false;btn.textContent='🎬 Tạo Short AI';}}};
163
- window.rewriteCurrentArticle=function(){let btn=document.querySelector('[data-rw-article]');if(btn)doRewriteArticle(btn);};
164
- window.askAIWall=async function(i){let q=document.getElementById('article-ai-q')?.value.trim();if(!q)return alert('Nhập câu hỏi');document.getElementById('article-ai-ans').textContent='Đang hỏi...';let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let p=wall[i]||{};let ctx=(p.text||'');for(let s of (p.source_details||[]))ctx+='\n'+(s.content||'');try{let r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:q,context:ctx.slice(0,12000)})});let j=await r.json();document.getElementById('article-ai-ans').textContent=j.answer||'Không trả lời được';}catch(e){document.getElementById('article-ai-ans').textContent='Lỗi: '+e.message}};
165
- window.askArticleAI=async function(){let q=document.getElementById('article-ai-question')?.value.trim();if(!q)return alert('Nhập câu hỏi');let a=document.getElementById('article-ai-answer');a.textContent='Đang hỏi...';let url=(window._currentArticle&&window._currentArticle.url)||'';let ctx=document.querySelector('.article-view')?.innerText?.slice(0,12000)||'';try{let r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,question:q,context:ctx})});let j=await r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}};
166
- window.openShortComments=async function(id){let panel=document.getElementById('short-cmt-panel');let j=await fetch('/api/short/comments?id='+encodeURIComponent(id)).then(r=>r.json()).catch(()=>({comments:[]}));panel.innerHTML=`<h3 style="color:#5cb87a">💬 Bình luận</h3><div id="cmt-list">${(j.comments||[]).map(c=>`<div class="cmt-item">${esc(c.text)}</div>`).join('')||'<div class="cmt-item" style="color:#777">Chưa có</div>'}</div><textarea id="cmt-text" placeholder="Bình luận..."></textarea><button onclick="submitShortCmt('${esc(id)}')">Gửi</button><button onclick="document.getElementById('short-cmt-panel').classList.remove('active')">Đóng</button>`;panel.classList.add('active');}
167
- window.submitShortCmt=async function(id){let t=document.getElementById('cmt-text')?.value.trim();if(!t)return;let j=await fetch('/api/short/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,text:t})}).then(r=>r.json()).catch(()=>({comments:[]}));document.getElementById('cmt-list').innerHTML=(j.comments||[]).map(c=>`<div class="cmt-item">${esc(c.text)}</div>`).join('');document.getElementById('cmt-text').value='';let el=document.getElementById('cc-'+id);if(el)el.textContent=(j.comments||[]).length;}
168
-
169
- // === Patch regular articles ===
170
- function patchArticle(){let art=document.querySelector('#view-article .article-view');if(!art)return;art.querySelectorAll('button[onclick*="rewriteCurrentArticle"],[data-rewrite],.rewrite-injected').forEach(e=>e.remove());art.querySelectorAll('.article-ai-ask').forEach((e,i)=>{if(i>0)e.remove();});if(!art.querySelector('[data-rw-article]')){let a=art.querySelector('.article-actions');if(a){let b=document.createElement('button');b.className='primary';b.setAttribute('data-rw-article','1');b.textContent='🤖 Rewrite AI đăng tường';b.onclick=function(){doRewriteArticle(b)};a.insertBefore(b,a.firstChild);}}if(!art.querySelector('.article-ai-ask')){let box=document.createElement('div');box.className='article-ai-ask';box.innerHTML='<h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="article-ai-question" placeholder="Hỏi..."></textarea><button onclick="askArticleAI()">Hỏi</button><div id="article-ai-answer" class="article-ai-answer"></div>';art.appendChild(box);}}
171
- function patchShortBtns(){document.querySelectorAll('.tiktok-slide').forEach(sl=>{if(sl.dataset.cmtDone)return;sl.dataset.cmtDone='1';let id=sl.dataset.id||'';if(!id)return;let r=sl.querySelector('.tiktok-right');if(!r||r.querySelector('[data-cmt]'))return;let b=document.createElement('button');b.className='tiktok-right-btn';b.setAttribute('data-cmt','1');b.innerHTML='<div class="icon">💬</div><div class="count">0</div>';b.onclick=function(e){e.stopPropagation();openShortComments(id);};r.appendChild(b);fetch('/api/short/comments?id='+encodeURIComponent(id)).then(r=>r.json()).then(j=>{b.querySelector('.count').textContent=(j.comments||[]).length}).catch(()=>{});});}
172
- function patchOldSourceLinks(){document.querySelectorAll('.source-detail-item a[target="_blank"],.source-detail-item a[href]').forEach(a=>{if(a.dataset.p7)return;a.dataset.p7='1';let url=a.href||'';a.removeAttribute('target');a.removeAttribute('href');a.textContent='📖 Xem trên VNEWS';a.className='source-vnews-btn';a.style.cursor='pointer';a.onclick=function(e){e.preventDefault();e.stopPropagation();if(url&&typeof readArticle==='function')readArticle(url);}});}
173
-
174
- let oldRA=window.readArticle;if(oldRA){window.readArticle=async function(){let ret=await oldRA.apply(this,arguments);setTimeout(patchArticle,500);return ret;}}
175
- let _hl=false;function dH(){if(_hl)return;_hl=true;setTimeout(()=>{if(typeof ensureHotTopics==='function')ensureHotTopics();if(typeof ensureNewsShortsHome==='function')ensureNewsShortsHome();},4000);}
176
- if(document.readyState==='complete')dH();else window.addEventListener('load',dH);
177
- setInterval(()=>{patchArticle();patchShortBtns();patchOldSourceLinks();},1500);
178
- })();
179
- </script>
180
- '''
181
-
182
- @app.get('/')
183
- async def _index():
184
- html=f5.f4.f3.f2.f1._load_index_html()
185
- body=getattr(rt.old,'PATCH_INJECT','')+f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT
186
- body+=getattr(f6,'FINAL6_INJECT','');body+=getattr(f6,'FINAL6_FAST_HOME_INJECT','');body+=getattr(f6,'FINAL6E_INJECT','')
187
- body+=PATCH_INJECT
188
- return HTMLResponse(html.replace('</body>',body+'\n</body>') if '</body>' in html else html+body)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main_patch.py DELETED
@@ -1,8 +0,0 @@
1
- # PATCH: Add these 2 lines to main.py right after "app = FastAPI()"
2
- # Line 1: from vtv_api import router as vtv_router
3
- # Line 2: app.include_router(vtv_router)
4
- #
5
- # This enables the VTV1-VTV10 + VTVPrime stream endpoints:
6
- # GET /api/vtv/streams - Get all channel streams
7
- # GET /api/vtv/stream/{id} - Get specific channel stream
8
- # GET /api/proxy/page?url=... - Proxy web pages (for xemtv PHP scraping)
 
 
 
 
 
 
 
 
 
match_detail.py DELETED
@@ -1,309 +0,0 @@
1
- """
2
- Match Detail Scraper for bongda.com.vn
3
- """
4
- import requests, re, json, time, threading
5
- from bs4 import BeautifulSoup
6
-
7
- def _sp(html):
8
- try:
9
- return BeautifulSoup(html, 'lxml')
10
- except:
11
- return BeautifulSoup(html, 'html.parser')
12
-
13
- BH = {
14
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
15
- "Accept": "application/json, text/javascript, */*; q=0.01",
16
- "Referer": "https://bongda.com.vn/",
17
- "X-Requested-With": "XMLHttpRequest",
18
- }
19
- HH = {
20
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
21
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
22
- "Referer": "https://bongda.com.vn/",
23
- }
24
-
25
- def _cl(s):
26
- return re.sub(r'\s+', ' ', str(s or '')).strip()
27
-
28
- def _api(ep, params=None):
29
- try:
30
- url = f"https://bongda.com.vn{ep}"
31
- if params:
32
- url += "?" + "&".join(f"{k}={v}" for k, v in params.items())
33
- r = requests.get(url, headers=BH, timeout=15)
34
- if r.status_code == 200:
35
- try: return r.json()
36
- except: pass
37
- except: pass
38
- return None
39
-
40
- def _get_teams(soup):
41
- info = {}
42
- tel = soup.select_one('.teams')
43
- if not tel:
44
- return info
45
- he = tel.select_one('.team.home, .home-team')
46
- if he:
47
- ne = he.select_one('p:not(.logo)') or he.find('p')
48
- if ne: info['home_team'] = _cl(ne.get_text())
49
- lo = he.select_one('img')
50
- if lo: info['home_logo'] = lo.get('src', '')
51
- le = he if he.name == 'a' else he.find('a')
52
- if le and le.get('href'):
53
- m = re.search(r'/doi-bong/(\d+)/', le['href'])
54
- if m: info['home_team_id'] = m.group(1)
55
- ae = tel.select_one('.team.away, .away-team')
56
- if ae:
57
- ne = ae.select_one('p:not(.logo)') or ae.find('p')
58
- if ne: info['away_team'] = _cl(ne.get_text())
59
- lo = ae.select_one('img')
60
- if lo: info['away_logo'] = lo.get('src', '')
61
- le = ae if ae.name == 'a' else ae.find('a')
62
- if le and le.get('href'):
63
- m = re.search(r'/doi-bong/(\d+)/', le['href'])
64
- if m: info['away_team_id'] = m.group(1)
65
- sc = tel.select_one('.score')
66
- if sc:
67
- parts = [_cl(p.get_text()) for p in sc.select('p')]
68
- if len(parts) >= 2: info['score'] = f"{parts[0]} - {parts[1]}"
69
- lb = sc.select_one('.label')
70
- if lb: info['status_label'] = _cl(lb.get_text())
71
- return info
72
-
73
- def _get_timeline(soup):
74
- tl = []
75
- el = soup.select_one('.timeline')
76
- if not el: return tl
77
- half = ''
78
- for c in el.children:
79
- if not hasattr(c, 'name') or not c.name: continue
80
- t = _cl(c.get_text())
81
- if not t: continue
82
- if t in ['H1','H2','Hiệp 1','Hiệp 2']:
83
- half = t; continue
84
- m = re.match(r"(\d+'\+?\d*)", t)
85
- if m:
86
- tl.append({'time': m.group(1), 'text': t[m.end():].strip(), 'half': half})
87
- elif len(t) > 5:
88
- tl.append({'time': '', 'text': t, 'half': half})
89
- return tl
90
-
91
- def _get_events(soup):
92
- evts = []
93
- for el in soup.select('.event'):
94
- e = {}
95
- cl = ' '.join(el.get('class', []))
96
- e['team'] = 'home' if 'home' in cl else ('away' if 'away' in cl else '')
97
- ps = [_cl(p.get_text()) for p in el.select('p')]
98
- ps = [p for p in ps if p]
99
- if ps: e['players'] = ps
100
- tl = el.select_one('.time, .minute, span')
101
- if tl: e['time'] = _cl(tl.get_text())
102
- evts.append(e)
103
- return evts
104
-
105
- def _get_stats(soup):
106
- st = {}
107
- for sel in ['.match-stats','[class*="stats"]']:
108
- el = soup.select_one(sel)
109
- if el and len(str(el)) > 50:
110
- for row in el.select('li,tr,.stat-row'):
111
- cells = row.select('td,span,p')
112
- if len(cells) >= 3:
113
- lb = _cl(cells[0].get_text())
114
- if lb: st[lb] = {'home': _cl(cells[1].get_text()), 'away': _cl(cells[2].get_text())}
115
- if st: break
116
- return st
117
-
118
- def _get_h2h(soup):
119
- h2h = {'matches': [], 'stats': {}}
120
- for sel in ['.head-to-head','[class*="h2h"]']:
121
- el = soup.select_one(sel)
122
- if el and len(str(el)) > 50:
123
- for it in el.select('li,tr,.match-item'):
124
- m = {}
125
- cells = it.select('td,span,p')
126
- if len(cells) >= 3:
127
- m['date'] = _cl(cells[0].get_text())
128
- m['home'] = _cl(cells[1].get_text())
129
- m['score'] = _cl(cells[2].get_text())
130
- if m.get('home'):
131
- if len(cells) > 3: m['away'] = _cl(cells[3].get_text())
132
- h2h['matches'].append(m)
133
- if h2h['matches']: break
134
- return h2h
135
-
136
- def _get_form(soup):
137
- f = {'home': [], 'away': []}
138
- for sel in ['.form-guide','[class*="form"]']:
139
- el = soup.select_one(sel)
140
- if el and len(str(el)) > 50:
141
- items = el.select('li,.form-item,tr')
142
- for it in items[:10]:
143
- t = _cl(it.get_text())
144
- if t: f['home'].append({'text': t})
145
- for it in items[10:20]:
146
- t = _cl(it.get_text())
147
- if t: f['away'].append({'text': t})
148
- break
149
- return f
150
-
151
- def _get_info(soup):
152
- info = {}
153
- mi = soup.select_one('.match-info')
154
- if mi:
155
- te = mi.select_one('.times,li')
156
- if te: info['datetime'] = _cl(te.get_text())
157
- le = soup.select_one('.league,.tournament,[class*="league"]')
158
- if le: info['league'] = _cl(le.get_text())
159
- return info
160
-
161
- def _scrape(url):
162
- print(f"[DEBUG] _scrape: {url[:80]}", flush=True)
163
- try:
164
- r = requests.get(url, headers=HH, timeout=15, allow_redirects=True)
165
- print(f"[DEBUG] HTTP={r.status_code}", flush=True)
166
- if r.status_code != 200:
167
- return False, {}
168
- sp = _sp(r.text)
169
- d = {}
170
-
171
- teams = _get_teams(sp)
172
- print(f"[DEBUG] teams={teams}", flush=True)
173
- if teams: d['info'] = teams
174
-
175
- mi = _get_info(sp)
176
- if mi:
177
- d.setdefault('info', {}).update(mi)
178
-
179
- tl = _get_timeline(sp)
180
- if tl:
181
- d['timeline'] = tl
182
- d['commentaries_html'] = '\n'.join([f"{t.get('time','')} {t.get('text','')}" for t in tl])
183
-
184
- ev = _get_events(sp)
185
- if ev: d['events'] = ev
186
-
187
- st = _get_stats(sp)
188
- if st:
189
- d['stats_parsed'] = st
190
- d['stats_html'] = str(st)
191
-
192
- h2h = _get_h2h(sp)
193
- if h2h.get('matches'): d['h2h_matches'] = h2h['matches']
194
- if h2h.get('stats'): d['h2h_stats'] = h2h['stats']
195
-
196
- if '/preview/' in url:
197
- fm = _get_form(sp)
198
- if fm.get('home'): d['home_form'] = fm['home']
199
- if fm.get('away'): d['away_form'] = fm['away']
200
-
201
- print(f"[DEBUG] success keys={list(d.keys())}", flush=True)
202
- return True, d
203
- except Exception as e:
204
- import traceback
205
- print(f"[DEBUG] error: {e}", flush=True)
206
- traceback.print_exc()
207
- return False, {}
208
-
209
- def fetch_match_detail_by_url(url):
210
- m = re.search(r'/tran-dau/(\d+)/', url)
211
- if not m: return {"error": "Could not extract event_id", "found": False}
212
- event_id = int(m.group(1))
213
- res = {"event_id": event_id, "found": False, "sections": []}
214
- _fetch_api(event_id, res)
215
- ok, d = _scrape(url)
216
- print(f"[DEBUG] by_url: ok={ok} d_keys={list(d.keys())}", flush=True)
217
- if ok: _merge(res, d)
218
- return res
219
-
220
- def fetch_match_detail(event_id):
221
- print(f"[DEBUG] fetch_match_detail({event_id})", flush=True)
222
- res = {"event_id": event_id, "found": False, "sections": []}
223
- _fetch_api(event_id, res)
224
-
225
- for pt in ["centre", "preview"]:
226
- url = f"https://bongda.com.vn/tran-dau/{event_id}/{pt}/"
227
- ok, d = _scrape(url)
228
- print(f"[DEBUG] {pt}: ok={ok}", flush=True)
229
- if ok:
230
- _merge(res, d)
231
- if res.get("found"): break
232
-
233
- print(f"[DEBUG] final: found={res['found']} sections={res['sections']}", flush=True)
234
- return res
235
-
236
- def _fetch_api(eid, res):
237
- pm = _api("/api/event-standing/pre-match", {"event_id": eid})
238
- res["pre_match"] = pm
239
- res["pre_match_html"] = pm.get("html","") if pm and pm.get("status")=="success" and len(pm.get("html","").strip())>10 else ""
240
-
241
- hm = _api("/api/fixtures/h2h-match", {"event_id": eid})
242
- res["h2h_match"] = hm
243
- if hm and hm.get("status")=="success":
244
- h = hm.get("html","")
245
- if len(h.strip())>10:
246
- res["h2h_html"] = h
247
- res["sections"].append("h2h")
248
- else: res["h2h_html"] = ""
249
-
250
- hs = _api("/api/fixtures/h2h-stats", {"event_id": eid})
251
- res["h2h_stats"] = hs
252
- if hs and hs.get("status")=="success":
253
- h = hs.get("html","")
254
- if len(h.strip())>10:
255
- res["h2h_stats_html"] = h
256
- res["sections"].append("h2h_stats")
257
- try:
258
- sp = _sp(h)
259
- stats = {}
260
- for row in sp.select('li,tr,.stat-row'):
261
- cells = row.select('td,span,p')
262
- if len(cells)>=3:
263
- lb = _cl(cells[0].get_text())
264
- if lb: stats[lb] = {'home': _cl(cells[1].get_text()), 'away': _cl(cells[2].get_text())}
265
- if stats: res["h2h_stats_parsed"] = stats
266
- except: pass
267
- else: res["h2h_stats_html"] = ""
268
-
269
- pf = _api("/api/event-standing/player-performance", {"event_id": eid})
270
- res["performance"] = pf
271
- if pf and pf.get("status")=="success" and len(pf.get("html","").strip())>10:
272
- res["stats_html"] = pf["html"]
273
- res["sections"].append("stats")
274
- else: res["stats_html"] = ""
275
-
276
- cm = _api("/api/fixtures/commentaries", {"event_id": eid})
277
- if cm and cm.get("status")=="success" and len(cm.get("html","").strip())>10:
278
- res["commentaries_html"] = cm["html"]
279
- res["sections"].append("commentaries")
280
- elif not res.get("commentaries_html"): res["commentaries_html"] = ""
281
-
282
- def _merge(res, d):
283
- if d.get("info"):
284
- res.setdefault("info", {}).update(d["info"])
285
- res["found"] = True
286
- if "info" not in res["sections"]: res["sections"].append("info")
287
- if d.get("timeline"):
288
- res["timeline"] = d["timeline"]
289
- if not res.get("commentaries_html"): res["commentaries_html"] = d.get("commentaries_html","")
290
- res["sections"].append("commentaries")
291
- if d.get("events"):
292
- res["events"] = d["events"]
293
- res["sections"].append("events")
294
- if d.get("stats_parsed"):
295
- res["stats_parsed"] = d["stats_parsed"]
296
- if not res.get("stats_html"): res["stats_html"] = d.get("stats_html","")
297
- res["sections"].append("stats")
298
- if d.get("h2h_matches"):
299
- res["h2h"] = d["h2h_matches"]
300
- res["sections"].append("h2h")
301
- if d.get("h2h_stats"):
302
- res["h2h_stats_parsed"] = d["h2h_stats"]
303
- res["sections"].append("h2h_stats")
304
- if d.get("home_form"):
305
- res["home_form"] = d["home_form"]
306
- res["sections"].append("home_form")
307
- if d.get("away_form"):
308
- res["away_form"] = d["away_form"]
309
- res["sections"].append("away_form")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/app_v3.js DELETED
@@ -1,319 +0,0 @@
1
- // === VNEWS Frontend v2 - Full Functions ===
2
- // Updated: Voice selector + speed control + image gallery + auto voice detect
3
-
4
- // === LOAD HOME ===
5
- async function loadHome(){
6
- const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
7
- fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
8
- fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
9
- fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
10
- fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
11
- fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
12
- fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
13
- ]);
14
- _hlLeagueData=hlLeagues;
15
- _wc2026Data=wcData;
16
- _shortsData=interleaveShorts(sh||[]);
17
- _wallPosts=(wall&&wall.posts)||[];
18
- let h='';
19
- if(featured&&featured.home){
20
- const sc=featured.status==='live'?'':'upcoming';
21
- const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
22
- // Safely encode for HTML attribute: escape quotes, angle brackets, ampersands
23
- const eid = String(featured.event_id||'').replace(/[<>&"']/g,'');
24
- const mUrl = String(featured.url||'').replace(/[<>&"']/g,'');
25
- const fHome = String(featured.home||'').replace(/[<>&"']/g,'');
26
- const fAway = String(featured.away||'').replace(/[<>&"']/g,'');
27
- const fLeague = String(featured.league||'').replace(/[<>&"']/g,'');
28
- const fScore = String(featured.score||'VS').replace(/[<>&"']/g,'');
29
- const fHomeLogo = String(featured.home_logo||'').replace(/[<>&"']/g,'');
30
- const fAwayLogo = String(featured.away_logo||'').replace(/[<>&"']/g,'');
31
- const safeTitle = `${fHome} vs ${fAway} — ${fLeague}`;
32
- h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${safeTitle}">`+
33
- `<div class="fm-league">${fLeague}</div>`+
34
- `<div class="fm-teams">`+
35
- `<div class="fm-team"><img src="${fHomeLogo}" onerror="this.style.display='none'"><span>${fHome}</span></div>`+
36
- `<div class="fm-score">${fScore}</div>`+
37
- `<div class="fm-team"><img src="${fAwayLogo}" onerror="this.style.display='none'"><span>${fAway}</span></div>`+
38
- `</div>`+
39
- `<div class="fm-status ${sc}">${st}</div>`+
40
- `</div>`;
41
- }
42
- 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>`;
43
- h+='<div id="hashtag-box"></div>';
44
- 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>`;
45
- 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>`;
46
- const wallPosts=_wallPosts;
47
- const aiShorts=wallPosts.filter(p=>p.video);
48
- 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>';}
49
- 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>';}
50
- 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>';}
51
- 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:"🤝"}};
52
- 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>';}
53
- 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>';}
54
- document.getElementById('view-home').innerHTML=h;
55
- loadLivescore('today');loadHotTopics();
56
- if(_wc2026Data)switchWCTab('news');
57
- }
58
-
59
- // === WALL POST HELPERS ===
60
- function makeWallItem(p,i){
61
- const hasVideo = p.video && p.video.length > 0;
62
- const thumbContent = p.img
63
- ? `<img src="${esc(p.img)}" onerror="this.style.display='none'">`
64
- : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
65
- const videoBadge = hasVideo
66
- ? `<div class="wall-video-badge">🎬</div>`
67
- : '';
68
- const videoBtn = hasVideo
69
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
70
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
71
-
72
- return `<div class="wall-item" id="wall-item-${esc(p.id||i)}">
73
- <div class="wall-thumb">
74
- ${thumbContent}
75
- ${videoBadge}
76
- </div>
77
- <div class="wall-title">${esc(p.title)}</div>
78
- <div class="wall-text">${esc((p.text||'').slice(0,180))}</div>
79
- <div class="wall-actions">
80
- <button class="primary" onclick="readWallPost(${i})">Xem</button>
81
- ${videoBtn}
82
- </div>
83
- </div>`;
84
- }
85
-
86
- // === GENERATE SHORT VIDEO FOR A WALL POST ===
87
- async function makeShortVideo(postId, btn, voice, speed){
88
- if(!postId)return;
89
- const origText = btn ? btn.textContent : '🎬 Tạo Video';
90
- if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
91
- toast('⏳ Đang tạo video shorts...');
92
- try{
93
- let url = '/api/ai/short/'+encodeURIComponent(postId);
94
- const params = [];
95
- if(voice) params.push('voice='+encodeURIComponent(voice));
96
- if(speed) params.push('speed='+encodeURIComponent(speed));
97
- if(params.length) url += '?' + params.join('&');
98
- const r = await fetch(url, {method:'POST'});
99
- const j = await r.json();
100
- if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video');
101
- toast('✅ Đã tạo video shorts!');
102
- const p = _wallPosts.find(x => String(x.id) === String(postId));
103
- if(p){
104
- p.video = j.video;
105
- const itemId = 'wall-item-'+postId;
106
- const el = document.getElementById(itemId);
107
- if(el){
108
- const idx = _wallPosts.indexOf(p);
109
- el.outerHTML = makeWallItem(p, idx);
110
- const newEl = document.getElementById(itemId);
111
- if(newEl) newEl.className = 'wall-item wall-item-new';
112
- }
113
- }
114
- refreshShortAISlider();
115
- }catch(e){
116
- toast('❌ '+e.message);
117
- if(btn){btn.disabled=false;btn.textContent=origText;}
118
- }
119
- }
120
-
121
- // Refresh Short AI slider after video generation
122
- function refreshShortAISlider(){
123
- const aiShorts = _wallPosts.filter(p=>p.video);
124
- let shortAISection = document.getElementById('short-ai-section');
125
- if(aiShorts.length === 0){
126
- if(shortAISection) shortAISection.remove();
127
- return;
128
- }
129
- if(shortAISection){
130
- const track = shortAISection.querySelector('.slider-track');
131
- if(track){
132
- let h = '';
133
- aiShorts.slice(0,20).forEach((p,i)=>{
134
- 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>`;
135
- });
136
- track.innerHTML = h;
137
- }
138
- }
139
- }
140
-
141
- function prependWallPost(post){
142
- _wallPosts.unshift(post);
143
- const track=document.getElementById('ai-wall-track');
144
- const wrap=document.getElementById('ai-wall-wrap');
145
- const homeEl=document.getElementById('view-home');
146
- if(!track||!wrap){
147
- if(homeEl){
148
- let insertBefore=homeEl.querySelector('.slider-wrap');
149
- const newWrap=document.createElement('div');
150
- newWrap.className='slider-wrap';
151
- newWrap.id='ai-wall-wrap';
152
- 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>`;
153
- if(insertBefore){
154
- homeEl.insertBefore(newWrap,insertBefore);
155
- }else{
156
- homeEl.appendChild(newWrap);
157
- }
158
- const firstItem=newWrap.querySelector('.wall-item');
159
- if(firstItem)firstItem.className='wall-item wall-item-new';
160
- }
161
- return;
162
- }
163
- const div=document.createElement('div');
164
- div.className='wall-item wall-item-new';
165
- div.id='wall-item-'+(post.id||'new-'+Date.now());
166
- const hasVideo = post.video && post.video.length > 0;
167
- const thumbContent = post.img
168
- ? `<img src="${esc(post.img)}" onerror="this.style.display='none'">`
169
- : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
170
- const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
171
- const videoBtn = hasVideo
172
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
173
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
174
- 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>`;
175
- track.prepend(div);
176
- track.scrollTo({left:0,behavior:'smooth'});
177
- if(hasVideo) refreshShortAISlider();
178
- }
179
-
180
- // === REST OF FUNCTIONS ===
181
- let _shortsData=[];
182
- let _wallPosts=[];
183
- let _currentView='home';
184
- let _currentEventId=null;
185
- let _currentMatchUrl=null;
186
- 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;}
187
- let _htPage=0,_htTopic='';
188
- 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);}}
189
- 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);}
190
- 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>`;}}
191
- function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
192
- 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';}}}
193
- 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>';}}
194
- function bindMatchClicks(el){
195
- if(!el) return;
196
- el.querySelectorAll('.match-detail').forEach(md=>{
197
- md.style.cursor='pointer';
198
- // Remove old listeners to avoid duplicates (mark as bound)
199
- if(md._bound) return;
200
- md._bound = true;
201
- md.addEventListener('click',function(e){
202
- // Don't intercept clicks on interactive elements inside the row
203
- const tag = e.target.tagName?.toLowerCase();
204
- if(tag === 'a' || tag === 'button' || tag === 'input') {
205
- e.preventDefault();
206
- e.stopPropagation();
207
- }
208
- // Find ANY link with /tran-dau/ inside this match-detail row
209
- const links = this.querySelectorAll('a[href*="/tran-dau/"]');
210
- let bestA = null;
211
- links.forEach(a => {
212
- const href = a.getAttribute('href') || '';
213
- // Prefer links with both event_id AND slug (fuller URL)
214
- if(href.match(/\/tran-dau\/\d+\/(centre|preview|quan-cau|video)\//)) {
215
- bestA = a;
216
- } else if(!bestA && href.match(/\/tran-dau\/\d+\//)) {
217
- bestA = a;
218
- }
219
- });
220
- if(!bestA) return;
221
- e.preventDefault();
222
- e.stopPropagation();
223
- const href = bestA.getAttribute('href') || '';
224
- const m = href.match(/\/tran-dau\/(\d+)\//);
225
- if(m){
226
- const fullUrl = href.startsWith('http') ? href : 'https://bongda.com.vn' + href;
227
- openMatch(m[1], fullUrl);
228
- }
229
- });
230
- });
231
- // Prevent default navigation on all links inside livescore (but let match-detail click handler work)
232
- el.querySelectorAll('a').forEach(a=>{
233
- a.addEventListener('click',e=>{
234
- e.preventDefault();
235
- e.stopPropagation();
236
- });
237
- });
238
- }
239
- 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')}
240
- function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
241
- 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>'}}
242
- 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;}}
243
- 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};}}
244
- 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[];}}
245
- 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[];}}
246
- 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>`;}
247
- 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);}}
248
- 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);}}
249
- 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);}
250
- 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);}}
251
- 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);}
252
- 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;}
253
- 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);}
254
- 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)}
255
- 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();}
256
- 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();}
257
- 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();}
258
- 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>`;}
259
- 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)}}
260
- 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)}}
261
- 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}}
262
- async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
263
- const images = p.images || [];
264
- let imgGallery = '';
265
- if(images.length > 0){
266
- imgGallery = '<div class="article-image-gallery">';
267
- images.forEach((imgUrl, idx) => {
268
- if(idx === 0){
269
- imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;
270
- } else {
271
- if(idx === 1) imgGallery += '<div class="gallery-thumbs">';
272
- imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;
273
- }
274
- });
275
- if(images.length > 1) imgGallery += '</div>';
276
- imgGallery += '</div>';
277
- }
278
- const hasVideo = p.video && p.video.length > 0;
279
- const voiceOptions = [
280
- {id:'hoaimy', label:'🎙️ Nữ — Hoài My'},
281
- {id:'namminh', label:'🎙️ Nam — Nam Minh'},
282
- ];
283
- let voiceSelector = '';
284
- if(!hasVideo){
285
- voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
286
- voiceOptions.forEach(v=>{
287
- 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>`;
288
- });
289
- 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>`;
290
- voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
291
- }
292
- 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>`;
293
- const firstVoiceBtn = document.querySelector('.tts-voice-btn');
294
- if(firstVoiceBtn) firstVoiceBtn.classList.add('active');
295
- window.scrollTo(0,0)}
296
- 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>'}}
297
- 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}
298
- 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(()=>{});
299
-
300
- // === AUTO-OPEN SHARE LINKS (/s?url=... sets pending_article) ===
301
- (function(){
302
- try{
303
- const pa=localStorage.getItem('pending_article');
304
- const pv=localStorage.getItem('pending_video');
305
- if(pa){
306
- localStorage.removeItem('pending_article');
307
- setTimeout(()=>{
308
- if(typeof readArticle==='function') readArticle(pa);
309
- },1500);
310
- }
311
- if(pv){
312
- localStorage.removeItem('pending_video');
313
- try{
314
- const v=JSON.parse(pv);
315
- if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500);
316
- }catch(e){}
317
- }
318
- }catch(e){}
319
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/app_v4.js DELETED
@@ -1,446 +0,0 @@
1
- // === VNEWS Frontend v4 — VTV inline + fixed livescore clicks ===
2
-
3
- // === VTV CHANNELS CONFIG ===
4
- const VTV_CHANNELS = [
5
- {id:'vtv1', name:'VTV1', badge:'Tin tức'},
6
- {id:'vtv2', name:'VTV2', badge:'Khoa học'},
7
- {id:'vtv3', name:'VTV3', badge:'Giải trí'},
8
- {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
9
- {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
10
- {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
11
- {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
12
- {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
13
- {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
14
- {id:'vtv10', name:'VTV10', badge:'VTV10'},
15
- {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
16
- ];
17
-
18
- const VTV_EPG = {
19
- vtv1:[{t:'06:00',n:'Nhật ký ngày mai'},{t:'07:00',n:'Thời sự sáng'},{t:'12:00',n:'Thời sự trưa'},{t:'19:00',n:'Thời sự tối'},{t:'21:00',n:'Thời sự đêm'}],
20
- vtv2:[{t:'06:00',n:'Khoa học & CN'},{t:'08:00',n:'Thế giới tự nhiên'},{t:'12:00',n:'Đi tìm giải pháp'},{t:'18:00',n:'Thế giới động vật'},{t:'20:00',n:'Khoa học & Tương lai'}],
21
- vtv3:[{t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'12:00',n:'Âm nhạc'},{t:'18:00',n:'Tạp kỹ thuật số'},{t:'20:00',n:'Phim truyện đặc biệt'}],
22
- vtv4:[{t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'12:00',n:'Midday News'},{t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'}],
23
- vtv5:[{t:'06:00',n:'Thời sự miền Nam'},{t:'08:00',n:'Thiếu nhi'},{t:'12:00',n:'Thời sự trưa'},{t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'}],
24
- vtv6:[{t:'06:00',n:'Khởi động'},{t:'08:00',n:'Thanh niên & Sáng tạo'},{t:'12:00',n:'Nhịp sống trẻ'},{t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'}],
25
- vtv7:[{t:'06:00',n:'Giáo dục sáng'},{t:'08:00',n:'Học mọi lúc'},{t:'12:00',n:'Giáo dục trưa'},{t:'18:00',n:'Giáo dục chiều'},{t:'20:00',n:'Tài liệu GD'}],
26
- vtv8:[{t:'06:00',n:'Thời sự miền Trung'},{t:'08:00',n:'Văn hóa'},{t:'12:00',n:'Thời sự trưa'},{t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'}],
27
- vtv9:[{t:'06:00',n:'Thời sự miền Bắc'},{t:'08:00',n:'Văn hóa'},{t:'12:00',n:'Thời sự trưa'},{t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'}],
28
- vtv10:[{t:'06:00',n:'Thời sự Tây Nam Bộ'},{t:'08:00',n:'Văn hóa đồng bằng'},{t:'12:00',n:'Thời sự trưa'},{t:'18:00',n:'Thời sự chiều'},{t:'20:00',n:'Phim truyện'}],
29
- vtvprime:[{t:'06:00',n:'Prime Morning'},{t:'08:00',n:'Prime Cinema'},{t:'12:00',n:'Prime News'},{t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'}],
30
- };
31
-
32
- let _vtvStreams = {};
33
- let _vtvCurrentCh = null;
34
- let _vtvHls = null;
35
-
36
- function buildVTVEPG(chId){
37
- const epg = VTV_EPG[chId] || [];
38
- if(!epg.length) return '';
39
- const curH = new Date().getHours();
40
- let items = '';
41
- epg.forEach(item => {
42
- const itemH = parseInt(item.t.split(':')[0], 10);
43
- const isNow = itemH <= curH && (itemH + 2) > curH;
44
- items += `<div class="vtv-epg-item${isNow?' now':''}"><div class="epg-t">${item.t}</div><div class="epg-n">${item.n}</div></div>`;
45
- });
46
- return `<div class="vtv-epg" id="vtv-epg"><div class="vtv-epg-header"><span class="vtv-epg-title">📋 Lịch phát sóng</span><button class="vtv-epg-toggle" onclick="_vtvToggleEPG()">Ẩn/Hiện</button></div><div class="vtv-epg-list" id="vtv-epg-list">${items}</div></div>`;
47
- }
48
-
49
- function _vtvToggleEPG(){
50
- const list = document.getElementById('vtv-epg-list');
51
- if(list) list.style.display = list.style.display === 'none' ? 'flex' : 'none';
52
- }
53
-
54
- function buildVTVBlockHTML(){
55
- let tabs = '';
56
- VTV_CHANNELS.forEach(ch => {
57
- tabs += `<button class="vtv-tab off" id="vtvt-${ch.id}" onclick="_vtvPlay('${ch.id}')">${ch.name}</button>`;
58
- });
59
- return `<div class="vtv-wrap" id="vtv-block">
60
- <div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>
61
- <div class="vtv-tabs">${tabs}</div>
62
- <div class="vtv-frame">
63
- <div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>
64
- <video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>
65
- <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="_vtvRetry()">Thử lại</button></div>
66
- </div>
67
- </div>`;
68
- }
69
-
70
- async function loadVTVStreams(){
71
- try {
72
- const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(10000)});
73
- if(r.ok){
74
- const data = await r.json();
75
- VTV_CHANNELS.forEach(ch => {
76
- const info = data[ch.id];
77
- if(info && info.stream_url){
78
- _vtvStreams[ch.id] = ['/api/proxy/m3u8/vtv?url=' + encodeURIComponent(info.stream_url)];
79
- } else {
80
- _vtvStreams[ch.id] = [];
81
- }
82
- });
83
- }
84
- } catch(e) {
85
- console.warn('VTV API error:', e);
86
- }
87
- VTV_CHANNELS.forEach(ch => {
88
- const tab = document.getElementById('vtvt-'+ch.id);
89
- if(tab){
90
- if(_vtvStreams[ch.id] && _vtvStreams[ch.id].length > 0){
91
- tab.classList.remove('off');
92
- tab.textContent = ch.name;
93
- } else {
94
- tab.style.opacity = '0.35';
95
- tab.textContent = ch.name + ' ✕';
96
- }
97
- }
98
- });
99
- }
100
-
101
- function _vtvRetry(){
102
- if(_vtvCurrentCh) _vtvPlay(_vtvCurrentCh);
103
- }
104
-
105
- function _vtvPlay(chId){
106
- const ch = VTV_CHANNELS.find(c => c.id === chId);
107
- if(!ch) return;
108
- _vtvCurrentCh = chId;
109
- document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
110
- const tab = document.getElementById('vtvt-'+chId);
111
- if(tab) tab.classList.add('on');
112
- const video = document.getElementById('vtv-player');
113
- const errEl = document.getElementById('vtv-err');
114
- const loadEl = document.getElementById('vtv-load');
115
- const errMsg = document.getElementById('vtv-err-msg');
116
- video.style.display = 'none';
117
- errEl.style.display = 'none';
118
- loadEl.style.display = 'flex';
119
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
120
- if(_vtvHls){ _vtvHls.destroy(); _vtvHls = null; }
121
- const urls = _vtvStreams[chId] || [];
122
- if(urls.length === 0){
123
- loadEl.style.display = 'none';
124
- errEl.style.display = 'flex';
125
- errMsg.textContent = chId === 'vtvprime' ? 'VTVPrime: Kênh trả phí.' : ch.name + ': Không tìm thấy luồng.';
126
- return;
127
- }
128
- const epgEl = document.getElementById('vtv-epg');
129
- if(epgEl) epgEl.remove();
130
- const frame = document.querySelector('.vtv-frame');
131
- if(frame){
132
- const d = document.createElement('div');
133
- d.innerHTML = buildVTVEPG(chId);
134
- frame.appendChild(d.firstElementChild);
135
- }
136
- _vtvTryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
137
- }
138
-
139
- function _vtvTryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
140
- if(idx >= urls.length){
141
- loadEl.style.display = 'none';
142
- errEl.style.display = 'flex';
143
- errMsg.textContent = name + ': Tất cả nguồn lỗi.';
144
- return;
145
- }
146
- const src = urls[idx];
147
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + ' (' + (idx+1) + '/' + urls.length + ')...';
148
- if(typeof Hls !== 'undefined' && Hls.isSupported()){
149
- const hls = new Hls({enableWorker:true, lowLatencyMode:true, startLevel:-1, capLevelToPlayerSize:true, maxBufferLength:20});
150
- _vtvHls = hls;
151
- hls.loadSource(src);
152
- hls.attachMedia(video);
153
- hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play().catch(()=>{}); loadEl.style.display='none'; video.style.display='block'; });
154
- let recAttempts = 0;
155
- hls.on(Hls.Events.ERROR, (ev, data) => {
156
- if(data.fatal){
157
- if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
158
- recAttempts++;
159
- if(recAttempts <= 3){ setTimeout(() => hls.startLoad(), 2000); }
160
- else { hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }
161
- } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
162
- try { hls.recoverMediaError(); } catch(e) {}
163
- } else { hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }
164
- }
165
- });
166
- } else if(video.canPlayType('application/vnd.apple.mpegurl')){
167
- video.src = src;
168
- video.addEventListener('loadedmetadata', () => { video.play().catch(()=>{}); loadEl.style.display='none'; video.style.display='block'; }, {once:true});
169
- video.addEventListener('error', () => { _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }, {once:true});
170
- } else {
171
- loadEl.style.display = 'none'; errEl.style.display = 'flex'; errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
172
- }
173
- }
174
-
175
- // === LOAD HOME ===
176
- async function loadHome(){
177
- const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
178
- fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
179
- fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
180
- fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
181
- fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
182
- fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
183
- fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
184
- ]);
185
- _hlLeagueData=hlLeagues;
186
- _wc2026Data=wcData;
187
- _shortsData=interleaveShorts(sh||[]);
188
- _wallPosts=(wall&&wall.posts)||[];
189
- let h='';
190
-
191
- // ===== VTV BLOCK — rendered inline, no external JS needed =====
192
- h += buildVTVBlockHTML();
193
-
194
- if(featured&&featured.home){
195
- const sc=featured.status==='live'?'':'upcoming';
196
- const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
197
- const eid = String(featured.event_id||'').replace(/[<>&"']/g,'');
198
- const mUrl = String(featured.url||'').replace(/[<>&"']/g,'');
199
- const fHome = String(featured.home||'').replace(/[<>&"']/g,'');
200
- const fAway = String(featured.away||'').replace(/[<>&"']/g,'');
201
- const fLeague = String(featured.league||'').replace(/[<>&"']/g,'');
202
- const fScore = String(featured.score||'VS').replace(/[<>&"']/g,'');
203
- const fHomeLogo = String(featured.home_logo||'').replace(/[<>&"']/g,'');
204
- const fAwayLogo = String(featured.away_logo||'').replace(/[<>&"']/g,'');
205
- h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${fHome} vs ${fAway} — ${fLeague}">`+
206
- `<div class="fm-league">${fLeague}</div>`+
207
- `<div class="fm-teams">`+
208
- `<div class="fm-team"><img src="${fHomeLogo}" onerror="this.style.display='none'"><span>${fHome}</span></div>`+
209
- `<div class="fm-score">${fScore}</div>`+
210
- `<div class="fm-team"><img src="${fAwayLogo}" onerror="this.style.display='none'"><span>${fAway}</span></div>`+
211
- `</div>`+
212
- `<div class="fm-status ${sc}">${st}</div>`+
213
- `</div>`;
214
- }
215
- 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>`;
216
- h+='<div id="hashtag-box"></div>';
217
- 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>`;
218
- 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>`;
219
- const wallPosts=_wallPosts;
220
- const aiShorts=wallPosts.filter(p=>p.video);
221
- 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>';}
222
- 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>';}
223
- 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>';}
224
- 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:"🤝"}};
225
- 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>';}
226
- 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>';}
227
- document.getElementById('view-home').innerHTML=h;
228
-
229
- // Load VTV streams after DOM is ready
230
- loadVTVStreams().then(() => {
231
- const tryOrder = ['vtv6','vtv1','vtv2','vtv3','vtv4','vtv5','vtv7','vtv8','vtv9','vtv10'];
232
- for(const chId of tryOrder){
233
- if(_vtvStreams[chId] && _vtvStreams[chId].length > 0){
234
- setTimeout(() => _vtvPlay(chId), 300);
235
- return;
236
- }
237
- }
238
- });
239
-
240
- loadLivescore('today');loadHotTopics();
241
- if(_wc2026Data)switchWCTab('news');
242
- }
243
-
244
- // === WALL POST HELPERS ===
245
- function makeWallItem(p,i){
246
- const hasVideo = p.video && p.video.length > 0;
247
- const thumbContent = p.img ? `<img src="${esc(p.img)}" onerror="this.style.display='none'">` : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
248
- const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
249
- const videoBtn = hasVideo
250
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
251
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
252
- return `<div class="wall-item" id="wall-item-${esc(p.id||i)}"><div class="wall-thumb">${thumbContent}${videoBadge}</div><div class="wall-title">${esc(p.title)}</div><div class="wall-text">${esc((p.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(${i})">Xem</button>${videoBtn}</div></div>`;
253
- }
254
-
255
- async function makeShortVideo(postId, btn, voice, speed){
256
- if(!postId)return;
257
- const origText = btn ? btn.textContent : '🎬 Tạo Video';
258
- if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
259
- toast('⏳ Đang tạo video shorts...');
260
- try{
261
- let url = '/api/ai/short/'+encodeURIComponent(postId);
262
- const params = [];
263
- if(voice) params.push('voice='+encodeURIComponent(voice));
264
- if(speed) params.push('speed='+encodeURIComponent(speed));
265
- if(params.length) url += '?' + params.join('&');
266
- const r = await fetch(url, {method:'POST'});
267
- const j = await r.json();
268
- if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video');
269
- toast('✅ Đã tạo video shorts!');
270
- const p = _wallPosts.find(x => String(x.id) === String(postId));
271
- if(p){
272
- p.video = j.video;
273
- const itemId = 'wall-item-'+postId;
274
- const el = document.getElementById(itemId);
275
- if(el){
276
- const idx = _wallPosts.indexOf(p);
277
- el.outerHTML = makeWallItem(p, idx);
278
- const newEl = document.getElementById(itemId);
279
- if(newEl) newEl.className = 'wall-item wall-item-new';
280
- }
281
- }
282
- refreshShortAISlider();
283
- }catch(e){
284
- toast('❌ '+e.message);
285
- if(btn){btn.disabled=false;btn.textContent=origText;}
286
- }
287
- }
288
-
289
- function refreshShortAISlider(){
290
- const aiShorts = _wallPosts.filter(p=>p.video);
291
- let shortAISection = document.getElementById('short-ai-section');
292
- if(aiShorts.length === 0){ if(shortAISection) shortAISection.remove(); return; }
293
- if(shortAISection){
294
- const track = shortAISection.querySelector('.slider-track');
295
- if(track){
296
- let h = '';
297
- 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="${esc(p.video)}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`; });
298
- track.innerHTML = h;
299
- }
300
- }
301
- }
302
-
303
- function prependWallPost(post){
304
- _wallPosts.unshift(post);
305
- const track=document.getElementById('ai-wall-track');
306
- const wrap=document.getElementById('ai-wall-wrap');
307
- const homeEl=document.getElementById('view-home');
308
- if(!track||!wrap){
309
- if(homeEl){
310
- let insertBefore=homeEl.querySelector('.slider-wrap');
311
- const newWrap=document.createElement('div');
312
- newWrap.className='slider-wrap'; newWrap.id='ai-wall-wrap';
313
- 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>`;
314
- if(insertBefore){ homeEl.insertBefore(newWrap,insertBefore); }else{ homeEl.appendChild(newWrap); }
315
- const firstItem=newWrap.querySelector('.wall-item');
316
- if(firstItem)firstItem.className='wall-item wall-item-new';
317
- }
318
- return;
319
- }
320
- const div=document.createElement('div');
321
- div.className='wall-item wall-item-new';
322
- div.id='wall-item-'+(post.id||'new-'+Date.now());
323
- const hasVideo = post.video && post.video.length > 0;
324
- const thumbContent = post.img ? `<img src="${esc(post.img)}" onerror="this.style.display='none'">` : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
325
- const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
326
- const videoBtn = hasVideo
327
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
328
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
329
- 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>`;
330
- track.prepend(div);
331
- track.scrollTo({left:0,behavior:'smooth'});
332
- if(hasVideo) refreshShortAISlider();
333
- }
334
-
335
- let _shortsData=[];
336
- let _wallPosts=[];
337
- let _currentView='home';
338
- let _currentEventId=null;
339
- let _currentMatchUrl=null;
340
- 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;}
341
- let _htPage=0,_htTopic='';
342
- 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);}}
343
- 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);}
344
- 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>`;}}
345
- function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
346
- 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';}}}
347
-
348
- // === LIVESCORE — FIXED: use closest() instead of e.target.tagName === 'a' ===
349
- async function loadLivescore(tab){
350
- document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));
351
- document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');
352
- const el=document.getElementById('ls-content');
353
- if(!el)return;
354
- el.innerHTML='<div class="loading">Đang tải...</div>';
355
- let ep='/api/livescore/'+tab;
356
- if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');
357
- try{
358
- const r=await fetch(ep);
359
- const d=await r.json();
360
- el.innerHTML=d.html&&d.html.length>50?d.html:'<div class="loading">Không có dữ liệu</div>';
361
- bindMatchClicks(el);
362
- }catch(e){el.innerHTML='<div class="loading">Lỗi</div>';}
363
- }
364
-
365
- function bindMatchClicks(el){
366
- if(!el) return;
367
- el.querySelectorAll('.match-detail').forEach(md=>{
368
- if(md._bound) return;
369
- md._bound = true;
370
- md.style.cursor='pointer';
371
- md.addEventListener('click',function(e){
372
- // Find the closest anchor with /tran-dau/ — works even when clicking text inside <a>
373
- const a = e.target.closest('a[href*="/tran-dau/"]');
374
- if(!a) return; // No match link found, let it be
375
- e.preventDefault();
376
- e.stopPropagation();
377
- const href = a.getAttribute('href') || '';
378
- const m = href.match(/\/tran-dau\/(\d+)\//);
379
- if(m){
380
- const fullUrl = href.startsWith('http') ? href : 'https://bongda.com.vn' + href;
381
- openMatch(m[1], fullUrl);
382
- }
383
- });
384
- });
385
- }
386
-
387
- 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')}
388
- function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
389
- 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>'}}
390
- 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;}}
391
- 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};}}
392
- 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[];}}
393
- 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[];}}
394
- 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>`;}
395
- 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);}}
396
- 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);}}
397
- 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);}
398
- 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);}}
399
- 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);}
400
- 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;}
401
- 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);}
402
- 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)}
403
- 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();}
404
- 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();}
405
- 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();}
406
- 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>`;}
407
- 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)}}
408
- 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)}}
409
- 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}}
410
- async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
411
- const images = p.images || [];
412
- let imgGallery = '';
413
- if(images.length > 0){
414
- imgGallery = '<div class="article-image-gallery">';
415
- images.forEach((imgUrl, idx) => {
416
- if(idx === 0){ imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`; }
417
- else { if(idx === 1) imgGallery += '<div class="gallery-thumbs">'; imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`; }
418
- });
419
- if(images.length > 1) imgGallery += '</div>';
420
- imgGallery += '</div>';
421
- }
422
- const hasVideo = p.video && p.video.length > 0;
423
- const voiceOptions = [{id:'hoaimy',label:'🎙️ Nữ — Hoài My'},{id:'namminh',label:'🎙️ Nam — Nam Minh'}];
424
- let voiceSelector = '';
425
- if(!hasVideo){
426
- voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
427
- voiceOptions.forEach(v=>{ 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>`; });
428
- 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>`;
429
- voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
430
- }
431
- 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>`;
432
- const firstVoiceBtn = document.querySelector('.tts-voice-btn');
433
- if(firstVoiceBtn) firstVoiceBtn.classList.add('active');
434
- window.scrollTo(0,0)}
435
- 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>'}}
436
- 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}
437
- fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!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(()=>{});
438
-
439
- (function(){
440
- try{
441
- const pa=localStorage.getItem('pending_article');
442
- const pv=localStorage.getItem('pending_video');
443
- if(pa){ localStorage.removeItem('pending_article'); setTimeout(()=>{ if(typeof readArticle==='function') readArticle(pa); },1500); }
444
- if(pv){ localStorage.removeItem('pending_video'); try{ const v=JSON.parse(pv); if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500); }catch(e){} }
445
- }catch(e){}
446
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/app_v5.js DELETED
@@ -1,391 +0,0 @@
1
- // === VNEWS Frontend v5 — VTV multi-source + fixed CSS/EPG/livescore ===
2
-
3
- // ===== VTV CHANNELS =====
4
- const VTV_CHANNELS = [
5
- {id:'vtv1', name:'VTV1', badge:'Tin tức'},
6
- {id:'vtv2', name:'VTV2', badge:'Khoa học'},
7
- {id:'vtv3', name:'VTV3', badge:'Giải trí'},
8
- {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
9
- {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
10
- {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
11
- {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
12
- {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
13
- {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
14
- {id:'vtv10', name:'VTV10', badge:'VTV10'},
15
- {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
16
- ];
17
-
18
- const VTV_EPG = {
19
- vtv1:[{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ự'},{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'},{t:'21:00',n:'Thời sự đêm'},{t:'23:00',n:'Nhật ký'}],
20
- vtv2:[{t:'06:00',n:'Khoa học & CN'},{t:'08:00',n:'Thế giới tự nhiên'},{t:'10:00',n:'Khoa học 360'},{t:'12:00',n:'Đi tìm giải pháp'},{t:'14:00',n:'Sức khỏe'},{t:'16:00',n:'Khoa học cho mọi nhà'},{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 KH'}],
21
- vtv3:[{t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'10:00',n:'Gameshow'},{t:'12:00',n:'Âm nhạc'},{t:'14:00',n:'Phim truyện'},{t:'16:00',n:'Giải trí chiều'},{t:'18:00',n:'Tạp kỹ thuật số'},{t:'20:00',n:'Phim đặc biệt'},{t:'22:00',n:'Đêm giải trí'}],
22
- vtv4:[{t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'10:00',n:'Culture'},{t:'12:00',n:'Midday News'},{t:'14:00',n:'Documentary'},{t:'16:00',n:'Sports'},{t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'},{t:'22:00',n:'Nightline'}],
23
- vtv5:[{t:'06:00',n:'Thời sự miền Nam'},{t:'08:00',n:'Thiếu nhi'},{t:'10:00',n:'Phim truyện'},{t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao MN'},{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'}],
24
- vtv6:[{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ẻ'},{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'},{t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'},{t:'22:00',n:'Thanh niên & Đêm'}],
25
- vtv7:[{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'},{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'},{t:'18:00',n:'Giáo dục chiều'},{t:'20:00',n:'Tài liệu GD'},{t:'22:00',n:'Học suốt đời'}],
26
- vtv8:[{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'},{t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao MT'},{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'}],
27
- vtv9:[{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'},{t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao MB'},{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'}],
28
- vtv10:[{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'},{t:'12:00',n:'Thời sự trưa'},{t:'14:00',n:'Giải trí'},{t:'16:00',n:'Thể thao TNB'},{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'}],
29
- vtvprime:[{t:'06:00',n:'Prime Morning'},{t:'08:00',n:'Prime Cinema'},{t:'10:00',n:'Prime Sports'},{t:'12:00',n:'Prime News'},{t:'14:00',n:'Prime Drama'},{t:'16:00',n:'Prime Entertainment'},{t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'},{t:'22:00',n:'Prime Late'}],
30
- };
31
-
32
- let _vtvStreams = {}; // chId -> [proxyUrl, proxyUrl, ...]
33
- let _vtvCurrentCh = null;
34
- let _vtvHls = null;
35
-
36
- // ===== VTV EPG =====
37
- function buildVTVEPG(chId){
38
- const epg = VTV_EPG[chId] || [];
39
- if(!epg.length) return '';
40
- const curH = new Date().getHours();
41
- let items = '';
42
- epg.forEach(item => {
43
- const itemH = parseInt(item.t.split(':')[0], 10);
44
- const isNow = itemH <= curH && (itemH + 2) > curH;
45
- items += `<div class="vtv-epg-item${isNow?' now':''}"><span class="epg-t">${item.t}</span><span class="epg-n">${item.n}</span></div>`;
46
- });
47
- return `<div class="vtv-epg" id="vtv-epg">
48
- <div class="vtv-epg-title">📋 Lịch phát sóng</div>
49
- <div class="vtv-epg-list" id="vtv-epg-list">${items}</div>
50
- </div>`;
51
- }
52
-
53
- // ===== VTV BLOCK HTML =====
54
- function buildVTVBlockHTML(){
55
- let tabs = '';
56
- VTV_CHANNELS.forEach(ch => {
57
- tabs += `<button class="vtv-tab off" id="vtvt-${ch.id}" onclick="_vtvPlay('${ch.id}')">${ch.name}</button>`;
58
- });
59
- return `<div class="vtv-wrap" id="vtv-block">
60
- <div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>
61
- <div class="vtv-tabs">${tabs}</div>
62
- <div class="vtv-player-area">
63
- <div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>
64
- <video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>
65
- <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="_vtvRetry()">Thử lại</button></div>
66
- </div>
67
- <div id="vtv-epg-wrap"></div>
68
- </div>`;
69
- }
70
-
71
- // ===== LOAD VTV STREAMS from API (multi-source) =====
72
- async function loadVTVStreams(){
73
- try {
74
- const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(10000)});
75
- if(r.ok){
76
- const data = await r.json();
77
- VTV_CHANNELS.forEach(ch => {
78
- const info = data[ch.id];
79
- const sources = (info && info.all_sources) ? info.all_sources : (info && info.stream_url ? [info.stream_url] : []);
80
- _vtvStreams[ch.id] = sources.map(u => '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(u));
81
- });
82
- }
83
- } catch(e) {
84
- console.warn('VTV API error:', e);
85
- }
86
- VTV_CHANNELS.forEach(ch => {
87
- const tab = document.getElementById('vtvt-'+ch.id);
88
- if(tab){
89
- if(_vtvStreams[ch.id] && _vtvStreams[ch.id].length > 0){
90
- tab.classList.remove('off');
91
- tab.textContent = ch.name;
92
- } else {
93
- tab.style.opacity = '0.35';
94
- tab.textContent = ch.name + ' ✕';
95
- }
96
- }
97
- });
98
- }
99
-
100
- function _vtvRetry(){
101
- if(_vtvCurrentCh) _vtvPlay(_vtvCurrentCh);
102
- }
103
-
104
- // ===== PLAY CHANNEL with multi-source failover =====
105
- function _vtvPlay(chId){
106
- const ch = VTV_CHANNELS.find(c => c.id === chId);
107
- if(!ch) return;
108
- _vtvCurrentCh = chId;
109
- document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
110
- const tab = document.getElementById('vtvt-'+chId);
111
- if(tab) tab.classList.add('on');
112
- const video = document.getElementById('vtv-player');
113
- const errEl = document.getElementById('vtv-err');
114
- const loadEl = document.getElementById('vtv-load');
115
- const errMsg = document.getElementById('vtv-err-msg');
116
- video.style.display = 'none';
117
- errEl.style.display = 'none';
118
- loadEl.style.display = 'flex';
119
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
120
- if(_vtvHls){ _vtvHls.destroy(); _vtvHls = null; }
121
- const urls = _vtvStreams[chId] || [];
122
- if(urls.length === 0){
123
- loadEl.style.display = 'none';
124
- errEl.style.display = 'flex';
125
- errMsg.textContent = chId === 'vtvprime' ? 'VTVPrime: Kênh trả phí.' : ch.name + ': Không tìm thấy luồng.';
126
- return;
127
- }
128
- // Update EPG
129
- const epgWrap = document.getElementById('vtv-epg-wrap');
130
- if(epgWrap) epgWrap.innerHTML = buildVTVEPG(chId);
131
- _vtvTryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
132
- }
133
-
134
- function _vtvTryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
135
- if(idx >= urls.length){
136
- loadEl.style.display = 'none';
137
- errEl.style.display = 'flex';
138
- errMsg.textContent = name + ': Tất cả nguồn đều lỗi. Thử lại sau.';
139
- return;
140
- }
141
- const src = urls[idx];
142
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + ' (' + (idx+1) + '/' + urls.length + ')...';
143
- if(typeof Hls !== 'undefined' && Hls.isSupported()){
144
- const hls = new Hls({
145
- enableWorker: true,
146
- lowLatencyMode: true,
147
- startLevel: -1,
148
- capLevelToPlayerSize: true,
149
- maxBufferLength: 15,
150
- maxMaxBufferLength: 30,
151
- });
152
- _vtvHls = hls;
153
- hls.loadSource(src);
154
- hls.attachMedia(video);
155
- hls.on(Hls.Events.MANIFEST_PARSED, () => {
156
- video.play().catch(()=>{});
157
- loadEl.style.display = 'none';
158
- video.style.display = 'block';
159
- });
160
- let recAttempts = 0;
161
- hls.on(Hls.Events.ERROR, (ev, data) => {
162
- if(data.fatal){
163
- if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
164
- recAttempts++;
165
- if(recAttempts <= 2){ setTimeout(() => hls.startLoad(), 1500); }
166
- else { hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }
167
- } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
168
- try { hls.recoverMediaError(); } catch(e) {}
169
- } else {
170
- hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg);
171
- }
172
- }
173
- });
174
- } else if(video.canPlayType('application/vnd.apple.mpegurl')){
175
- video.src = src;
176
- video.addEventListener('loadedmetadata', () => { video.play().catch(()=>{}); loadEl.style.display='none'; video.style.display='block'; }, {once:true});
177
- video.addEventListener('error', () => { _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }, {once:true});
178
- } else {
179
- loadEl.style.display = 'none'; errEl.style.display = 'flex'; errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
180
- }
181
- }
182
-
183
- // ===== LOAD HOME =====
184
- async function loadHome(){
185
- const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
186
- fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
187
- fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
188
- fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
189
- fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
190
- fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
191
- fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
192
- ]);
193
- _hlLeagueData=hlLeagues;
194
- _wc2026Data=wcData;
195
- _shortsData=interleaveShorts(sh||[]);
196
- _wallPosts=(wall&&wall.posts)||[];
197
- let h='';
198
-
199
- // VTV BLOCK — first thing on homepage
200
- h += buildVTVBlockHTML();
201
-
202
- if(featured&&featured.home){
203
- const sc=featured.status==='live'?'':'upcoming';
204
- const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
205
- const eid=String(featured.event_id||'').replace(/[<>&"']/g,'');
206
- const mUrl=String(featured.url||'').replace(/[<>&"']/g,'');
207
- const fH=String(featured.home||'').replace(/[<>&"']/g,'');
208
- const fA=String(featured.away||'').replace(/[<>&"']/g,'');
209
- const fL=String(featured.league||'').replace(/[<>&"']/g,'');
210
- const fS=String(featured.score||'VS').replace(/[<>&"']/g,'');
211
- const fHL=String(featured.home_logo||'').replace(/[<>&"']/g,'');
212
- const fAL=String(featured.away_logo||'').replace(/[<>&"']/g,'');
213
- h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${fH} vs ${fA} — ${fL}">`+
214
- `<div class="fm-league">${fL}</div>`+
215
- `<div class="fm-teams">`+
216
- `<div class="fm-team"><img src="${fHL}" onerror="this.style.display='none'"><span>${fH}</span></div>`+
217
- `<div class="fm-score">${fS}</div>`+
218
- `<div class="fm-team"><img src="${fAL}" onerror="this.style.display='none'"><span>${fA}</span></div>`+
219
- `</div>`+
220
- `<div class="fm-status ${sc}">${st}</div>`+
221
- `</div>`;
222
- }
223
- 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>`;
224
- h+='<div id="hashtag-box"></div>';
225
- 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>`;
226
- 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>`;
227
- const wallPosts=_wallPosts;
228
- const aiShorts=wallPosts.filter(p=>p.video);
229
- 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>';}
230
- 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>';}
231
- 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>';}
232
- 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:"🤝"}};
233
- 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>';}
234
- 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>';}
235
- document.getElementById('view-home').innerHTML=h;
236
-
237
- // Load VTV streams + auto-play
238
- loadVTVStreams().then(() => {
239
- const tryOrder = ['vtv6','vtv1','vtv2','vtv3','vtv4','vtv5','vtv7','vtv8','vtv9','vtv10'];
240
- for(const chId of tryOrder){
241
- if(_vtvStreams[chId] && _vtvStreams[chId].length > 0){
242
- setTimeout(() => _vtvPlay(chId), 300);
243
- return;
244
- }
245
- }
246
- });
247
-
248
- loadLivescore('today');loadHotTopics();
249
- if(_wc2026Data)switchWCTab('news');
250
- }
251
-
252
- // ===== WALL POST HELPERS =====
253
- function makeWallItem(p,i){
254
- const hasVideo=p.video&&p.video.length>0;
255
- const thumb=p.img?`<img src="${esc(p.img)}" onerror="this.style.display='none'">`:(hasVideo?`<video src="${esc(p.video)}" muted></video>`:'');
256
- const badge=hasVideo?`<div class="wall-video-badge">🎬</div>`:'';
257
- const btn=hasVideo?`<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`:`<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
258
- return `<div class="wall-item" id="wall-item-${esc(p.id||i)}"><div class="wall-thumb">${thumb}${badge}</div><div class="wall-title">${esc(p.title)}</div><div class="wall-text">${esc((p.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(${i})">Xem</button>${btn}</div></div>`;
259
- }
260
-
261
- async function makeShortVideo(postId,btn,voice,speed){
262
- if(!postId)return;
263
- const orig=btn?btn.textContent:'🎬 Tạo Video';
264
- if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
265
- toast('⏳ Đang tạo video shorts...');
266
- try{
267
- let url='/api/ai/short/'+encodeURIComponent(postId);
268
- const params=[];if(voice)params.push('voice='+encodeURIComponent(voice));if(speed)params.push('speed='+encodeURIComponent(speed));
269
- if(params.length)url+='?'+params.join('&');
270
- const r=await fetch(url,{method:'POST'});const j=await r.json();
271
- if(!r.ok||j.error)throw new Error(j.error||'Lỗi tạo video');
272
- toast('✅ Đã tạo video shorts!');
273
- const p=_wallPosts.find(x=>String(x.id)===String(postId));
274
- if(p){p.video=j.video;const itemId='wall-item-'+postId;const el=document.getElementById(itemId);if(el){const idx=_wallPosts.indexOf(p);el.outerHTML=makeWallItem(p,idx);const n=document.getElementById(itemId);if(n)n.className='wall-item wall-item-new';}}
275
- refreshShortAISlider();
276
- }catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent=orig;}}
277
- }
278
-
279
- function refreshShortAISlider(){
280
- const aiShorts=_wallPosts.filter(p=>p.video);
281
- let sec=document.getElementById('short-ai-section');
282
- if(aiShorts.length===0){if(sec)sec.remove();return;}
283
- if(sec){const t=sec.querySelector('.slider-track');if(t){let h='';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="${esc(p.video)}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`;});t.innerHTML=h;}}
284
- }
285
-
286
- function prependWallPost(post){
287
- _wallPosts.unshift(post);
288
- const track=document.getElementById('ai-wall-track');
289
- const wrap=document.getElementById('ai-wall-wrap');
290
- const homeEl=document.getElementById('view-home');
291
- if(!track||!wrap){
292
- if(homeEl){
293
- let ib=homeEl.querySelector('.slider-wrap');
294
- const nw=document.createElement('div');nw.className='slider-wrap';nw.id='ai-wall-wrap';
295
- nw.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>`;
296
- if(ib)homeEl.insertBefore(nw,ib);else homeEl.appendChild(nw);
297
- const fi=nw.querySelector('.wall-item');if(fi)fi.className='wall-item wall-item-new';
298
- }
299
- return;
300
- }
301
- const div=document.createElement('div');div.className='wall-item wall-item-new';div.id='wall-item-'+(post.id||'new-'+Date.now());
302
- const hasVideo=post.video&&post.video.length>0;
303
- const thumb=post.img?`<img src="${esc(post.img)}" onerror="this.style.display='none'">`:(hasVideo?`<video src="${esc(post.video)}" muted></video>`:'');
304
- const badge=hasVideo?`<div class="wall-video-badge">🎬</div>`:'';
305
- const btn=hasVideo?`<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`:`<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
306
- div.innerHTML=`<div class="wall-thumb">${thumb}${badge}</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>${btn}</div>`;
307
- track.prepend(div);track.scrollTo({left:0,behavior:'smooth'});
308
- if(hasVideo)refreshShortAISlider();
309
- }
310
-
311
- let _shortsData=[];let _wallPosts=[];let _currentView='home';let _currentEventId=null;let _currentMatchUrl=null;
312
- function interleaveShorts(shorts){const dt=shorts.filter(s=>s.channel==='baodantri7941');const sk=shorts.filter(s=>s.channel==='baosuckhoedoisongboyte');const r=[];let i=0,j=0;while(i<dt.length||j<sk.length){if(i<dt.length)r.push(dt[i++]);if(j<sk.length)r.push(sk[j++]);}return r;}
313
- let _htPage=0,_htTopic='';
314
- 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 tt=t.topic||t.label.replace(/^#/,'');return`<button class="hot-chip" onclick="searchTopic('${tt.replace(/'/g,"\\'")}')">${esc(t.label)}</button>`;}).join('');if(j.topics&&j.topics[0]){const ft=j.topics[0].topic||j.topics[0].label.replace(/^#/,'');setTimeout(()=>searchTopic(ft),800);}}
315
- 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);}
316
- 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>`;}}
317
- function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
318
- 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';}}}
319
-
320
- // ===== LIVESCORE — FIXED with closest() =====
321
- async function loadLivescore(tab){
322
- document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));
323
- document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');
324
- const el=document.getElementById('ls-content');
325
- if(!el)return;
326
- el.innerHTML='<div class="loading">Đang tải...</div>';
327
- let ep='/api/livescore/'+tab;
328
- if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');
329
- try{
330
- const r=await fetch(ep);const d=await r.json();
331
- el.innerHTML=d.html&&d.html.length>50?d.html:'<div class="loading">Không có dữ liệu</div>';
332
- bindMatchClicks(el);
333
- }catch(e){el.innerHTML='<div class="loading">Lỗi</div>';}
334
- }
335
-
336
- function bindMatchClicks(el){
337
- if(!el) return;
338
- el.querySelectorAll('.match-detail').forEach(md=>{
339
- if(md._bound) return;
340
- md._bound = true;
341
- md.style.cursor='pointer';
342
- md.addEventListener('click',function(e){
343
- const a = e.target.closest('a[href*="/tran-dau/"]');
344
- if(!a) return;
345
- e.preventDefault();e.stopPropagation();
346
- const href = a.getAttribute('href') || '';
347
- const m = href.match(/\/tran-dau\/(\d+)\//);
348
- if(m){
349
- const fullUrl = href.startsWith('http') ? href : 'https://bongda.com.vn' + href;
350
- openMatch(m[1], fullUrl);
351
- }
352
- });
353
- });
354
- }
355
-
356
- 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')}
357
- function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
358
- 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>'}}
359
- 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;}}
360
- 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};}}
361
- 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[];}}
362
- 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[];}}
363
- 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>`;}
364
- 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);}}
365
- 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);}}
366
- 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);}
367
- 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);}}
368
- 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);}
369
- 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;}
370
- 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);}
371
- 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)}
372
- 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();}
373
- 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();}
374
- 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();}
375
- 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>`;}
376
- 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)}}
377
- 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)}}
378
- 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}}
379
- async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
380
- const images=p.images||[];let imgGallery='';
381
- if(images.length>0){imgGallery='<div class="article-image-gallery">';images.forEach((imgUrl,idx)=>{if(idx===0)imgGallery+=`<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;else{if(idx===1)imgGallery+='<div class="gallery-thumbs">';imgGallery+=`<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;}});if(images.length>1)imgGallery+='</div>';imgGallery+='</div>';}
382
- const hasVideo=p.video&&p.video.length>0;
383
- const voiceOptions=[{id:'hoaimy',label:'🎙️ Nữ — Hoài My'},{id:'namminh',label:'🎙️ Nam — Nam Minh'}];
384
- let voiceSelector='';
385
- if(!hasVideo){voiceSelector=`<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;voiceOptions.forEach(v=>{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>`;});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>`;voiceSelector+=`<input type="hidden" id="selected-voice" value="hoaimy"></div>`;}
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');if(firstVoiceBtn)firstVoiceBtn.classList.add('active');window.scrollTo(0,0)}
388
- 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>'}}
389
- 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}
390
- 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(()=>{});
391
- (function(){try{const pa=localStorage.getItem('pending_article');const pv=localStorage.getItem('pending_video');if(pa){localStorage.removeItem('pending_article');setTimeout(()=>{if(typeof readArticle==='function')readArticle(pa);},1500);}if(pv){localStorage.removeItem('pending_video');try{const v=JSON.parse(pv);if(v&&v.url)setTimeout(()=>{window.open(v.url,'_blank')},1500);}catch(e){}}}catch(e){}})();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/core_1781056782.js DELETED
@@ -1,319 +0,0 @@
1
- // === VNEWS Frontend v2 - Full Functions ===
2
- // Updated: Voice selector + speed control + image gallery + auto voice detect
3
-
4
- // === LOAD HOME ===
5
- async function loadHome(){
6
- const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
7
- fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
8
- fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
9
- fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
10
- fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
11
- fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
12
- fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
13
- ]);
14
- _hlLeagueData=hlLeagues;
15
- _wc2026Data=wcData;
16
- _shortsData=interleaveShorts(sh||[]);
17
- _wallPosts=(wall&&wall.posts)||[];
18
- let h='';
19
- if(featured&&featured.home){
20
- const sc=featured.status==='live'?'':'upcoming';
21
- const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
22
- // Safely encode for HTML attribute: escape quotes, angle brackets, ampersands
23
- const eid = String(featured.event_id||'').replace(/[<>&"']/g,'');
24
- const mUrl = String(featured.url||'').replace(/[<>&"']/g,'');
25
- const fHome = String(featured.home||'').replace(/[<>&"']/g,'');
26
- const fAway = String(featured.away||'').replace(/[<>&"']/g,'');
27
- const fLeague = String(featured.league||'').replace(/[<>&"']/g,'');
28
- const fScore = String(featured.score||'VS').replace(/[<>&"']/g,'');
29
- const fHomeLogo = String(featured.home_logo||'').replace(/[<>&"']/g,'');
30
- const fAwayLogo = String(featured.away_logo||'').replace(/[<>&"']/g,'');
31
- const safeTitle = `${fHome} vs ${fAway} — ${fLeague}`;
32
- h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${safeTitle}">`+
33
- `<div class="fm-league">${fLeague}</div>`+
34
- `<div class="fm-teams">`+
35
- `<div class="fm-team"><img src="${fHomeLogo}" onerror="this.style.display='none'"><span>${fHome}</span></div>`+
36
- `<div class="fm-score">${fScore}</div>`+
37
- `<div class="fm-team"><img src="${fAwayLogo}" onerror="this.style.display='none'"><span>${fAway}</span></div>`+
38
- `</div>`+
39
- `<div class="fm-status ${sc}">${st}</div>`+
40
- `</div>`;
41
- }
42
- 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>`;
43
- h+='<div id="hashtag-box"></div>';
44
- 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>`;
45
- 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>`;
46
- const wallPosts=_wallPosts;
47
- const aiShorts=wallPosts.filter(p=>p.video);
48
- 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>';}
49
- 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>';}
50
- 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>';}
51
- 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:"🤝"}};
52
- 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>';}
53
- 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>';}
54
- document.getElementById('view-home').innerHTML=h;
55
- loadLivescore('today');loadHotTopics();
56
- if(_wc2026Data)switchWCTab('news');
57
- }
58
-
59
- // === WALL POST HELPERS ===
60
- function makeWallItem(p,i){
61
- const hasVideo = p.video && p.video.length > 0;
62
- const thumbContent = p.img
63
- ? `<img src="${esc(p.img)}" onerror="this.style.display='none'">`
64
- : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
65
- const videoBadge = hasVideo
66
- ? `<div class="wall-video-badge">🎬</div>`
67
- : '';
68
- const videoBtn = hasVideo
69
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
70
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
71
-
72
- return `<div class="wall-item" id="wall-item-${esc(p.id||i)}">
73
- <div class="wall-thumb">
74
- ${thumbContent}
75
- ${videoBadge}
76
- </div>
77
- <div class="wall-title">${esc(p.title)}</div>
78
- <div class="wall-text">${esc((p.text||'').slice(0,180))}</div>
79
- <div class="wall-actions">
80
- <button class="primary" onclick="readWallPost(${i})">Xem</button>
81
- ${videoBtn}
82
- </div>
83
- </div>`;
84
- }
85
-
86
- // === GENERATE SHORT VIDEO FOR A WALL POST ===
87
- async function makeShortVideo(postId, btn, voice, speed){
88
- if(!postId)return;
89
- const origText = btn ? btn.textContent : '🎬 Tạo Video';
90
- if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
91
- toast('⏳ Đang tạo video shorts...');
92
- try{
93
- let url = '/api/ai/short/'+encodeURIComponent(postId);
94
- const params = [];
95
- if(voice) params.push('voice='+encodeURIComponent(voice));
96
- if(speed) params.push('speed='+encodeURIComponent(speed));
97
- if(params.length) url += '?' + params.join('&');
98
- const r = await fetch(url, {method:'POST'});
99
- const j = await r.json();
100
- if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video');
101
- toast('✅ Đã tạo video shorts!');
102
- const p = _wallPosts.find(x => String(x.id) === String(postId));
103
- if(p){
104
- p.video = j.video;
105
- const itemId = 'wall-item-'+postId;
106
- const el = document.getElementById(itemId);
107
- if(el){
108
- const idx = _wallPosts.indexOf(p);
109
- el.outerHTML = makeWallItem(p, idx);
110
- const newEl = document.getElementById(itemId);
111
- if(newEl) newEl.className = 'wall-item wall-item-new';
112
- }
113
- }
114
- refreshShortAISlider();
115
- }catch(e){
116
- toast('❌ '+e.message);
117
- if(btn){btn.disabled=false;btn.textContent=origText;}
118
- }
119
- }
120
-
121
- // Refresh Short AI slider after video generation
122
- function refreshShortAISlider(){
123
- const aiShorts = _wallPosts.filter(p=>p.video);
124
- let shortAISection = document.getElementById('short-ai-section');
125
- if(aiShorts.length === 0){
126
- if(shortAISection) shortAISection.remove();
127
- return;
128
- }
129
- if(shortAISection){
130
- const track = shortAISection.querySelector('.slider-track');
131
- if(track){
132
- let h = '';
133
- aiShorts.slice(0,20).forEach((p,i)=>{
134
- 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>`;
135
- });
136
- track.innerHTML = h;
137
- }
138
- }
139
- }
140
-
141
- function prependWallPost(post){
142
- _wallPosts.unshift(post);
143
- const track=document.getElementById('ai-wall-track');
144
- const wrap=document.getElementById('ai-wall-wrap');
145
- const homeEl=document.getElementById('view-home');
146
- if(!track||!wrap){
147
- if(homeEl){
148
- let insertBefore=homeEl.querySelector('.slider-wrap');
149
- const newWrap=document.createElement('div');
150
- newWrap.className='slider-wrap';
151
- newWrap.id='ai-wall-wrap';
152
- 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>`;
153
- if(insertBefore){
154
- homeEl.insertBefore(newWrap,insertBefore);
155
- }else{
156
- homeEl.appendChild(newWrap);
157
- }
158
- const firstItem=newWrap.querySelector('.wall-item');
159
- if(firstItem)firstItem.className='wall-item wall-item-new';
160
- }
161
- return;
162
- }
163
- const div=document.createElement('div');
164
- div.className='wall-item wall-item-new';
165
- div.id='wall-item-'+(post.id||'new-'+Date.now());
166
- const hasVideo = post.video && post.video.length > 0;
167
- const thumbContent = post.img
168
- ? `<img src="${esc(post.img)}" onerror="this.style.display='none'">`
169
- : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
170
- const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
171
- const videoBtn = hasVideo
172
- ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
173
- : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
174
- 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>`;
175
- track.prepend(div);
176
- track.scrollTo({left:0,behavior:'smooth'});
177
- if(hasVideo) refreshShortAISlider();
178
- }
179
-
180
- // === REST OF FUNCTIONS ===
181
- let _shortsData=[];
182
- let _wallPosts=[];
183
- let _currentView='home';
184
- let _currentEventId=null;
185
- let _currentMatchUrl=null;
186
- 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;}
187
- let _htPage=0,_htTopic='';
188
- 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);}}
189
- 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);}
190
- 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>`;}}
191
- function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
192
- 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';}}}
193
- 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>';}}
194
- function bindMatchClicks(el){
195
- if(!el) return;
196
- el.querySelectorAll('.match-detail').forEach(md=>{
197
- md.style.cursor='pointer';
198
- // Remove old listeners to avoid duplicates (mark as bound)
199
- if(md._bound) return;
200
- md._bound = true;
201
- md.addEventListener('click',function(e){
202
- // Don't intercept clicks on interactive elements inside the row
203
- const tag = e.target.tagName?.toLowerCase();
204
- if(tag === 'a' || tag === 'button' || tag === 'input') {
205
- e.preventDefault();
206
- e.stopPropagation();
207
- }
208
- // Find ANY link with /tran-dau/ inside this match-detail row
209
- const links = this.querySelectorAll('a[href*="/tran-dau/"]');
210
- let bestA = null;
211
- links.forEach(a => {
212
- const href = a.getAttribute('href') || '';
213
- // Prefer links with both event_id AND slug (fuller URL)
214
- if(href.match(/\/tran-dau\/\d+\/(centre|preview|quan-cau|video)\//)) {
215
- bestA = a;
216
- } else if(!bestA && href.match(/\/tran-dau\/\d+\//)) {
217
- bestA = a;
218
- }
219
- });
220
- if(!bestA) return;
221
- e.preventDefault();
222
- e.stopPropagation();
223
- const href = bestA.getAttribute('href') || '';
224
- const m = href.match(/\/tran-dau\/(\d+)\//);
225
- if(m){
226
- const fullUrl = href.startsWith('http') ? href : 'https://bongda.com.vn' + href;
227
- openMatch(m[1], fullUrl);
228
- }
229
- });
230
- });
231
- // Prevent default navigation on all links inside livescore (but let match-detail click handler work)
232
- el.querySelectorAll('a').forEach(a=>{
233
- a.addEventListener('click',e=>{
234
- e.preventDefault();
235
- e.stopPropagation();
236
- });
237
- });
238
- }
239
- 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')}
240
- function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
241
- 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>'}}
242
- 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;}}
243
- 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};}}
244
- 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[];}}
245
- 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[];}}
246
- 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>`;}
247
- 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);}}
248
- 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);}}
249
- 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);}
250
- 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);}}
251
- 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);}
252
- 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;}
253
- 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);}
254
- 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)}
255
- 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();}
256
- 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();}
257
- 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();}
258
- 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>`;}
259
- 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)}}
260
- 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)}}
261
- 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}}
262
- async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
263
- const images = p.images || [];
264
- let imgGallery = '';
265
- if(images.length > 0){
266
- imgGallery = '<div class="article-image-gallery">';
267
- images.forEach((imgUrl, idx) => {
268
- if(idx === 0){
269
- imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;
270
- } else {
271
- if(idx === 1) imgGallery += '<div class="gallery-thumbs">';
272
- imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;
273
- }
274
- });
275
- if(images.length > 1) imgGallery += '</div>';
276
- imgGallery += '</div>';
277
- }
278
- const hasVideo = p.video && p.video.length > 0;
279
- const voiceOptions = [
280
- {id:'hoaimy', label:'🎙️ Nữ — Hoài My'},
281
- {id:'namminh', label:'🎙️ Nam — Nam Minh'},
282
- ];
283
- let voiceSelector = '';
284
- if(!hasVideo){
285
- voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
286
- voiceOptions.forEach(v=>{
287
- 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>`;
288
- });
289
- 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>`;
290
- voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
291
- }
292
- 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>`;
293
- const firstVoiceBtn = document.querySelector('.tts-voice-btn');
294
- if(firstVoiceBtn) firstVoiceBtn.classList.add('active');
295
- window.scrollTo(0,0)}
296
- 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>'}}
297
- 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}
298
- 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(()=>{});
299
-
300
- // === AUTO-OPEN SHARE LINKS (/s?url=... sets pending_article) ===
301
- (function(){
302
- try{
303
- const pa=localStorage.getItem('pending_article');
304
- const pv=localStorage.getItem('pending_video');
305
- if(pa){
306
- localStorage.removeItem('pending_article');
307
- setTimeout(()=>{
308
- if(typeof readArticle==='function') readArticle(pa);
309
- },1500);
310
- }
311
- if(pv){
312
- localStorage.removeItem('pending_video');
313
- try{
314
- const v=JSON.parse(pv);
315
- if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500);
316
- }catch(e){}
317
- }
318
- }catch(e){}
319
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/index_v3.html DELETED
@@ -1,74 +0,0 @@
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, TV trực tuyến, 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>*{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}.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}.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}.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}.view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}.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}.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}.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)}}.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}.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}.section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}.back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}.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}.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}.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}.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}.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}.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}.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}.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)}.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)}}.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}#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}.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
14
- /* ===== VTV PLAYER ===== */
15
- .vtv-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:10px;overflow:hidden}
16
- .vtv-head{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:linear-gradient(90deg,#1a2a1f,#0d1117);border-bottom:1px solid #2d8659}
17
- .vtv-title{color:#5cb87a;font-size:13px;font-weight:800}
18
- .vtv-badge{font-size:9px;color:#e74c3c;font-weight:700;animation:vtv-pulse 1.5s infinite}
19
- @keyframes vtv-pulse{0%,100%{opacity:1}50%{opacity:.4}}
20
- .vtv-tabs{display:flex;gap:3px;padding:6px 8px;overflow-x:auto;scrollbar-width:none;background:#111;border-bottom:1px solid #222}
21
- .vtv-tabs::-webkit-scrollbar{display:none}
22
- .vtv-tab{padding:5px 10px;background:#222;border:1px solid #333;border-radius:12px;color:#999;font-size:10px;white-space:nowrap;cursor:pointer;flex-shrink:0;transition:all .2s}
23
- .vtv-tab.on{background:#2d8659;border-color:#2d8659;color:#fff;font-weight:700;box-shadow:0 0 8px rgba(45,134,89,.4)}
24
- .vtv-tab.off{opacity:.4;cursor:not-allowed}
25
- .vtv-tab:not(.off):hover{background:#2a3a2a;border-color:#5cb87a}
26
- .vtv-player-area{position:relative;width:100%;aspect-ratio:16/9;background:#000}
27
- .vtv-player-area video{width:100%;height:100%;object-fit:contain}
28
- .vtv-load{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#000;color:#888;font-size:12px;gap:8px}
29
- .vtv-spinner{width:28px;height:28px;border:3px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:vtv-spin .8s linear infinite}
30
- @keyframes vtv-spin{to{transform:rotate(360deg)}}
31
- .vtv-err{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#000;color:#e74c3c;font-size:12px;gap:8px;text-align:center;padding:16px}
32
- .vtv-err button{background:#2d8659;border:0;color:#fff;padding:6px 16px;border-radius:12px;font-size:11px;cursor:pointer}
33
- .vtv-epg{padding:8px 10px;background:#111;border-top:1px solid #222}
34
- .vtv-epg-title{font-size:11px;font-weight:700;color:#5cb87a;margin-bottom:6px}
35
- .vtv-epg-list{display:flex;flex-direction:column;gap:2px}
36
- .vtv-epg-item{display:flex;gap:8px;padding:4px 6px;border-radius:4px;font-size:10px}
37
- .vtv-epg-item.now{background:#1a2a1f;border-left:2px solid #5cb87a}
38
- .vtv-epg-item .epg-t{color:#f0c040;min-width:40px;font-weight:700}
39
- .vtv-epg-item .epg-n{color:#ccc}
40
- </style>
41
- </head>
42
- <body>
43
- <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · TV Trực Tuyến · Video · AI · World Cup 2026</p></div>
44
- <div class="cats" id="cat-bar"></div>
45
- <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
46
- <div id="view-cat" class="view"></div>
47
- <div id="view-video" class="view"></div>
48
- <div id="view-tiktok" class="view"></div>
49
- <div id="view-article" class="view"></div>
50
- <div class="match-overlay" id="match-overlay">
51
- <div class="mo-header"><h3 id="mo-title">Chi tiết trận đấu</h3><button class="mo-close" onclick="closeMatch()">✕</button></div>
52
- <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>
53
- <div class="mo-body" id="mo-body"><div class="loading">Đang tải...</div></div>
54
- </div>
55
- <div id="progress-toast"></div>
56
- <script>
57
- var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
58
- function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
59
- function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
60
- 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)}}
61
- function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
62
- 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(()=>{})}
63
- async function init(){_cats=await fetch('/api/categories').then(r=>r.json()).catch(()=>[]);let bar='<div class="cat active" data-cat="home">🏠</div><div class="cat" data-cat="news-all">📰 Tin tức</div>';_cats.forEach(c=>{bar+=`<div class="cat" data-cat="${c.id}">${c.name}</div>`});document.getElementById('cat-bar').innerHTML=bar;document.querySelectorAll('.cat').forEach(t=>{t.onclick=()=>switchCat(t.dataset.cat)});await loadHome()}
64
- var SPACE=location.origin;
65
- </script>
66
- <script src="/static/app_v2.js"></script>
67
- <script src="/static/yt_live_v2.js"></script>
68
- <script src="/static/hot_multi.js"></script>
69
- <script src="/static/wc2026_v2.js"></script>
70
- <script src="/static/live_mode.js"></script>
71
- <script src="/static/match_detail_v6.js"></script>
72
- <script>init();</script>
73
- </body>
74
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/index_v4.html DELETED
@@ -1,77 +0,0 @@
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>*{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}.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}.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}.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}.view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}.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}.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}.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)}}.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}.badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700;display:inline-block;margin-bottom:2px;color:#fff}.badge-vne{background:#c0392b}.badge-bbc{background:#b80000}.badge-dt{background:#1565c0}.badge-genk{background:#6a1b9a}.badge-fpt{background:#f26522}.badge-ai{background:#2d8659}.badge-wc{background:#0b6bcb}.section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}.back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}.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}.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}.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}.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}.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}.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}.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}.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)}.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)}}.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}#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}.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
14
- /* ===== VTV PLAYER FIXED CSS ===== */
15
- .vtv-wrap{margin:6px 4px;background:#0a0a0a;border:1px solid #1a3a5a;border-radius:10px;overflow:hidden}
16
- .vtv-head{display:flex;align-items:center;gap:8px;padding:8px 12px;background:linear-gradient(90deg,#001a33,#0d1a2a);border-bottom:1px solid #1a3a5a}
17
- .vtv-title{font-size:14px;font-weight:800;color:#00ccff;letter-spacing:.5px}
18
- .vtv-badge{font-size:10px;font-weight:800;color:#ff4444;animation:vtvp 1.2s infinite}
19
- @keyframes vtvp{0%,100%{opacity:1}50%{opacity:.3}}
20
- .vtv-tabs{display:flex;gap:4px;padding:6px 10px;overflow-x:auto;scrollbar-width:none;background:#0d1520}
21
- .vtv-tabs::-webkit-scrollbar{display:none}
22
- .vtv-tab{padding:5px 10px;background:#112233;border:1px solid #1a3a4a;border-radius:8px;color:#6a9fca;font-size:9px;font-weight:700;cursor:pointer;white-space:nowrap;flex-shrink:0;transition:all .15s}
23
- .vtv-tab:hover{background:#1a3a5a;color:#fff}
24
- .vtv-tab.on{background:#0066cc;border-color:#00aaff;color:#fff;font-weight:800;box-shadow:0 0 8px rgba(0,102,204,.4)}
25
- .vtv-tab.off{opacity:.3;pointer-events:none}
26
- .vtv-player-area{position:relative;width:100%;aspect-ratio:16/9;background:#000;min-height:200px}
27
- .vtv-player-area video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000}
28
- .vtv-load{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#00ccff;font-size:12px;flex-direction:column;gap:10px;background:#000}
29
- .vtv-err{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#ff6666;font-size:12px;text-align:center;padding:20px;flex-direction:column;gap:10px;background:#000}
30
- .vtv-err button{background:#0066cc;border:none;color:#fff;padding:8px 18px;border-radius:8px;font-size:11px;cursor:pointer;font-weight:700}
31
- .vtv-err button:hover{background:#0088ff}
32
- .vtv-spinner{width:28px;height:28px;border:3px solid #222;border-top-color:#00ccff;border-radius:50%;animation:vtvspin .7s linear infinite}
33
- @keyframes vtvspin{to{transform:rotate(360deg)}}
34
- .vtv-epg{padding:8px 12px;background:#080e18;border-top:1px solid #1a2a3a}
35
- .vtv-epg-title{font-size:10px;font-weight:700;color:#00ccff;margin-bottom:6px}
36
- .vtv-epg-list{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding-bottom:4px}
37
- .vtv-epg-list::-webkit-scrollbar{display:none}
38
- .vtv-epg-item{flex:0 0 auto;padding:4px 8px;background:#112233;border-radius:6px;font-size:9px;color:#8ab4d8;white-space:nowrap;border:1px solid #1a2a3a}
39
- .vtv-epg-item.now{background:#0066cc;color:#fff;font-weight:700;border-color:#00aaff}
40
- .vtv-epg-item .epg-t{font-size:8px;color:#5a7a9a;display:block}
41
- .vtv-epg-item.now .epg-t{color:#aaddff}
42
- .vtv-epg-item .epg-n{color:#ccc;font-size:9px;display:block;margin-top:1px}
43
- .vtv-epg-item.now .epg-n{color:#fff}
44
- </style>
45
- </head>
46
- <body>
47
- <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · Video · AI · World Cup 2026</p></div>
48
- <div class="cats" id="cat-bar"></div>
49
- <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
50
- <div id="view-cat" class="view"></div>
51
- <div id="view-video" class="view"></div>
52
- <div id="view-tiktok" class="view"></div>
53
- <div id="view-article" class="view"></div>
54
- <div class="match-overlay" id="match-overlay">
55
- <div class="mo-header"><h3 id="mo-title">Chi tiết trận đấu</h3><button class="mo-close" onclick="closeMatch()">✕</button></div>
56
- <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>
57
- <div class="mo-body" id="mo-body"><div class="loading">Đang tải...</div></div>
58
- </div>
59
- <div id="progress-toast"></div>
60
- <script>
61
- var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
62
- function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
63
- function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
64
- 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)}}
65
- function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
66
- 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(()=>{})}
67
- async function init(){_cats=await fetch('/api/categories').then(r=>r.json()).catch(()=>[]);let bar='<div class="cat active" data-cat="home">🏠</div><div class="cat" data-cat="news-all">📰 Tin tức</div>';_cats.forEach(c=>{bar+=`<div class="cat" data-cat="${c.id}">${c.name}</div>`});document.getElementById('cat-bar').innerHTML=bar;document.querySelectorAll('.cat').forEach(t=>{t.onclick=()=>switchCat(t.dataset.cat)});await loadHome()}
68
- var SPACE=location.origin;
69
- </script>
70
- <script src="/static/app_v5.js?v=1781061783"></script>
71
- <script src="/static/hot_multi.js?v=1781059323"></script>
72
- <script src="/static/wc2026_v2.js?v=1781059323"></script>
73
- <script src="/static/live_mode.js?v=1781059323"></script>
74
- <script src="/static/match_detail_v6.js?v=1781059323"></script>
75
- <script>init();</script>
76
- </body>
77
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/rewrite_fix.js DELETED
@@ -1,90 +0,0 @@
1
- // Fix rewriteArticle - call correct endpoint
2
- // This file patches the rewriteArticle function to use /api/rewrite_slide instead of /api/rewrite_share
3
-
4
- (function(){
5
- // Override rewriteArticle to call /api/rewrite_slide
6
- const origRewrite = window.rewriteArticle;
7
- window.rewriteArticle = async function(){
8
- const url = _currentArticle?.url;
9
- if(!url) return;
10
- toast('⏳ Đang tạo slide tóm tắt...');
11
- try {
12
- const r = await fetch('/api/rewrite_slide', {
13
- method: 'POST',
14
- headers: {'Content-Type': 'application/json'},
15
- body: JSON.stringify({url, context: document.querySelector('.article-view')?.innerText?.slice(0,14000) || ''})
16
- });
17
- const j = await r.json();
18
- if (!r.ok || j.error) throw new Error(j.error);
19
- toast('✅ Đã đăng Tường AI!');
20
- if (j.post) prependWallPost(j.post);
21
- // Navigate to the new post on Tường AI (home). Slide overlay (if any) stays on top.
22
- if (j.post && typeof goToWallPost === 'function') goToWallPost(j.post.id);
23
- // Show slides preview
24
- if (j.slides && j.slides.length) {
25
- showSlidePreview(j.slides, j.post?.title || '');
26
- }
27
- } catch(e) {
28
- // Fallback: try /api/rewrite_share (old endpoint from ai_ext)
29
- try {
30
- const r2 = await fetch('/api/rewrite_share', {
31
- method: 'POST',
32
- headers: {'Content-Type': 'application/json'},
33
- body: JSON.stringify({url, context: document.querySelector('.article-view')?.innerText?.slice(0,14000) || ''})
34
- });
35
- const j2 = await r2.json();
36
- if (r2.ok && !j2.error) {
37
- toast('✅ Đã đăng Tường AI!');
38
- if (j2.post) prependWallPost(j2.post);
39
- if (j2.post && typeof goToWallPost === 'function') goToWallPost(j2.post.id);
40
- return;
41
- }
42
- } catch(e2) {}
43
- toast('❌ ' + e.message);
44
- }
45
- };
46
-
47
- // Show slides as fullscreen overlay
48
- window.showSlidePreview = function(slides, title) {
49
- if (!slides || !slides.length) return;
50
- const overlay = document.createElement('div');
51
- overlay.id = 'slide-preview';
52
- overlay.style.cssText = 'position:fixed;inset:0;background:#000;z-index:99999;display:flex;flex-direction:column;overflow:hidden';
53
-
54
- let currentSlide = 0;
55
- function renderSlide(idx) {
56
- const s = slides[idx];
57
- overlay.innerHTML = `
58
- <div style="position:absolute;top:10px;left:10px;right:10px;display:flex;justify-content:space-between;align-items:center;z-index:2">
59
- <button onclick="document.getElementById('slide-preview').remove()" style="background:rgba(0,0,0,.6);border:0;color:#fff;padding:8px 14px;border-radius:20px;font-size:12px;cursor:pointer">✕ Đóng</button>
60
- <span style="color:#fff;font-size:11px;background:rgba(0,0,0,.6);padding:4px 10px;border-radius:10px">${idx+1}/${slides.length}</span>
61
- </div>
62
- <div style="flex:1;display:flex;align-items:center;justify-content:center;padding:20px">
63
- ${s.image ? `<img src="${esc(s.image)}" style="max-width:100%;max-height:60vh;border-radius:10px;object-fit:contain" onerror="this.style.display='none'">` : ''}
64
- </div>
65
- <div style="padding:16px 20px;background:linear-gradient(transparent,rgba(0,0,0,.9));min-height:100px">
66
- <p style="color:#fff;font-size:14px;line-height:1.6">${esc(s.text)}</p>
67
- </div>
68
- <div style="display:flex;gap:10px;padding:10px 20px 20px;justify-content:center">
69
- <button onclick="prevSlide()" style="background:#333;border:0;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;cursor:pointer" ${idx===0?'disabled style="opacity:.3"':''}>← Trước</button>
70
- <button onclick="nextSlide()" style="background:#2d8659;border:0;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;cursor:pointer" ${idx===slides.length-1?'disabled style="opacity:.3"':''}>Tiếp →</button>
71
- </div>
72
- `;
73
- }
74
-
75
- window.nextSlide = function() { if (currentSlide < slides.length - 1) { currentSlide++; renderSlide(currentSlide); } };
76
- window.prevSlide = function() { if (currentSlide > 0) { currentSlide--; renderSlide(currentSlide); } };
77
-
78
- renderSlide(0);
79
- document.body.appendChild(overlay);
80
-
81
- // Swipe support
82
- let startX = 0;
83
- overlay.addEventListener('touchstart', e => { startX = e.touches[0].clientX; });
84
- overlay.addEventListener('touchend', e => {
85
- const diff = e.changedTouches[0].clientX - startX;
86
- if (diff < -50) nextSlide();
87
- else if (diff > 50) prevSlide();
88
- });
89
- };
90
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/tv_player.js DELETED
@@ -1,348 +0,0 @@
1
- // === VNEWS — VTV1-VTV10 + VTVPrime LIVE CHANNELS + EPG ===
2
- // Uses backend /api/vtv/streams for stream URLs
3
- // Default channel: VTV6 | No double-load | EPG schedule
4
-
5
- (function(){
6
- if(window._ytLiveLoaded) return;
7
- window._ytLiveLoaded = true;
8
-
9
- const CHANNELS = [
10
- {id:'vtv1', name:'VTV1', badge:'Tin tức'},
11
- {id:'vtv2', name:'VTV2', badge:'Khoa học'},
12
- {id:'vtv3', name:'VTV3', badge:'Giải trí'},
13
- {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
14
- {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
15
- {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
16
- {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
17
- {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
18
- {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
19
- {id:'vtv10', name:'VTV10', badge:'VTV10'},
20
- {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
21
- ];
22
-
23
- // ===== EPG — Lịch phát sóng mẫu cho từng kênh =====
24
- const EPG = {
25
- vtv1: [
26
- {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ự'},
27
- {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'},
28
- {t:'21:00',n:'Thời sự đêm'},{t:'23:00',n:'Nhật ký ngày mai'},
29
- ],
30
- vtv2: [
31
- {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'},
32
- {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à'},
33
- {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'},
34
- ],
35
- vtv3: [
36
- {t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'10:00',n:'Gameshow'},
37
- {t:'12:00',n:'Âm nhạc'},{t:'14:00',n:'Phim truyện'},{t:'16:00',n:'Giải trí chiều'},
38
- {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í'},
39
- ],
40
- vtv4: [
41
- {t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'10:00',n:'Culture'},
42
- {t:'12:00',n:'Midday News'},{t:'14:00',n:'Documentary'},{t:'16:00',n:'Sports'},
43
- {t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'},{t:'22:00',n:'Nightline'},
44
- ],
45
- vtv5: [
46
- {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'},
47
- {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'},
48
- {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'},
49
- ],
50
- vtv6: [
51
- {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ẻ'},
52
- {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'},
53
- {t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'},{t:'22:00',n:'Thanh niên & Đêm'},
54
- ],
55
- vtv7: [
56
- {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'},
57
- {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'},
58
- {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'},
59
- ],
60
- vtv8: [
61
- {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'},
62
- {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'},
63
- {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'},
64
- ],
65
- vtv9: [
66
- {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'},
67
- {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'},
68
- {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'},
69
- ],
70
- vtv10: [
71
- {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'},
72
- {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ộ'},
73
- {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'},
74
- ],
75
- vtvprime: [
76
- {t:'06:00',n:'Prime Morning'},{t:'08:00',n:'Prime Cinema'},{t:'10:00',n:'Prime Sports'},
77
- {t:'12:00',n:'Prime News'},{t:'14:00',n:'Prime Drama'},{t:'16:00',n:'Prime Entertainment'},
78
- {t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'},{t:'22:00',n:'Prime Late'},
79
- ],
80
- };
81
-
82
- // ALL external streams need proxy — VTVGo/fptplay CDNs don't send CORS headers
83
- const STREAMS = {};
84
- let _currentCh = null;
85
- let _hls = null;
86
- let _loading = false;
87
- let _epgVisible = false;
88
-
89
- const s = document.createElement('style');
90
- s.textContent = `
91
- .vtv-wrap{margin:6px 4px;background:#111;border:1px solid #0066cc;border-radius:10px;overflow:hidden}
92
- .vtv-head{display:flex;align-items:center;gap:8px;padding:8px 10px;background:linear-gradient(90deg,#003366,#1a1a1a)}
93
- .vtv-title{font-size:13px;font-weight:800;color:#00ccff}
94
- .vtv-badge{font-size:10px;font-weight:800;color:#00ccff;animation:vtvp 1.3s infinite}
95
- @keyframes vtvp{0%,100%{opacity:1}50%{opacity:.3}}
96
- .vtv-tabs{display:flex;gap:3px;padding:6px 8px;overflow-x:auto;scrollbar-width:none;background:#0d1a2a}
97
- .vtv-tabs::-webkit-scrollbar{display:none}
98
- .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}
99
- .vtv-tab:hover{background:#0b4a7a;color:#fff}
100
- .vtv-tab.on{background:#0066cc;border-color:#00ccff;color:#fff;font-weight:700}
101
- .vtv-tab.off{opacity:.35;pointer-events:none}
102
- .vtv-frame{position:relative;width:100%;aspect-ratio:16/9;background:#000;min-height:180px}
103
- .vtv-frame video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
104
- .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}
105
- .vtv-err button{background:#0066cc;border:none;color:#fff;padding:6px 14px;border-radius:8px;font-size:11px;cursor:pointer}
106
- .vtv-load{display:flex;align-items:center;justify-content:center;height:180px;color:#00ccff;font-size:12px;flex-direction:column;gap:8px}
107
- .vtv-spinner{width:24px;height:24px;border:2px solid #333;border-top-color:#00ccff;border-radius:50%;animation:vtvspin .8s linear infinite}
108
- @keyframes vtvspin{to{transform:rotate(360deg)}}
109
- .vtv-epg{margin:0;padding:6px 10px;background:#0a1628;border-top:1px solid #1a2a3a}
110
- .vtv-epg-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:4px}
111
- .vtv-epg-title{font-size:10px;font-weight:700;color:#00ccff}
112
- .vtv-epg-toggle{background:none;border:1px solid #2a3a4a;color:#8ab4d8;font-size:9px;padding:2px 8px;border-radius:6px;cursor:pointer}
113
- .vtv-epg-list{display:flex;gap:4px;overflow-x:auto;scrollbar-width:none;padding-bottom:4px}
114
- .vtv-epg-list::-webkit-scrollbar{display:none}
115
- .vtv-epg-item{flex:0 0 auto;padding:3px 6px;background:#1a2a3a;border-radius:4px;font-size:8px;color:#8ab4d8;white-space:nowrap}
116
- .vtv-epg-item.now{background:#0066cc;color:#fff;font-weight:700}
117
- .vtv-epg-item .epg-t{font-size:7px;color:#6a8aaa}
118
- .vtv-epg-item.now .epg-t{color:#aaccee}
119
- .vtv-epg-item .epg-n{color:#ccc;font-size:8px}
120
- .vtv-epg-item.now .epg-n{color:#fff}
121
- `;
122
- document.head.appendChild(s);
123
-
124
- function getCurrentHour(){
125
- return new Date().getHours();
126
- }
127
-
128
- function buildEPGHTML(chId){
129
- const epg = EPG[chId] || [];
130
- if(!epg.length) return '';
131
- const curH = getCurrentHour();
132
- let items = '';
133
- epg.forEach(item => {
134
- const itemH = parseInt(item.t.split(':')[0], 10);
135
- const isNow = itemH <= curH && (itemH + 2) > curH;
136
- items += `<div class="vtv-epg-item${isNow?' now':''}"><div class="epg-t">${item.t}</div><div class="epg-n">${item.n}</div></div>`;
137
- });
138
- return `<div class="vtv-epg" id="vtv-epg">' +
139
- '<div class="vtv-epg-header"><span class="vtv-epg-title">📋 Lịch phát sóng</span>' +
140
- '<button class="vtv-epg-toggle" onclick="window._vtvToggleEPG()">Ẩn/Hiện</button></div>' +
141
- '<div class="vtv-epg-list" id="vtv-epg-list">' + items + '</div></div>';
142
- }
143
-
144
- window._vtvToggleEPG = function(){
145
- const list = document.getElementById('vtv-epg-list');
146
- if(list) list.style.display = list.style.display === 'none' ? 'flex' : 'none';
147
- };
148
-
149
- async function loadAllStreams(){
150
- if(_loading) return;
151
- _loading = true;
152
- const loadEl = document.getElementById('vtv-load');
153
- if(loadEl) loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang tải danh sách kênh...';
154
-
155
- try {
156
- const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(10000)});
157
- if(r.ok){
158
- const data = await r.json();
159
- CHANNELS.forEach(ch => {
160
- const info = data[ch.id];
161
- if(info && info.stream_url){
162
- // Always proxy through backend to avoid CORS issues
163
- const url = '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(info.stream_url);
164
- STREAMS[ch.id] = [url];
165
- } else {
166
- STREAMS[ch.id] = [];
167
- }
168
- });
169
- }
170
- } catch(e) {
171
- console.warn('VTV API error:', e);
172
- }
173
-
174
- CHANNELS.forEach(ch => {
175
- const tab = document.getElementById('vtvt-'+ch.id);
176
- if(tab){
177
- if(STREAMS[ch.id] && STREAMS[ch.id].length > 0){
178
- tab.classList.remove('off');
179
- tab.textContent = ch.name;
180
- } else {
181
- tab.style.opacity = '0.35';
182
- tab.textContent = ch.name + ' ✕';
183
- }
184
- }
185
- });
186
- _loading = false;
187
- }
188
-
189
- function buildBlock(){
190
- const w = document.createElement('div');
191
- w.className = 'vtv-wrap';
192
- w.id = 'vtv-block';
193
- let tabs = '';
194
- CHANNELS.forEach(ch => {
195
- tabs += '<button class="vtv-tab off" id="vtvt-'+ch.id+'" onclick="window._vtvPlay(\''+ch.id+'\')">'+ch.name+'</button>';
196
- });
197
- w.innerHTML =
198
- '<div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>' +
199
- '<div class="vtv-tabs">' + tabs + '</div>' +
200
- '<div class="vtv-frame">' +
201
- '<div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>' +
202
- '<video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>' +
203
- '<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>' +
204
- '</div>';
205
- return w;
206
- }
207
-
208
- // ===== PIN BLOCK — called only once via loadHome wrapper =====
209
- function pinBlock(){
210
- const h = document.getElementById('view-home');
211
- if(!h || document.getElementById('vtv-block')) return;
212
- h.insertBefore(buildBlock(), h.firstChild);
213
- loadAllStreams().then(() => {
214
- // Default to VTV6 if available, otherwise first available channel
215
- const tryOrder = ['vtv6','vtv1','vtv2','vtv3','vtv4','vtv5','vtv7','vtv8','vtv9','vtv10'];
216
- for(const chId of tryOrder){
217
- if(STREAMS[chId] && STREAMS[chId].length > 0){
218
- setTimeout(() => window._vtvPlay(chId), 300);
219
- return;
220
- }
221
- }
222
- });
223
- }
224
-
225
- window._vtvRetry = function(){
226
- if(_currentCh) window._vtvPlay(_currentCh);
227
- };
228
-
229
- window._vtvPlay = function(chId){
230
- const ch = CHANNELS.find(c => c.id === chId);
231
- if(!ch) return;
232
- _currentCh = chId;
233
- document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
234
- const tab = document.getElementById('vtvt-'+chId);
235
- if(tab) tab.classList.add('on');
236
- const video = document.getElementById('vtv-player');
237
- const errEl = document.getElementById('vtv-err');
238
- const loadEl = document.getElementById('vtv-load');
239
- const errMsg = document.getElementById('vtv-err-msg');
240
- video.style.display = 'none';
241
- errEl.style.display = 'none';
242
- loadEl.style.display = 'flex';
243
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
244
- if(_hls){ _hls.destroy(); _hls = null; }
245
- const urls = STREAMS[chId] || [];
246
- if(urls.length === 0){
247
- loadEl.style.display = 'none';
248
- errEl.style.display = 'flex';
249
- if(chId === 'vtvprime'){
250
- errMsg.textContent = 'VTVPrime: Kênh trả phí, không có luồng miễn phí.';
251
- } else {
252
- errMsg.textContent = ch.name + ': Không tìm thấy luồng. Thử lại sau.';
253
- }
254
- return;
255
- }
256
- // Update EPG
257
- const epgEl = document.getElementById('vtv-epg');
258
- if(epgEl) epgEl.remove();
259
- const frame = document.querySelector('.vtv-frame');
260
- if(frame){
261
- const epgDiv = document.createElement('div');
262
- epgDiv.innerHTML = buildEPGHTML(chId);
263
- frame.appendChild(epgDiv.firstElementChild);
264
- }
265
- _tryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
266
- };
267
-
268
- function _tryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
269
- if(idx >= urls.length){
270
- loadEl.style.display = 'none';
271
- errEl.style.display = 'flex';
272
- errMsg.textContent = name + ': Tất cả nguồn đều lỗi. Thử lại sau.';
273
- return;
274
- }
275
- const src = urls[idx];
276
- const sourceLabel = ' (' + (idx+1) + '/' + urls.length + ')';
277
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + sourceLabel + '...';
278
- if(typeof Hls !== 'undefined' && Hls.isSupported()){
279
- const hls = new Hls({
280
- enableWorker: true,
281
- lowLatencyMode: true,
282
- startLevel: -1,
283
- capLevelToPlayerSize: true,
284
- maxBufferLength: 20,
285
- xhrSetup: function(xhr, url){
286
- if(url.includes('fptplay')){
287
- xhr.setRequestHeader('Referer', 'https://fptplay.vn/');
288
- xhr.setRequestHeader('Origin', 'https://fptplay.vn');
289
- }
290
- }
291
- });
292
- _hls = hls;
293
- hls.loadSource(src);
294
- hls.attachMedia(video);
295
- hls.on(Hls.Events.MANIFEST_PARSED, () => {
296
- video.play().catch(() => {});
297
- loadEl.style.display = 'none';
298
- video.style.display = 'block';
299
- });
300
- let recoverAttempts = 0;
301
- hls.on(Hls.Events.ERROR, (ev, data) => {
302
- if(data.fatal){
303
- if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
304
- recoverAttempts++;
305
- if(recoverAttempts <= 3){
306
- setTimeout(() => hls.startLoad(), 2000);
307
- } else {
308
- hls.destroy();
309
- _hls = null;
310
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
311
- }
312
- } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
313
- try { hls.recoverMediaError(); } catch(e) {}
314
- } else {
315
- hls.destroy();
316
- _hls = null;
317
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
318
- }
319
- }
320
- });
321
- } else if(video.canPlayType('application/vnd.apple.mpegurl')){
322
- video.src = src;
323
- video.addEventListener('loadedmetadata', () => {
324
- video.play().catch(() => {});
325
- loadEl.style.display = 'none';
326
- video.style.display = 'block';
327
- }, {once: true});
328
- video.addEventListener('error', () => {
329
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
330
- }, {once: true});
331
- } else {
332
- loadEl.style.display = 'none';
333
- errEl.style.display = 'flex';
334
- errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
335
- }
336
- }
337
-
338
- // ===== ONLY wrap loadHome — no DOMContentLoaded listener to avoid double-load =====
339
- const orig = window.loadHome;
340
- if(orig && !orig.__vtvWrapped){
341
- window.loadHome = async function(){
342
- const r = await orig.apply(this, arguments);
343
- try{ pinBlock(); }catch(e){}
344
- return r;
345
- };
346
- window.loadHome.__vtvWrapped = true;
347
- }
348
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/yt_live_v2.js DELETED
@@ -1,348 +0,0 @@
1
- // === VNEWS — VTV1-VTV10 + VTVPrime LIVE CHANNELS + EPG ===
2
- // Uses backend /api/vtv/streams for stream URLs
3
- // Default channel: VTV6 | No double-load | EPG schedule
4
-
5
- (function(){
6
- if(window._ytLiveLoaded) return;
7
- window._ytLiveLoaded = true;
8
-
9
- const CHANNELS = [
10
- {id:'vtv1', name:'VTV1', badge:'Tin tức'},
11
- {id:'vtv2', name:'VTV2', badge:'Khoa học'},
12
- {id:'vtv3', name:'VTV3', badge:'Giải trí'},
13
- {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
14
- {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
15
- {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
16
- {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
17
- {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
18
- {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
19
- {id:'vtv10', name:'VTV10', badge:'VTV10'},
20
- {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
21
- ];
22
-
23
- // ===== EPG — Lịch phát sóng mẫu cho từng kênh =====
24
- const EPG = {
25
- vtv1: [
26
- {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ự'},
27
- {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'},
28
- {t:'21:00',n:'Thời sự đêm'},{t:'23:00',n:'Nhật ký ngày mai'},
29
- ],
30
- vtv2: [
31
- {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'},
32
- {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à'},
33
- {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'},
34
- ],
35
- vtv3: [
36
- {t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'10:00',n:'Gameshow'},
37
- {t:'12:00',n:'Âm nhạc'},{t:'14:00',n:'Phim truyện'},{t:'16:00',n:'Giải trí chiều'},
38
- {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í'},
39
- ],
40
- vtv4: [
41
- {t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'10:00',n:'Culture'},
42
- {t:'12:00',n:'Midday News'},{t:'14:00',n:'Documentary'},{t:'16:00',n:'Sports'},
43
- {t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'},{t:'22:00',n:'Nightline'},
44
- ],
45
- vtv5: [
46
- {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'},
47
- {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'},
48
- {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'},
49
- ],
50
- vtv6: [
51
- {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ẻ'},
52
- {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'},
53
- {t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'},{t:'22:00',n:'Thanh niên & Đêm'},
54
- ],
55
- vtv7: [
56
- {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'},
57
- {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'},
58
- {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'},
59
- ],
60
- vtv8: [
61
- {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'},
62
- {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'},
63
- {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'},
64
- ],
65
- vtv9: [
66
- {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'},
67
- {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'},
68
- {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'},
69
- ],
70
- vtv10: [
71
- {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'},
72
- {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ộ'},
73
- {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'},
74
- ],
75
- vtvprime: [
76
- {t:'06:00',n:'Prime Morning'},{t:'08:00',n:'Prime Cinema'},{t:'10:00',n:'Prime Sports'},
77
- {t:'12:00',n:'Prime News'},{t:'14:00',n:'Prime Drama'},{t:'16:00',n:'Prime Entertainment'},
78
- {t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'},{t:'22:00',n:'Prime Late'},
79
- ],
80
- };
81
-
82
- // ALL external streams need proxy — VTVGo/fptplay CDNs don't send CORS headers
83
- const STREAMS = {};
84
- let _currentCh = null;
85
- let _hls = null;
86
- let _loading = false;
87
- let _epgVisible = false;
88
-
89
- const s = document.createElement('style');
90
- s.textContent = `
91
- .vtv-wrap{margin:6px 4px;background:#111;border:1px solid #0066cc;border-radius:10px;overflow:hidden}
92
- .vtv-head{display:flex;align-items:center;gap:8px;padding:8px 10px;background:linear-gradient(90deg,#003366,#1a1a1a)}
93
- .vtv-title{font-size:13px;font-weight:800;color:#00ccff}
94
- .vtv-badge{font-size:10px;font-weight:800;color:#00ccff;animation:vtvp 1.3s infinite}
95
- @keyframes vtvp{0%,100%{opacity:1}50%{opacity:.3}}
96
- .vtv-tabs{display:flex;gap:3px;padding:6px 8px;overflow-x:auto;scrollbar-width:none;background:#0d1a2a}
97
- .vtv-tabs::-webkit-scrollbar{display:none}
98
- .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}
99
- .vtv-tab:hover{background:#0b4a7a;color:#fff}
100
- .vtv-tab.on{background:#0066cc;border-color:#00ccff;color:#fff;font-weight:700}
101
- .vtv-tab.off{opacity:.35;pointer-events:none}
102
- .vtv-frame{position:relative;width:100%;aspect-ratio:16/9;background:#000;min-height:180px}
103
- .vtv-frame video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
104
- .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}
105
- .vtv-err button{background:#0066cc;border:none;color:#fff;padding:6px 14px;border-radius:8px;font-size:11px;cursor:pointer}
106
- .vtv-load{display:flex;align-items:center;justify-content:center;height:180px;color:#00ccff;font-size:12px;flex-direction:column;gap:8px}
107
- .vtv-spinner{width:24px;height:24px;border:2px solid #333;border-top-color:#00ccff;border-radius:50%;animation:vtvspin .8s linear infinite}
108
- @keyframes vtvspin{to{transform:rotate(360deg)}}
109
- .vtv-epg{margin:0;padding:6px 10px;background:#0a1628;border-top:1px solid #1a2a3a}
110
- .vtv-epg-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:4px}
111
- .vtv-epg-title{font-size:10px;font-weight:700;color:#00ccff}
112
- .vtv-epg-toggle{background:none;border:1px solid #2a3a4a;color:#8ab4d8;font-size:9px;padding:2px 8px;border-radius:6px;cursor:pointer}
113
- .vtv-epg-list{display:flex;gap:4px;overflow-x:auto;scrollbar-width:none;padding-bottom:4px}
114
- .vtv-epg-list::-webkit-scrollbar{display:none}
115
- .vtv-epg-item{flex:0 0 auto;padding:3px 6px;background:#1a2a3a;border-radius:4px;font-size:8px;color:#8ab4d8;white-space:nowrap}
116
- .vtv-epg-item.now{background:#0066cc;color:#fff;font-weight:700}
117
- .vtv-epg-item .epg-t{font-size:7px;color:#6a8aaa}
118
- .vtv-epg-item.now .epg-t{color:#aaccee}
119
- .vtv-epg-item .epg-n{color:#ccc;font-size:8px}
120
- .vtv-epg-item.now .epg-n{color:#fff}
121
- `;
122
- document.head.appendChild(s);
123
-
124
- function getCurrentHour(){
125
- return new Date().getHours();
126
- }
127
-
128
- function buildEPGHTML(chId){
129
- const epg = EPG[chId] || [];
130
- if(!epg.length) return '';
131
- const curH = getCurrentHour();
132
- let items = '';
133
- epg.forEach(item => {
134
- const itemH = parseInt(item.t.split(':')[0], 10);
135
- const isNow = itemH <= curH && (itemH + 2) > curH;
136
- items += `<div class="vtv-epg-item${isNow?' now':''}"><div class="epg-t">${item.t}</div><div class="epg-n">${item.n}</div></div>`;
137
- });
138
- return `<div class="vtv-epg" id="vtv-epg">' +
139
- '<div class="vtv-epg-header"><span class="vtv-epg-title">📋 Lịch phát sóng</span>' +
140
- '<button class="vtv-epg-toggle" onclick="window._vtvToggleEPG()">Ẩn/Hiện</button></div>' +
141
- '<div class="vtv-epg-list" id="vtv-epg-list">' + items + '</div></div>';
142
- }
143
-
144
- window._vtvToggleEPG = function(){
145
- const list = document.getElementById('vtv-epg-list');
146
- if(list) list.style.display = list.style.display === 'none' ? 'flex' : 'none';
147
- };
148
-
149
- async function loadAllStreams(){
150
- if(_loading) return;
151
- _loading = true;
152
- const loadEl = document.getElementById('vtv-load');
153
- if(loadEl) loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang tải danh sách kênh...';
154
-
155
- try {
156
- const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(10000)});
157
- if(r.ok){
158
- const data = await r.json();
159
- CHANNELS.forEach(ch => {
160
- const info = data[ch.id];
161
- if(info && info.stream_url){
162
- // Always proxy through backend to avoid CORS issues
163
- const url = '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(info.stream_url);
164
- STREAMS[ch.id] = [url];
165
- } else {
166
- STREAMS[ch.id] = [];
167
- }
168
- });
169
- }
170
- } catch(e) {
171
- console.warn('VTV API error:', e);
172
- }
173
-
174
- CHANNELS.forEach(ch => {
175
- const tab = document.getElementById('vtvt-'+ch.id);
176
- if(tab){
177
- if(STREAMS[ch.id] && STREAMS[ch.id].length > 0){
178
- tab.classList.remove('off');
179
- tab.textContent = ch.name;
180
- } else {
181
- tab.style.opacity = '0.35';
182
- tab.textContent = ch.name + ' ✕';
183
- }
184
- }
185
- });
186
- _loading = false;
187
- }
188
-
189
- function buildBlock(){
190
- const w = document.createElement('div');
191
- w.className = 'vtv-wrap';
192
- w.id = 'vtv-block';
193
- let tabs = '';
194
- CHANNELS.forEach(ch => {
195
- tabs += '<button class="vtv-tab off" id="vtvt-'+ch.id+'" onclick="window._vtvPlay(\''+ch.id+'\')">'+ch.name+'</button>';
196
- });
197
- w.innerHTML =
198
- '<div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>' +
199
- '<div class="vtv-tabs">' + tabs + '</div>' +
200
- '<div class="vtv-frame">' +
201
- '<div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>' +
202
- '<video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>' +
203
- '<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>' +
204
- '</div>';
205
- return w;
206
- }
207
-
208
- // ===== PIN BLOCK — called only once via loadHome wrapper =====
209
- function pinBlock(){
210
- const h = document.getElementById('view-home');
211
- if(!h || document.getElementById('vtv-block')) return;
212
- h.insertBefore(buildBlock(), h.firstChild);
213
- loadAllStreams().then(() => {
214
- // Default to VTV6 if available, otherwise first available channel
215
- const tryOrder = ['vtv6','vtv1','vtv2','vtv3','vtv4','vtv5','vtv7','vtv8','vtv9','vtv10'];
216
- for(const chId of tryOrder){
217
- if(STREAMS[chId] && STREAMS[chId].length > 0){
218
- setTimeout(() => window._vtvPlay(chId), 300);
219
- return;
220
- }
221
- }
222
- });
223
- }
224
-
225
- window._vtvRetry = function(){
226
- if(_currentCh) window._vtvPlay(_currentCh);
227
- };
228
-
229
- window._vtvPlay = function(chId){
230
- const ch = CHANNELS.find(c => c.id === chId);
231
- if(!ch) return;
232
- _currentCh = chId;
233
- document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
234
- const tab = document.getElementById('vtvt-'+chId);
235
- if(tab) tab.classList.add('on');
236
- const video = document.getElementById('vtv-player');
237
- const errEl = document.getElementById('vtv-err');
238
- const loadEl = document.getElementById('vtv-load');
239
- const errMsg = document.getElementById('vtv-err-msg');
240
- video.style.display = 'none';
241
- errEl.style.display = 'none';
242
- loadEl.style.display = 'flex';
243
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
244
- if(_hls){ _hls.destroy(); _hls = null; }
245
- const urls = STREAMS[chId] || [];
246
- if(urls.length === 0){
247
- loadEl.style.display = 'none';
248
- errEl.style.display = 'flex';
249
- if(chId === 'vtvprime'){
250
- errMsg.textContent = 'VTVPrime: Kênh trả phí, không có luồng miễn phí.';
251
- } else {
252
- errMsg.textContent = ch.name + ': Không tìm thấy luồng. Thử lại sau.';
253
- }
254
- return;
255
- }
256
- // Update EPG
257
- const epgEl = document.getElementById('vtv-epg');
258
- if(epgEl) epgEl.remove();
259
- const frame = document.querySelector('.vtv-frame');
260
- if(frame){
261
- const epgDiv = document.createElement('div');
262
- epgDiv.innerHTML = buildEPGHTML(chId);
263
- frame.appendChild(epgDiv.firstElementChild);
264
- }
265
- _tryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
266
- };
267
-
268
- function _tryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
269
- if(idx >= urls.length){
270
- loadEl.style.display = 'none';
271
- errEl.style.display = 'flex';
272
- errMsg.textContent = name + ': Tất cả nguồn đều lỗi. Thử lại sau.';
273
- return;
274
- }
275
- const src = urls[idx];
276
- const sourceLabel = ' (' + (idx+1) + '/' + urls.length + ')';
277
- loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + sourceLabel + '...';
278
- if(typeof Hls !== 'undefined' && Hls.isSupported()){
279
- const hls = new Hls({
280
- enableWorker: true,
281
- lowLatencyMode: true,
282
- startLevel: -1,
283
- capLevelToPlayerSize: true,
284
- maxBufferLength: 20,
285
- xhrSetup: function(xhr, url){
286
- if(url.includes('fptplay')){
287
- xhr.setRequestHeader('Referer', 'https://fptplay.vn/');
288
- xhr.setRequestHeader('Origin', 'https://fptplay.vn');
289
- }
290
- }
291
- });
292
- _hls = hls;
293
- hls.loadSource(src);
294
- hls.attachMedia(video);
295
- hls.on(Hls.Events.MANIFEST_PARSED, () => {
296
- video.play().catch(() => {});
297
- loadEl.style.display = 'none';
298
- video.style.display = 'block';
299
- });
300
- let recoverAttempts = 0;
301
- hls.on(Hls.Events.ERROR, (ev, data) => {
302
- if(data.fatal){
303
- if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
304
- recoverAttempts++;
305
- if(recoverAttempts <= 3){
306
- setTimeout(() => hls.startLoad(), 2000);
307
- } else {
308
- hls.destroy();
309
- _hls = null;
310
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
311
- }
312
- } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
313
- try { hls.recoverMediaError(); } catch(e) {}
314
- } else {
315
- hls.destroy();
316
- _hls = null;
317
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
318
- }
319
- }
320
- });
321
- } else if(video.canPlayType('application/vnd.apple.mpegurl')){
322
- video.src = src;
323
- video.addEventListener('loadedmetadata', () => {
324
- video.play().catch(() => {});
325
- loadEl.style.display = 'none';
326
- video.style.display = 'block';
327
- }, {once: true});
328
- video.addEventListener('error', () => {
329
- _tryPlay(video, urls, idx + 1, name, loadEl, errEl, errMsg);
330
- }, {once: true});
331
- } else {
332
- loadEl.style.display = 'none';
333
- errEl.style.display = 'flex';
334
- errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
335
- }
336
- }
337
-
338
- // ===== ONLY wrap loadHome — no DOMContentLoaded listener to avoid double-load =====
339
- const orig = window.loadHome;
340
- if(orig && !orig.__vtvWrapped){
341
- window.loadHome = async function(){
342
- const r = await orig.apply(this, arguments);
343
- try{ pinBlock(); }catch(e){}
344
- return r;
345
- };
346
- window.loadHome.__vtvWrapped = true;
347
- }
348
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vtv_scraper.py DELETED
@@ -1,156 +0,0 @@
1
- """
2
- VTV Channels Scraper
3
- Fetches stream URLs from hd.xemtv.net PHP endpoints for VTV1-VTV10 + VTV Cần Thơ
4
- The PHP endpoints return jwplayer config with fresh stream URLs (important for VTV6 which has expiring signatures)
5
- """
6
- import requests, re, time, threading
7
-
8
- UA = {
9
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
10
- "Accept-Language": "vi-VN,vi;q=0.9",
11
- "Referer": "https://hd.xemtv.net/",
12
- }
13
-
14
- # Channel ID -> xemtv.net PHP endpoint mapping
15
- # These PHP pages return jwplayer config with fresh stream URLs
16
- XEMTV_PHP_ENDPOINTS = {
17
- "vtv1": "https://hd.xemtv.net/kenh/vtv1.php",
18
- "vtv2": "https://hd.xemtv.net/kenh/vtv2.php",
19
- "vtv3": "https://hd.xemtv.net/kenh/vtv3.php",
20
- "vtv4": "https://hd.xemtv.net/kenh/vtv4.php",
21
- "vtv5": "https://hd.xemtv.net/kenh/vtv5.php",
22
- "vtv6": "https://hd.xemtv.net/kenh/vtv6.php",
23
- "vtv7": "https://hd.xemtv.net/kenh/vtv7.php",
24
- "vtv8": "https://hd.xemtv.net/kenh/vtv8.php",
25
- "vtv9": "https://hd.xemtv.net/kenh/vtv9.php",
26
- "vtv10": "https://hd.xemtv.net/kenh/vtv10.php", # VTV Cần Thơ
27
- }
28
-
29
- # Channel display names
30
- CHANNEL_NAMES = {
31
- "vtv1": "VTV1",
32
- "vtv2": "VTV2",
33
- "vtv3": "VTV3",
34
- "vtv4": "VTV4",
35
- "vtv5": "VTV5",
36
- "vtv6": "VTV6",
37
- "vtv7": "VTV7",
38
- "vtv8": "VTV8",
39
- "vtv9": "VTV9",
40
- "vtv10": "VTV Cần Thơ",
41
- }
42
-
43
- # Fallback CDN streams (fptplay) — used when xemtv scraping fails
44
- CDN_FALLBACK = {
45
- "vtv1": "https://live.fptplay53.net/fnxch2/vtv1hd_abr.smil/chunklist.m3u8",
46
- "vtv2": "https://live.fptplay53.net/fnxch2/vtv2hd_abr.smil/chunklist.m3u8",
47
- "vtv3": "https://live.fptplay53.net/fnxch2/vtv3hd_abr.smil/chunklist.m3u8",
48
- "vtv4": "https://live.fptplay53.net/fnxch2/vtv4hd_abr.smil/chunklist.m3u8",
49
- "vtv5": "https://live-a.fptplay53.net/live/media/VTV5HD/live_hls_avc/index.m3u8",
50
- "vtv7": "https://live.fptplay53.net/fnxhd1/vtv7hd_vhls.smil/chunklist_b5000000.m3u8",
51
- "vtv8": "https://live.fptplay53.net/epzhd1/vtv8hd_vhls.smil/chunklist.m3u8",
52
- "vtv9": "https://live.fptplay53.net/fnxhd1/vtv9hd_vhls.smil/chunklist.m3u8",
53
- "vtv10": "https://live.fptplay53.net/fnxch2/vtvcantho_abr.smil/chunklist.m3u8",
54
- # VTV6 fallback: try canthotv as alternative
55
- "vtv6": "https://live.canthotv.vn/live/tv/chunklist.m3u8",
56
- }
57
-
58
- _vtv_cache = {}
59
- _vtv_lock = threading.Lock()
60
- _CACHE_TTL = 180 # 3 minutes — refresh frequently for VTV6 sign URLs
61
-
62
-
63
- def _cached(key):
64
- with _vtv_lock:
65
- if key in _vtv_cache and time.time() - _vtv_cache[key]['t'] < _CACHE_TTL:
66
- return _vtv_cache[key]['d']
67
- return None
68
-
69
-
70
- def _set_cache(key, data):
71
- with _vtv_lock:
72
- _vtv_cache[key] = {'t': time.time(), 'd': data}
73
-
74
-
75
- def extract_m3u8_from_html(html):
76
- """Extract m3u8 URL from xemtv PHP page (jwplayer config)."""
77
- if not html:
78
- return None
79
- # jwplayer config: file: 'URL'
80
- m = re.search(r"file\s*:\s*['\"]([^'\"]*\.m3u8[^'\"]*)['\"]", html, re.IGNORECASE)
81
- if m:
82
- url = m.group(1).strip()
83
- if len(url) > 20:
84
- return url
85
- # Generic m3u8 pattern
86
- m = re.search(r"(https?://[^\s\"'<>\\]+\.m3u8[^\s\"'<>\\]*)", html, re.IGNORECASE)
87
- if m:
88
- url = m.group(1).strip()
89
- if len(url) > 20:
90
- return url
91
- return None
92
-
93
-
94
- def fetch_vtv_stream(channel_id):
95
- """Fetch m3u8 stream URL for a VTV channel by scraping xemtv.net PHP endpoint."""
96
- channel_id = channel_id.lower().strip()
97
-
98
- # Normalize name
99
- name_map = {
100
- 'vtvct': 'vtv10', 'vtv-can-tho': 'vtv10', 'vtv can tho': 'vtv10',
101
- 'vtv_can_tho': 'vtv10', 'cantho': 'vtv10', 'cần thơ': 'vtv10',
102
- 'vietnam_vtv1': 'vtv1', 'vietnam_vtv2': 'vtv2', 'vietnam_vtv3': 'vtv3',
103
- 'vietnam_vtv4': 'vtv4', 'vietnam_vtv5': 'vtv5', 'vietnam_vtv6': 'vtv6',
104
- 'vietnam_vtv7': 'vtv7', 'vietnam_vtv8': 'vtv8', 'vietnam_vtv9': 'vtv9',
105
- }
106
- channel_id = name_map.get(channel_id, channel_id)
107
-
108
- # Check cache
109
- cached = _cached(channel_id)
110
- if cached:
111
- return cached
112
-
113
- php_url = XEMTV_PHP_ENDPOINTS.get(channel_id)
114
- if not php_url:
115
- # Fallback
116
- fallback = CDN_FALLBACK.get(channel_id)
117
- if fallback:
118
- _set_cache(channel_id, fallback)
119
- return fallback
120
- return None
121
-
122
- try:
123
- r = requests.get(php_url, headers=UA, timeout=15, allow_redirects=True)
124
- if r.status_code == 200:
125
- m3u8 = extract_m3u8_from_html(r.text)
126
- if m3u8:
127
- _set_cache(channel_id, m3u8)
128
- return m3u8
129
- except:
130
- pass
131
-
132
- # Fallback to CDN
133
- fallback = CDN_FALLBACK.get(channel_id)
134
- if fallback:
135
- _set_cache(channel_id, fallback)
136
- return fallback
137
-
138
- return None
139
-
140
-
141
- def get_all_vtv_streams():
142
- """Fetch all VTV channel streams. Returns list of {id, name, stream_url}."""
143
- channels = []
144
- for ch_id, php_url in XEMTV_PHP_ENDPOINTS.items():
145
- stream_url = fetch_vtv_stream(ch_id)
146
- channels.append({
147
- 'id': ch_id,
148
- 'name': CHANNEL_NAMES.get(ch_id, ch_id.upper()),
149
- 'stream_url': stream_url,
150
- })
151
- return channels
152
-
153
-
154
- # Legacy compatibility
155
- XEMTV_CHANNELS = {v: k for k, v in CHANNEL_NAMES.items()}
156
- CDN_STREAMS = {v: k for k, v in CDN_FALLBACK.items()}