diff --git "a/main.py" "b/main.py" --- "a/main.py" +++ "b/main.py" @@ -1,511 +1,374 @@ -"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + VTV channels""" -import re, time, subprocess, json, os, threading +"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube FPT shorts""" +import hashlib, re, time, subprocess, json, os, threading import html as html_lib -from datetime import datetime, timezone, timedelta, date -from collections import defaultdict +from datetime import datetime, timezone, timedelta VN_TZ = timezone(timedelta(hours=7)) from concurrent.futures import ThreadPoolExecutor, as_completed from fastapi import FastAPI, Query, Request from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response -from urllib.parse import quote +from fastapi.staticfiles import StaticFiles +from urllib.parse import unquote, quote, urlencode import requests from bs4 import BeautifulSoup app = FastAPI() -# ===== WORLD CUP 2026 SCRAPER ===== -from wc2026_scraper import get_wc2026_all, scrape_fixtures, scrape_standings, scrape_stats, scrape_wc_news - -# ===== RATE LIMITING ===== -_rate_limit_data = defaultdict(list) -_rate_limit_lock = threading.Lock() -RATE_LIMIT_MAX = 60 -RATE_LIMIT_WINDOW = 60 - -def _check_rate_limit(ip: str) -> bool: - with _rate_limit_lock: - now = time.time() - _rate_limit_data[ip] = [t for t in _rate_limit_data[ip] if now - t < RATE_LIMIT_WINDOW] - if len(_rate_limit_data[ip]) >= RATE_LIMIT_MAX: return False - _rate_limit_data[ip].append(now) - return True - -@app.middleware("http") -async def rate_limit_middleware(request: Request, call_next): - if request.url.path.startswith("/api/"): - ip = request.client.host - if not _check_rate_limit(ip): return JSONResponse({"error": "rate limit exceeded"}, status_code=429) - return await call_next(request) - -# ===== VTV CHANNELS API ===== +# ===== VTV CHANNELS API (VTV1-VTV10 + VTVPrime) ===== from vtv_api import router as vtv_router app.include_router(vtv_router) HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Accept-Language":"vi-VN,vi;q=0.9,en;q=0.8"} BONGDA_HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept-Language":"vi-VN,vi;q=0.9","Referer":"https://bongda.com.vn/lich-thi-dau","X-Requested-With":"XMLHttpRequest"} BASE_BDP = "https://bongdaplus.vn" +SPACE_URL = "https://bep40-vnews.hf.space" _cache = {} _cache_ttl = 300 _cache_ttl_live = 60 _cache_ttl_yt = 1800 - +SHORTS_FALLBACK = [ +{"id":"Lu_iCQ5YwNM","title":"Công an lập hồ sơ xử lý người phụ nữ chửi bới, tát nam tài xế ô tô ở Hà Nội | #shorts","channel":"baodantri7941"}, +{"id":"CwWvijF8BOA","title":"Chú rể Ninh Bình bật khóc nhận món quà bí mật người cha quá cố gửi 26 năm trước | #shorts","channel":"baodantri7941"}, +{"id":"tvPewsc2ph4","title":"Tính năng ẩn trên iPhone giúp giảm mỏi mắt | #shorts","channel":"baodantri7941"}, +{"id":"b1Nxzv9ixlU","title":"Y án 3 năm tù với nữ tài xế uống 8 lon bia lái xe tông chủ tịch xã tử vong | #shorts","channel":"baodantri7941"}, +{"id":"Xp5eTwAZAis","title":"Người đánh hàng xóm tại chung cư ở Hà Nội bị tuyên hơn 4 tháng tù | #shorts","channel":"baodantri7941"}, +{"id":"Htzvwg6iOBM","title":"Xe điện Audi S6 Sportback e-tron có gì đặc biệt? | #shorts","channel":"baodantri7941"}, +{"id":"iMdFmWvYdlo","title":"Cô gái người Nga yêu thời trang và đất nước Việt Nam | #shorts","channel":"baodantri7941"}, +{"id":"IVaRc6moEv8","title":"Người nông dân Trung Quốc đột quỵ, bệnh viện giúp bán sạch 4 tấn táo | #shorts","channel":"baodantri7941"}, +{"id":"uVxqPxToItU","title":"Công an vào cuộc vụ người phụ nữ chửi bới, hành hung tài xế ô tô ở Hà Nội | #shorts","channel":"baodantri7941"}, +{"id":"VAfgNNgZDRs","title":"Khởi tố 4 đối tượng ném bom xăng vào nhà dân ở Đồng Nai | #shorts","channel":"baodantri7941"}, +{"id":"sBH_-zGh0Xw","title":"Vì sao Times New Roman vẫn nổi tiếng sau hàng chục năm? | #shorts","channel":"baodantri7941"}, +{"id":"woKn5f2bLHM","title":"Quảng Ninh ngập sâu diện rộng sau đợt mưa lớn | #shorts","channel":"baodantri7941"}, +{"id":"bcpgRoxbLPw","title":"Giông lốc quật bay mái tôn ở TP.HCM | #shorts","channel":"baodantri7941"}, +{"id":"ZIIC5osy544","title":"Bé trai Trung Quốc rơi từ tầng 11 vẫn sống sót kỳ diệu | #shorts","channel":"baodantri7941"}, +{"id":"uTMJ49NQpyc","title":"Sau lớp mascot 40kg: Câu chuyện mưu sinh của người trẻ ở TPHCM | #shorts","channel":"baodantri7941"}, +{"id":"7Pd6vZ2Lz1M","title":"Hành động ấm lòng của người đàn ông tham gia tìm kiếm 5 học sinh tử vong ở sông Lô | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"SlHLt_ZyPiE","title":"Xử phạt người đàn ông xóa số điện thoại cứu hộ trên cao tốc Bắc - Nam | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"IUOprcJyYr4","title":"Phụ nữ táo bón có phải do lười ăn rau? | SKĐS #shorts","channel":"baosuckhoedoisongboyte"}, +{"id":"YY8ojFNE-AU","title":"Quái xế tự quay clip nẹt pô, đánh võng đăng TikTok bị xử lý | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"OV7_oGdQGII","title":"Bố cô dâu khóc sụt sùi rồi quẩy cực sung gây bão mạng | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"FoxhFyz2skY","title":"Người đàn ông nước ngoài đập phá ô tô, bẻ cần gạt nước ở Đà Nẵng | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"R1oC_I8dFPU","title":"Thanh niên buông tay lái, đứng trên xe máy khi đổ đèo ở Đắk Lắk | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"U0Ft6ChWAIo","title":"Cô giáo kể phút tháo chạy khỏi xe khách trước khi bị lũ vò nát ở Cao Bằng | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"hH0ANeze_4E","title":"Liên tiếp hàng chục con bò bị sét đánh chết trong ngày mưa dông | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"pXWt0QbAzRQ","title":"Va chạm giao thông, người phụ nữ lăng mạ tài xế ô tô | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"UWWLPY1OYt4","title":"CSGT chặn xe khách khống chế đối tượng cướp dây chuyền tại Gia Lai | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"AxhVTQutsuo","title":"Xuất tinh sớm và những hiểu lầm thường gặp | SKĐS #shorts","channel":"baosuckhoedoisongboyte"}, +{"id":"cNy6FgaNxYM","title":"Cô dâu khóc sưng mắt vì 6 chỉ vàng không cánh mà bay trong ngày cưới | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"IDt_S6q59Ro","title":"Chở bạn gái không đội mũ bảo hiểm, thanh niên đấm CSGT | SKĐS","channel":"baosuckhoedoisongboyte"}, +{"id":"LFxJ9Ik6W0A","title":"Mệnh lệnh từ trái tim: CSGT Hà Nội mở đường đưa bé 5 tháng tuổi đi cấp cứu | SKĐS","channel":"baosuckhoedoisongboyte"} +] +for _v in SHORTS_FALLBACK: + _v["link"]="https://www.youtube.com/watch?v="+_v["id"] + _v["img"]="https://i.ytimg.com/vi/"+_v["id"]+"/hqdefault.jpg" + _v["source"]="yt" +SHORT_STATS_FILE = "/data/short_stats.json" if os.path.isdir("/data") else "/app/short_stats.json" +_short_lock = threading.Lock() +def _load_short_db(): + try: + if os.path.exists(SHORT_STATS_FILE): + with open(SHORT_STATS_FILE,"r",encoding="utf-8") as f:return json.load(f) + except:pass + return {} +def _save_short_db(db): + try: + os.makedirs(os.path.dirname(SHORT_STATS_FILE),exist_ok=True) + tmp=SHORT_STATS_FILE+".tmp" + with open(tmp,"w",encoding="utf-8") as f:json.dump(db,f,ensure_ascii=False) + os.replace(tmp,SHORT_STATS_FILE) + except:pass + +def _short_default():return {"views":0,"likes":0,"shares":0,"comments":[]} +WALL_FILE = "/data/wall_posts.json" if os.path.isdir("/data") else "/app/wall_posts.json" +def _load_wall(): + try: + if os.path.exists(WALL_FILE): + with open(WALL_FILE,"r",encoding="utf-8") as f:return json.load(f) + except:pass + return [] +def _save_wall(posts): + try: + os.makedirs(os.path.dirname(WALL_FILE),exist_ok=True) + tmp=WALL_FILE+".tmp" + with open(tmp,"w",encoding="utf-8") as f:json.dump(posts[:100],f,ensure_ascii=False) + os.replace(tmp,WALL_FILE) + except:pass PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"] -LEAGUE_IDS = {"nha":36781,"laliga":38843,"seriea":36072,"bundesliga":40040,"ligue1":37298} -HL_LEAGUES = { - "premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴󠁧󠁢󠁥󠁮󠁧󠁿"}, - "fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"}, - "bundesliga":{"path":"duc/bundesliga","name":"Bundesliga","emoji":"🇩🇪"}, - "serie-a":{"path":"italy/serie-a","name":"Serie A","emoji":"🇮🇹"}, - "la-liga":{"path":"tay-ban-nha/la-liga","name":"La Liga","emoji":"🇪🇸"}, - "champions-league":{"path":"cup-chau-au/uefa-champions-league","name":"Champions League","emoji":"⭐"}, - "europa-league":{"path":"cup-chau-au/uefa-europa-league","name":"Europa League","emoji":"🟠"}, - "world-cup":{"path":"the-gioi/world-cup","name":"World Cup 2026","emoji":"🌍"}, -} +LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212} +HL_LEAGUES = {"premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴󠁧󠁢󠁥󠁮󠁧󠁿"},"fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"},"bundesliga":{"path":"duc/bundesliga","name":"Bundesliga","emoji":"🇩🇪"},"serie-a":{"path":"italy/serie-a","name":"Serie A","emoji":"🇮🇹"},"la-liga":{"path":"tay-ban-nha/la-liga","name":"La Liga","emoji":"🇪🇸"},"champions-league":{"path":"cup-chau-au/uefa-champions-league","name":"Champions League","emoji":"⭐"},"europa-league":{"path":"cup-chau-au/uefa-europa-league","name":"Europa League","emoji":"🟠"},"world-cup":{"path":"the-gioi/world-cup","name":"World Cup 2026","emoji":"🌍"}} def _cached(key, fn, ttl=None): - now=time.time(); t=ttl or _cache_ttl - if key in _cache and now-_cache[key]["t"]=3: score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}" - if len(spans)>=4: minute=spans[3].get_text(strip=True) - if not score and status_el and status_el.select_one(".vs"): score="VS" + href=status_el.get("href","");m=re.search(r'/tran-dau/(\d+)/',href) + if m:event_id=m.group(1) + spans=status_el.find_all("span") if status_el else [];score="";minute="" + if len(spans)>=3:score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}" + if len(spans)>=4:minute=spans[3].get_text(strip=True) + if not score and status_el and status_el.select_one(".vs"):score="VS" league=league_el.get_text(strip=True) if league_el else "" - return {"home":home_el.get_text(strip=True),"away":away_el.get_text(strip=True),"score":score or"VS","minute":minute,"league":league,"time":time_el.get_text(strip=True) if time_el else "","event_id":event_id,"home_logo":home_logo.get("src","") if home_logo else "","away_logo":away_logo.get("src","") if away_logo else "","status":status_type} + return{"home":home_el.get_text(strip=True),"away":away_el.get_text(strip=True),"score":score or"VS","minute":minute,"league":league,"time":time_el.get_text(strip=True) if time_el else "","event_id":event_id,"home_logo":home_logo.get("src","") if home_logo else "","away_logo":away_logo.get("src","") if away_logo else "","status":status_type} # ===== VIDEO PROXY ===== @app.get("/api/proxy/m3u8") def proxy_m3u8(url: str = Query(...)): try: r = requests.get(url, headers=HEADERS, timeout=15) - if r.status_code != 200: return Response(status_code=502, content="upstream error") - lines = r.text.strip().split('\n'); rewritten = [] + if r.status_code != 200:return Response(status_code=502, content="upstream error") + lines = r.text.strip().split('\n');rewritten = [] for line in lines: - if line.startswith('#') or not line.strip(): rewritten.append(line) - else: rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe="")) - return Response(content='\n'.join(rewritten).encode('utf-8'), media_type="application/vnd.apple.mpegurl", headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=300"}) - except: return Response(status_code=502, content="proxy error") + if line.startswith('#') or not line.strip():rewritten.append(line) + else:rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe="")) + return Response(content='\n'.join(rewritten).encode('utf-8'),media_type="application/vnd.apple.mpegurl",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=300"}) + except:return Response(status_code=502, content="proxy error") @app.get("/api/proxy/seg") -def proxy_segment(url: str = Query(...), ua: str = Query(default=None), cookie: str = Query(default=None), auth: str = Query(default=None), max_sec: float = Query(default=0)): - """Proxy a stream segment. For live MPEG-TS streams, streams the raw data - continuously so Hls.js can buffer and play it. The max_sec parameter is - accepted for backwards compatibility but the stream is left open-ended - (the client / CDN closes the read when sufficient data is buffered or the - user navigates away).""" +def proxy_segment(url: str = Query(...)): try: - seg_headers = dict(HEADERS) - if ua: seg_headers["User-Agent"] = ua - if cookie: seg_headers["Cookie"] = cookie - if auth: seg_headers["Authorization"] = auth - # Use a longer timeout for live streams — the upstream may not send - # data for several seconds at a time (key frames, buffer fills). - r = requests.get(url, headers=seg_headers, timeout=(10, 60), stream=True) - if r.status_code != 200: return Response(status_code=502, content="upstream error") - def _stream(): - for chunk in r.iter_content(chunk_size=65536): - yield chunk - return StreamingResponse( - _stream(), - media_type="video/mp2t", - headers={"Access-Control-Allow-Origin":"*","Cache-Control":"no-cache"} - ) - except Exception: - return Response(status_code=502, content="proxy error") + r = requests.get(url, headers=HEADERS, timeout=30) + if r.status_code != 200:return Response(status_code=502, content="upstream error") + data = r.content + if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47:data = data[188:] + return Response(content=data,media_type="video/mp2t",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=3600"}) + except:return Response(status_code=502, content="proxy error") @app.get("/api/proxy/video") def proxy_video(url: str = Query(...), request: Request = None): try: req_headers = dict(HEADERS) - if request and request.headers.get("range"): req_headers["Range"] = request.headers["range"] + if request and request.headers.get("range"):req_headers["Range"] = request.headers["range"] r = requests.get(url, headers=req_headers, timeout=30, stream=True) resp_headers = {"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes","Content-Type":r.headers.get("Content-Type","video/mp4")} - if "Content-Range" in r.headers: resp_headers["Content-Range"] = r.headers["Content-Range"] - if "Content-Length" in r.headers: resp_headers["Content-Length"] = r.headers["Content-Length"] - return StreamingResponse(r.iter_content(chunk_size=256*1024), status_code=r.status_code, headers=resp_headers) - except: return Response(status_code=502, content="proxy error") + if "Content-Range" in r.headers:resp_headers["Content-Range"] = r.headers["Content-RRange"] + if "Content-Length" in r.headers:resp_headers["Content-Length"] = r.headers["Content-Length"] + return StreamingResponse(r.iter_content(chunk_size=256*1024),status_code=r.status_code,headers=resp_headers) + except:return Response(status_code=502, content="proxy error") @app.get("/api/proxy/img") def proxy_img(url: str = Query(...)): + """Proxy images from sources that block hotlinking (DanTri CDN).""" try: - from urllib.parse import urlparse - _u = urlparse(url); _host = _u.netloc.lower() - _referer = "https://dantri.com.vn/" - if "refooty" in _host or "xemlaibongda" in _host: _referer = "https://xemlaibongda.top/" - elif "ytimg" in _host or "youtube" in _host: _referer = "https://www.youtube.com/" - elif "vncecdn" in _host or "vnexpress" in _host: _referer = "https://vnexpress.net/" - r = requests.get(url, headers={**HEADERS, "Referer": _referer}, timeout=10) - if r.status_code != 200: return Response(status_code=502) - return Response(content=r.content, media_type=r.headers.get("Content-Type", "image/jpeg"), headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}) - except: return Response(status_code=502) + r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10) + if r.status_code != 200:return Response(status_code=502) + ct = r.headers.get("Content-Type", "image/jpeg") + return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}) + except:return Response(status_code=502) # ===== XEMLAIBONGDA HIGHLIGHTS ===== def _scrape_xemlaibongda_page(page_path, limit=20): + """Scrape video articles from xemlaibongda.top. Tries multiple CSS selectors for robust parsing.""" try: url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/" - r = requests.get(url, headers=HEADERS, timeout=8) - if r.status_code != 200: return [] + r = requests.get(url, headers=HEADERS, timeout=15) + if r.status_code != 200: + return [] r.encoding = "utf-8" soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() - for a in soup.find_all("a", href=True): + videos = [] + seen = set() + + # Strategy 1: Look for article/video cards with links containing /video/ + # xemlaibongda.top uses various HTML structures, try multiple selectors + selectors = [ + 'a[href*="/video/"]', + 'a[href*="/xem-lai/"]', + '.video-item a', + '.post-item a', + '.item a', + 'article a', + ] + links = [] + for sel in selectors: + links.extend(soup.select(sel)) + + for a in links: href = a.get("href", "") - if "/video/" not in href and "/xem-lai/" not in href: continue - if not href.startswith("http"): href = "https://xemlaibongda.top" + href - clean_href = href.split("?")[0].split("#")[0] - if clean_href in seen: continue - seen.add(clean_href) - img_src = "" + if not href: + continue + # Normalize: pick the main slug part + is_video = "/video/" in href or "/xem-lai/" in href + if not is_video: + # Check if parent has video indicator + parent = a.parent + has_video_icon = parent.find(class_=re.compile(r'vid|play|highlight')) if parent else False + if not has_video_icon: + continue + if not href.startswith("http"): + href = "https://xemlaibongda.top" + href + if href in seen: + continue + seen.add(href) + + # Extract image: check inside the link or its parent img = a.find("img") - if not img and a.parent: img = a.parent.find("img") + if not img and a.parent: + img = a.parent.find("img") if not img: + # search up to 3 levels up p = a.parent - for _ in range(4): - if p and p.find("img"): img = p.find("img"); break - p = p.parent if p else None - if img: - img_src = (img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", "") or img.get("data-thumb", "") or img.get("data-image", "")) - if img_src.startswith("//"): img_src = "https:" + img_src - elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src - if not img_src: - p = a.parent - for _ in range(5): - if p is None: break - style = p.get("style", "") - bg_match = re.search(r'url\(["\']?(.*?)["\']?\)', style) - if bg_match: - img_src = bg_match.group(1) - if img_src.startswith("//"): img_src = "https:" + img_src - elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src + for _ in range(3): + if p and p.find("img"): + img = p.find("img") break p = p.parent if p else None + img_src = "" + if img: + img_src = img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", "") + if img_src.startswith("//"): + img_src = "https:" + img_src + elif img_src.startswith("/"): + img_src = "https://xemlaibongda.top" + img_src + + # Extract title: try multiple strategies title = "" - for attr in ["title", "aria-label"]: - val = a.get(attr, "") - if val and len(val) >= 5: title = val; break + # Try heading tags first + for tag in ["h3", "h2", "h4", ".title", ".post-title", ".entry-title", ".video-title"]: + t = a.select_one(tag) if hasattr(a, 'select_one') else None + if t: + title = t.get_text(" ", strip=True) + break if not title: - for selector in ["h3", "h2", "h4", ".title", ".video-title", "strong"]: - try: - el = a.select_one(selector) - if el: t = el.get_text(strip=True) - if t and len(t) >= 5: title = t; break - except: pass + title = a.get("title", "") if not title: - text = a.get_text(strip=True) - if text and len(text) >= 5: title = text[:100] - if not title or len(title) < 3: - slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") - title = slug.replace("-", " ").replace("_", " ").title() + # Try aria-label or alt + title = a.get("aria-label", "") + if not title: + img_for_alt = a.find("img") + if img_for_alt: + title = img_for_alt.get("alt", "") + if not title: + # Last resort: extract from URL slug but clean it up + slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") + title = slug.replace("-", " ").replace("_", " ") title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip() - if not title or len(title) < 3: continue - if not img_src: - slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") - img_src = f"https://xemlaibongda.top/uploads/thumb/{slug}.jpg" - videos.append({"title": title[:100], "link": clean_href, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean_href)}) - if len(videos) >= limit: break + title = title.title() + if not title or len(title) < 3: + continue + + videos.append({"title": title, "link": href, "img": img_src, "source": "xemlaibongda"}) + if len(videos) >= limit: + break + + # Strategy 2: If no videos found via links, look for video elements + if not videos: + for vid_el in soup.find_all("video"): + src = vid_el.get("src", "") + poster = vid_el.get("poster", "") + source_el = vid_el.find("source") + if not src and source_el: + src = source_el.get("src", "") + if src: + title = poster.rsplit("/", 1)[-1].rsplit(".", 1)[0].replace("-", " ").title() if poster else "Video" + videos.append({"title": title, "link": src, "img": poster, "source": "xemlaibongda"}) + if len(videos) >= limit: + break + return videos - except Exception as e: - print(f"[xemlaibongda] Error: {e}"); return [] + except: + return [] -def scrape_xemlaibongda(): return _scrape_xemlaibongda_page("", 20) +def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20) def scrape_highlights_by_league(league_key): - if league_key not in HL_LEAGUES: return [] - # Try bongdaplus.vn first (reliable from HF Spaces), fallback from there - bp_vids = scrape_bongdaplus_by_league(league_key, 20) - if bp_vids: return bp_vids - # Fallback: xemlaibongda.top (may be slow/unreachable) - vids = _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20) - if vids: return vids - # Ultimate fallback: bongdaplus.vn general video feed, only for primary home league - if league_key == "premier-league": - return scrape_bongdaplus_videos(20) - return [] + if league_key not in HL_LEAGUES:return[] + return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20) + def scrape_all_league_highlights(): results = {} - def _fetch(key): return key, scrape_highlights_by_league(key) + def _fetch(key):return key, scrape_highlights_by_league(key) with ThreadPoolExecutor(8) as ex: futs = [ex.submit(_fetch, k) for k in HL_LEAGUES] - for f in as_completed(futs, timeout=20): - try: key, vids = f.result() - except: continue - if vids: results[key] = vids - if not results: - fb = scrape_bongdaplus_videos(20) - if fb: - results["premier-league"] = fb - # The league sub-pages resolve to the SAME content from this server (the - # football sites serve one generic list regardless of league path). Return - # the unique videos once per league (deduped against the global set) and - # enrich with the general bongdaplus feed so the homepage slider gets a - # genuinely bigger, duplicate-free list instead of 8x the same 10 clips. - global_seen = set() - seen_per_league = {} - enriched = {} - try: - extra = scrape_bongdaplus_videos(40) - except Exception: - extra = [] - for key, vids in list(results.items()): - uniq = [] - fresh = [] - for v in vids: - link = (v or {}).get("link", "") - if not link or link in seen_per_league.get(key, set()): continue - seen_per_league.setdefault(key, set()).add(link) - if link in global_seen: - fresh.append(v) # duplicate across leagues — will dedupe - continue - global_seen.add(link) - uniq.append(v) - # league-local unique list - if uniq: - results[key] = uniq - # still add across-league dupes to each league so per-league feeds - # are non-empty, but ONLY if the league has < 10 unique videos - if len(uniq) < 10: - for v in fresh: - link = (v or {}).get("link", "") - if link in seen_per_league.get(key, set()): continue - seen_per_league[key].add(link) - uniq.append(v) - results[key] = uniq - # enrich league with global feed leftovers when it's still thin - if len(uniq) < 10: - for v in extra: - link = (v or {}).get("link", "") - if not link or link in seen_per_league.get(key, set()): continue - seen_per_league[key].add(link) - uniq.append(v) - results[key] = uniq - return results - -BDP_HL = "https://bongdaplus.vn/video" -def _video_published(img_src, link=""): - """Best-effort publish date from image URL (bongdaplus stores dates as - /Media/YYYY/MM/DD/) or from a dated slug. Returns 'YYYY-MM-DD' or ''.""" - try: - if img_src: - m = re.search(r"/Media/(\d{4})/(\d{2})/(\d{2})/", img_src) - if m: - return "%s-%s-%s" % (m.group(1), m.group(2), m.group(3)) - if link: - m2 = re.search(r"/(\d{4})/(\d{2})/(\d{2})/", link) - if m2: - return "%s-%s-%s" % (m2.group(1), m2.group(2), m2.group(3)) - except Exception: - pass - return "" - -def scrape_bongdaplus_videos(limit=20): - """Scrape football highlight/clip videos from bongdaplus.vn/video (reachable from HF Spaces).""" - try: - r = requests.get(BDP_HL, headers=HEADERS, timeout=15) - if r.status_code != 200: return [] - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() - for a in soup.find_all("a", href=True): - href = a.get("href","") - if "/video/" not in href or not href.endswith(".html"): continue - if not href.startswith("http"): href = "https://bongdaplus.vn" + href - link = href.split("?")[0].split("#")[0] - if link in seen: continue - seen.add(link) - img_src = "" - img = a.find("img") - if img: - img_src = img.get("data-src","") or img.get("src","") or "" - title = "" - t = a.get("title","") or "" - if t and len(t)>=5: title = t - if not title: - img_alt = img.get("alt","") if img else "" - if img_alt and len(img_alt)>=5: title = img_alt - if not title: - txt = a.get_text(strip=True) - if txt and len(txt)>=5: title = txt - title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip() - if not title or len(title)<5: continue - if img_src and img_src.startswith("//"): img_src = "https:" + img_src - videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)}) - if len(videos) >= limit: break - return videos - except Exception as e: - print(f"[bongdaplus] Error: {e}"); return [] - -# Bongdaplus.vn league-specific video URLs (used as fallback when xemlaibongda.top fails) -BDP_LEAGUE_URLS = { - "premier-league": "https://bongdaplus.vn/video/premier-league", - "la-liga": "https://bongdaplus.vn/video/la-liga", - "serie-a": "https://bongdaplus.vn/video/serie-a", - "bundesliga": "https://bongdaplus.vn/video/bundesliga", - "champions-league": "https://bongdaplus.vn/video/champions-league", - "fa-cup": "https://bongdaplus.vn/video/fa-cup", - "europa-league": "https://bongdaplus.vn/video/europa-league", - "world-cup": "https://bongdaplus.vn/video/world-cup", -} -def scrape_bongdaplus_by_league(league_key, limit=20): - """Scrape bongdaplus.vn video page for a specific league.""" - url = BDP_LEAGUE_URLS.get(league_key) - if not url: return [] - try: - r = requests.get(url, headers=HEADERS, timeout=15) - if r.status_code != 200: return [] - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() - for a in soup.find_all("a", href=True): - href = a.get("href","") - if "/video/" not in href or not href.endswith(".html"): continue - if not href.startswith("http"): href = "https://bongdaplus.vn" + href - link = href.split("?")[0].split("#")[0] - if link in seen: continue - seen.add(link) - img_src = "" - img = a.find("img") - if img: - img_src = img.get("data-src","") or img.get("src","") or "" - title = "" - t = a.get("title","") or "" - if t and len(t)>=5: title = t - if not title: - img_alt = img.get("alt","") if img else "" - if img_alt and len(img_alt)>=5: title = img_alt - if not title: - txt = a.get_text(strip=True) - if txt and len(txt)>=5: title = txt - title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip() - if not title or len(title)<5: continue - if img_src and img_src.startswith("//"): img_src = "https:" + img_src - videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)}) - if len(videos) >= limit: break - return videos - except Exception as e: - print(f"[bongdaplus:{league_key}] Error: {e}"); return [] - -def extract_bongdaplus_video(url): - """Extract direct MP4 from bongdaplus.vn video detail via its embed page. - - The embed page (/video-embed/{id}.html) sometimes only has a JPG placeholder - as . In that case, fall back to the main video page - (/video/{slug}.html) which contains a YouTube iframe with the actual - highlight. - """ - try: - m = re.search(r'/video/(?:[^/]+-)?(\d+)\.html', url) - if not m: - return None - vid = m.group(1) - embed = f"https://bongdaplus.vn/video-embed/{vid}.html" - r = requests.get(embed, headers=HEADERS, timeout=15) - if r.status_code != 200: return None - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - video = soup.find("video") - src = "" - poster = "" - if video: - src = video.get("src","") - poster = video.get("poster","") - if not src: - src_el = soup.find("source") - if src_el: src = src_el.get("src","") - if not src: return None - src = src.split("?")[0].split("#")[0] - # Only accept real media; placeholder .jpg/jpeg/png means video not available - if not re.search(r'\.(mp4|m3u8|webm)$', src, re.I): - # The embed source is a JPG placeholder — fall back to the main video - # page and look for a YouTube iframe (actual highlight video). + for f in as_completed(futs): try: - r2 = requests.get(url, headers=HEADERS, timeout=15) - if r2.status_code == 200: - soup2 = BeautifulSoup(r2.text, "lxml") - yt_iframe = soup2.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed")) - if yt_iframe: - yt_src = yt_iframe.get("src","").strip() - if yt_src.startswith("//"): yt_src = "https:" + yt_src - yt_id = re.search(r'/(?:embed|v)/([a-zA-Z0-9_-]{11})', yt_src) - if yt_id: - poster = poster or "" - if not poster: - og = soup2.find("meta", property="og:image") - if og: poster = og.get("content","") - if not poster: - og = soup.find("meta", property="og:image") - if og: poster = og.get("content","") - return {"src": f"https://www.youtube.com/embed/{yt_id.group(1)}?autoplay=1&rel=0&enablejsapi=1", "poster": poster or yt_src, "type": "youtube"} - except Exception: - pass - return None - if not poster: - og = soup.find("meta",property="og:image") - if og: poster = og.get("content","") - return {"src": src, "poster": poster, "type": "video"} - except Exception: - return None + key, vids = f.result() + if vids:results[key] = vids + except:pass + return results def extract_xemlaibongda_video(url): try: - r=requests.get(url, headers=HEADERS, timeout=15) - if r.status_code!=200: return None - r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml") - og=soup.find("meta",property="og:image") - og_poster=og.get("content","") if og else "" - if og_poster.startswith("//"): og_poster="https:"+og_poster - video=soup.find("video") + r=requests.get(url,headers=HEADERS,timeout=15) + if r.status_code!=200:return None + r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");video=soup.find("video") if video: - src=video.get("src",""); poster=video.get("poster","") + src=video.get("src","");poster=video.get("poster","") if not src: source=video.find("source") - if source: src=source.get("src","") - if not poster: poster=og_poster - if src: return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"} + if source:src=source.get("src","") + if src:return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"} m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text) - if m3u8s: return{"src":m3u8s[0],"poster":og_poster,"type":"hls"} - yt_iframe = soup.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed")) - if yt_iframe: return{"src":yt_iframe.get("src",""),"poster":og_poster,"type":"youtube"} + if m3u8s: + og=soup.find("meta",property="og:image");poster=og.get("content","") if og else "" + return{"src":m3u8s[0],"poster":poster,"type":"hls"} return None - except: return None + except:return None + +# ===== YOUTUBE SHORTS ===== +def _yt_channel_shorts(channel, count=15): + """Fast scrape YouTube shorts tab without yt-dlp. Returns newest-first IDs/titles.""" + try: + url=f"https://www.youtube.com/@{channel}/shorts" + r=requests.get(url,headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},timeout=15) + if r.status_code!=200:return[] + html=r.text + ids=[];items=[] + for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html): + vid=m.group(1) + if vid in ids:continue + ids.append(vid) + snip=html[max(0,m.start()-900):m.start()+1600] + title="" + mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip) + if not mt:mt=re.search(r'"accessibilityText":"([^"]+)"',snip) + if mt:title=html_lib.unescape(mt.group(1)).replace('\n',' ').strip() + if not title:title="YouTube Short" + items.append({"title":title,"link":f"https://www.youtube.com/watch?v={vid}","img":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","source":"yt","id":vid,"channel":channel}) + if len(items)>=count:break + return items + except:return[] +def scrape_shorts(): + """Stable shorts feed: fast HTML scrape + static fallback so slide never disappears.""" + vids=[] + with ThreadPoolExecutor(2) as ex: + futs=[ex.submit(_yt_channel_shorts,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]] + for f in as_completed(futs): + try: + r=f.result() + if r:vids.extend(r) + except:pass + merged=[];seen=set() + for v in vids+SHORTS_FALLBACK: + vid=v.get("id") + if not vid or vid in seen:continue + seen.add(vid);merged.append(v) + return merged[:40] # ===== LIVESCORE ===== @app.get("/api/livescore/live") -def api_livescore_live(): return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)}) +def api_livescore_live():return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)}) @app.get("/api/livescore/incoming") -def api_livescore_incoming(): return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)}) +def api_livescore_incoming():return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)}) @app.get("/api/livescore/today") def api_livescore_today(): today=datetime.now(VN_TZ).strftime("%Y-%m-%d");return JSONResponse({"html":_cached("ls_today",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}"),ttl=_cache_ttl)}) @@ -514,221 +377,28 @@ def api_livescore_results(): today=datetime.now(VN_TZ).strftime("%Y-%m-%d");return JSONResponse({"html":_cached("ls_results",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}&status=finished"),ttl=_cache_ttl)}) @app.get("/api/livescore/standings/{league}") def api_livescore_standings(league:str): - tid=LEAGUE_IDS.get(league,36781);return JSONResponse({"html":_cached(f"ls_bxh_{league}",lambda:fetch_bongda_api(f"/api/league-table/home?tournament_id={tid}&is_detail=True"),ttl=_cache_ttl)}) + tid=LEAGUE_IDS.get(league,27110);return JSONResponse({"html":_cached(f"ls_bxh_{league}",lambda:fetch_bongda_api(f"/api/league-table/home?tournament_id={tid}&is_detail=True"),ttl=_cache_ttl)}) @app.get("/api/livescore/date/{date}") def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")}) - -def _compute_updates7d(): - from datetime import date as _date - today = _date.today() - all_html = [] - # Past 7 days (results) - for i in range(7, 0, -1): - d = (today - timedelta(days=i)).strftime("%Y-%m-%d") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - day_label = (today - timedelta(days=i)).strftime("%d/%m") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - # Next 7 days (upcoming) - for i in range(7): - d = (today + timedelta(days=i)).strftime("%Y-%m-%d") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - day_label = (today + timedelta(days=i)).strftime("%d/%m") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - combined = "
" + "".join(all_html) + "
" - return combined if all_html else "" - -_updates7d_cache = {"t": 0, "d": "", "busy": False} -_updates7d_lock = threading.Lock() -def _start_updates7d_refresh(): - def _run(): - try: - with _updates7d_lock: - if _updates7d_cache["busy"]: return - _updates7d_cache["busy"] = True - data = _compute_updates7d() - with _updates7d_lock: - if data: - _updates7d_cache["t"] = time.time() - _updates7d_cache["d"] = data - _updates7d_cache["busy"] = False - except Exception: - with _updates7d_lock: - _updates7d_cache["busy"] = False - th = threading.Thread(target=_run, daemon=True) - th.start() - -@app.get("/api/livescore/updates7d") -def api_livescore_updates7d(): - """Aggregate matches. Never blocks synchronously — returns cached value instantly - and refreshes in a background thread. Pre-warmed at startup.""" - now = time.time() - with _updates7d_lock: - fresh = _updates7d_cache["d"] and (now - _updates7d_cache["t"] < _cache_ttl) - stale = _updates7d_cache["d"] - if not fresh: - _start_updates7d_refresh() - return JSONResponse({"html": stale or "", "cached": bool(stale)}) - -# ===== LIVESCORE RECENT (prioritized: upcoming → just-finished today → yesterday → older) ===== -def _compute_recent(): - """Compute recent livescore with priority: upcoming → just-finished today → yesterday → older.""" - from datetime import date as _date - today = _date.today() - all_html = [] - - # Helper to extract match details with date label - def _extract_matches(date_str, day_label, status_param=""): - url_path = f"/api/fixtures/get-by-date?date={date_str}" - if status_param: - url_path += f"&status={status_param}" - html = fetch_bongda_api(url_path) - if not html or len(html) <= 50: - return - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - - # 1) Trận sắp tới (hôm nay + ngày mai) - upcoming_html = [] - for offset in [0, 1]: - d = (today + timedelta(days=offset)).strftime("%Y-%m-%d") - day_label = (today + timedelta(days=offset)).strftime("%d/%m") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - upcoming_html.append(str(soup)) - if upcoming_html: - all_html.append("
⏰ Trận sắp tới
" + "".join(upcoming_html) + "
") - - # 2) Vừa kết thúc hôm nay - today_str = today.strftime("%Y-%m-%d") - finished_today = fetch_bongda_api(f"/api/fixtures/get-by-date?date={today_str}&status=finished") - if finished_today and len(finished_today) > 50: - soup = BeautifulSoup(finished_today, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {today.strftime('%d/%m')}" - match.insert(0, dt) - all_html.append("
✅ Vừa kết thúc
" + str(soup) + "
") - - # 3) Hôm qua - yesterday = today - timedelta(days=1) - d = yesterday.strftime("%Y-%m-%d") - html_yesterday = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html_yesterday and len(html_yesterday) > 50: - soup = BeautifulSoup(html_yesterday, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {yesterday.strftime('%d/%m')}" - match.insert(0, dt) - all_html.append("
📅 Hôm qua
" + str(soup) + "
") - - # 4) Các ngày cũ hơn (2 ngày trước → 6 ngày trước) - older_html = [] - for i in range(2, 7): - d = (today - timedelta(days=i)).strftime("%Y-%m-%d") - day_label = (today - timedelta(days=i)).strftime("%d/%m") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - older_html.append(str(soup)) - if older_html: - all_html.append("
🗓️ Kết quả trước
" + "".join(older_html) + "
") - - combined = "
" + "".join(all_html) + "
" - return combined if all_html else "" - -_recent_cache = {"t": 0, "d": "", "busy": False} -_recent_lock = threading.Lock() -def _start_recent_refresh(): - def _run(): - try: - with _recent_lock: - if _recent_cache["busy"]: return - _recent_cache["busy"] = True - data = _compute_recent() - with _recent_lock: - if data: - _recent_cache["t"] = time.time() - _recent_cache["d"] = data - _recent_cache["busy"] = False - except Exception: - with _recent_lock: - _recent_cache["busy"] = False - th = threading.Thread(target=_run, daemon=True) - th.start() - -@app.get("/api/livescore/recent") -def api_livescore_recent(): - """Recent matches with new priority: upcoming today/tomorrow → finished today → yesterday → older.""" - now = time.time() - with _recent_lock: - fresh = _recent_cache["d"] and (now - _recent_cache["t"] < _cache_ttl) - stale = _recent_cache["d"] - if not fresh: - _start_recent_refresh() - return JSONResponse({"html": stale or "", "cached": bool(stale)}) - -def _warm_recent(): - def _warm(): - try: - time.sleep(3) - _start_recent_refresh() - except Exception: - pass - th = threading.Thread(target=_warm, daemon=True) - th.start() -_warm_recent() - -def _warm_updates7d(): - # Lightweight startup pre-warm so the first user request is instant. - def _warm(): - try: - time.sleep(3) - _start_updates7d_refresh() - except Exception: - pass - th = threading.Thread(target=_warm, daemon=True) - th.start() -_warm_updates7d() - @app.get("/api/match/{event_id}/commentaries") def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")}) @app.get("/api/match/{event_id}/stats") def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")}) +# ===== MATCH DETAIL (server-side scrape from bongda.com.vn) ===== from match_detail_v2 import fetch_match_detail, fetch_match_detail_by_url @app.get("/api/match/{event_id}/detail") def api_match_detail(event_id: int, url: str = Query(default="")): + """Get full match detail by scraping bongda.com.vn server-side.""" try: - if url: data = fetch_match_detail_by_url(url) - else: data = fetch_match_detail(event_id) + if url: + data = fetch_match_detail_by_url(url) + else: + data = fetch_match_detail(event_id) return JSONResponse(data) - except Exception as e: return JSONResponse({"event_id": event_id, "found": False, "error": str(e)}) + except Exception as e: + return JSONResponse({"event_id": event_id, "found": False, "error": str(e)}) @app.get("/api/livescore/featured") def api_livescore_featured(): @@ -751,382 +421,548 @@ def api_livescore_featured(): return None return JSONResponse(_cached("ls_featured",_f,ttl=30)) +# ===== VIDEO APIs ===== +@app.get("/api/shorts") +def api_shorts():return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt)) +@app.get("/api/short-stats") +def api_short_stats(ids:str=Query(default="")): + arr=[x for x in ids.split(",") if x] + with _short_lock: + db=_load_short_db();out={} + for vid in arr: + st=db.get(vid) or _short_default() + out[vid]={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]} + return JSONResponse({"stats":out}) + +@app.post("/api/short-action") +async def api_short_action(request:Request): + try:body=await request.json() + except:body={} + vid=str(body.get("id","")).strip();action=str(body.get("action","")).strip();txt=str(body.get("text","")).strip() + if not vid:return JSONResponse({"error":"missing id"},status_code=400) + with _short_lock: + db=_load_short_db();st=db.get(vid) or _short_default() + if action=="view":st["views"]=int(st.get("views",0))+1 + elif action=="like":st["likes"]=int(st.get("likes",0))+1 + elif action=="share":st["shares"]=int(st.get("shares",0))+1 + elif action=="comment" and txt: + comments=st.get("comments",[]) + comments.insert(0,{"text":txt[:180],"ts":int(time.time())}) + st["comments"]=comments[:80] + st["updated"]=int(time.time());db[vid]=st;_save_short_db(db) + out={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]} + return JSONResponse({"stats":out}) + @app.get("/api/highlights") -def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",lambda: scrape_bongdaplus_videos(20) or scrape_xemlaibongda(),ttl=_cache_ttl)) +def api_highlights():return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl)) @app.get("/api/highlights/leagues") -def api_highlights_leagues(): return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl)) +def api_highlights_leagues():return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl)) @app.get("/api/highlights/{league}") def api_highlights_league(league:str): - if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"}) + if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"}) return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl)) - -@app.get("/api/highlights/{league}/page") -def api_highlights_league_page(league:str, page:int=Query(default=0, ge=0), limit:int=Query(default=15, ge=5, le=40)): - """Paginated league highlights for 'Xem thêm' load-more. Supports 'all' to fetch every league aggregated.""" - if league == "all": - all_vids = [] - with ThreadPoolExecutor(8) as ex: - futs = {ex.submit(scrape_highlights_by_league, k): k for k in HL_LEAGUES} - for f in as_completed(futs, timeout=20): - try: - all_vids.extend(f.result()) - except: pass - # The league sub-pages resolve to the same content from this server, - # so dedupe by link — the slider/feed must not show 8x the same 10 - # videos. If dedup leaves few unique items, enrich from the general - # bongdaplus video feed to add genuinely different videos. - seen = set(); uniq = [] - for v in all_vids: - link = (v or {}).get("link", "") - if not link or link in seen: continue - seen.add(link); uniq.append(v) - if len(uniq) < 20: - try: - extra = scrape_bongdaplus_videos(40) - for v in extra: - link = (v or {}).get("link", "") - if not link or link in seen: continue - seen.add(link); uniq.append(v) - except Exception: - pass - all_vids = uniq - start = page * limit - end = start + limit - paged = all_vids[start:end] - return JSONResponse({"videos": paged, "league": "all", "page": page, "has_more": end < len(all_vids), "total": len(all_vids)}) - if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"}) - all_vids = scrape_highlights_by_league(league) - start = page * limit - end = start + limit - paged = all_vids[start:end] - return JSONResponse({"videos": paged, "league": league, "page": page, "has_more": end < len(all_vids), "total": len(all_vids)}) - +@app.get("/api/highlights_config") +def api_highlights_config():return JSONResponse(HL_LEAGUES) @app.get("/api/video_url") -def api_video_url(url:str=Query(...), img:str=Query(default="")): +def api_video_url(url:str=Query(...)): if "youtube.com" in url or "youtu.be" in url: m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url) - if m: vid=m.group(1); return JSONResponse({"src":f"https://www.youtube.com/embed/{vid}?autoplay=1&rel=0&enablejsapi=1","poster":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","type":"youtube"}) + if m:vid=m.group(1);return JSONResponse({"src":f"https://www.youtube.com/embed/{vid}?autoplay=1&rel=0&enablejsapi=1","poster":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","type":"youtube"}) if "xemlaibongda.top" in url: v=extract_xemlaibongda_video(url) if v: - if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="") - if not v.get("poster") and img: v["poster"] = img - return JSONResponse(v) - if "bongdaplus.vn" in url and "/video/" in url: - v=extract_bongdaplus_video(url) - if v: - if not v.get("poster") and img: v["poster"] = img + if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="") return JSONResponse(v) + if "bongdaplus.vn" in url: + try: + m=re.search(r'-(\d{6,})\.html',url) + if m: + r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer") + if video: + source=video.find("source");src=source.get("src","") if source else "";poster=video.get("poster","") + if src:return JSONResponse({"src":"/api/proxy/video?url="+quote(src,safe=""),"poster":poster,"type":"video"}) + except:pass return JSONResponse({"error":"not found"}) - -# ===== FPT PLAY (YouTube channel) API ===== -# The datacenter cannot reach youtube.com directly, so this endpoint keeps a -# persisted list of the channel's latest videos. The frontend (running in the -# user's browser, which CAN reach YouTube) periodically fetches the channel via -# r.jina.ai, then POSTs the result here so the slide auto-updates when the -# channel uploads — exactly like "Thêm Short HOT" but fully automatic. -FPT_FILE = "/data/fpt_play_videos.json" -FPT_CHANNEL_URL = "https://www.youtube.com/@fptbongdaofficial" -FPT_CACHE_TTL = 600 # 10 min - -def _fpt_load(): - try: - if os.path.exists(FPT_FILE): - with open(FPT_FILE, encoding="utf-8") as f: - j = json.load(f) - if isinstance(j, list): - return j - except Exception: - pass - return [] - -def _fpt_save(videos): - try: - with open(FPT_FILE, "w", encoding="utf-8") as f: - json.dump(videos, f, ensure_ascii=False) - except Exception: - pass - -def _fpt_try_server_fetch(): - """Server-side attempt (jina proxy with our Origin). Usually blocked from - the datacenter, but harmless to try once so the slide works even without - a client push.""" - try: - _hdrs = dict(HEADERS) - _hdrs["Origin"] = "https://bep40-vnews.hf.space" - r = requests.get("https://r.jina.ai/" + FPT_CHANNEL_URL + "/videos", - headers=_hdrs, timeout=40) - if r.status_code != 200: - return [] - txt = r.text - out = [] - seen = set() - # jina markdown lists entries as "1. Title - url" or link lines with yt ids - for m in re.finditer(r"https?://(?:www\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})", txt): - vid = m.group(1) - if vid in seen: continue - seen.add(vid) - out.append({ - "id": vid, - "title": "", - "link": "https://youtu.be/" + vid, - "img": "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid, - "source": "fptplay", - "published": "", - }) - return out - except Exception: - return [] - -@app.get("/api/fptplay/videos") -def api_fptplay_videos(): - vids = _fpt_load() - if not vids: - vids = _fpt_try_server_fetch() - if vids: _fpt_save(vids) - return JSONResponse({"channel": FPT_CHANNEL_URL, "videos": vids, "updated": int(time.time())}) - -@app.post("/api/fptplay/update") -async def api_fptplay_update(request: Request): - try: - body = await request.json() - except Exception: - body = {} - incoming = body.get("videos") or [] - if not isinstance(incoming, list) or not incoming: - return JSONResponse({"ok": True, "videos": _fpt_load()}) - seen = set() - merged = [] - for v in _fpt_load(): - vid = (v or {}).get("id", "") - if vid and vid in seen: continue - if vid: seen.add(vid) - merged.append(v) - added = 0 - for v in incoming: - vid = (v or {}).get("id", "") or "" - if not vid or vid in seen: continue - seen.add(vid) - # keep user-friendly fields, always normalize the watch link - merged.append({ - "id": vid, - "title": (v.get("title") or "").strip()[:200], - "link": (v.get("link") or "https://youtu.be/" + vid), - "img": (v.get("img") or "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid), - "source": "fptplay", - "published": (v.get("published") or "")[:10], - }) - added += 1 - # newest first - merged.sort(key=lambda x: (x.get("published") or ""), reverse=True) - _fpt_save(merged[:50]) - return JSONResponse({"ok": True, "added": added, "videos": merged[:50]}) - -# ===== WORLD CUP 2026 API ===== -_wc_request_times = []; _wc_rate_limit_lock = threading.Lock() -_WC_RATE_LIMIT = 10 -def _wc_rate_limit(): - global _wc_request_times - with _wc_rate_limit_lock: - now = time.time() - _wc_request_times = [t for t in _wc_request_times if now - t < 60] - if len(_wc_request_times) >= _WC_RATE_LIMIT: return False - _wc_request_times.append(now) - return True - -@app.get("/api/wc2026") -def api_wc2026(): - return JSONResponse(_cached("wc2026", get_wc2026_all, ttl=_cache_ttl)) - -@app.get("/api/wc2026/{tab}") -def api_wc2026_tab(tab: str): - valid_tabs = ["news", "fixtures", "standings", "stats", "highlights"] - if tab not in valid_tabs: return JSONResponse({"error": "invalid tab"}, status_code=400) - def _fetch_tab(): - if tab == "highlights": return scrape_highlights_by_league("world-cup") - elif tab == "news": return scrape_wc_news() - elif tab == "fixtures": return scrape_fixtures() - elif tab == "standings": return scrape_standings() - elif tab == "stats": return scrape_stats() - return [] - return JSONResponse(_cached(f"wc2026_{tab}", _fetch_tab, ttl=_cache_ttl)) - @app.get("/api/bdp_videos") def api_bdp_videos(): def _f(): try: - soup=_get(f"{BASE_BDP}/video"); arts=[]; seen=set() + soup=_get(f"{BASE_BDP}/video");arts=[];seen=set() for a in soup.find_all("a",href=True): href=a.get("href","") if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue - if not href.startswith("http"): href=BASE_BDP+href - if href in seen: continue + if not href.startswith("http"):href=BASE_BDP+href + if href in seen:continue title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip() - if not title or len(title)<5: continue + if not title or len(title)<5:continue img_tag=a.find("img") or(a.parent.find("img") if a.parent else None) img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else "" - seen.add(href); arts.append({"title":title,"link":href,"img":img,"source":"bdp"}) + seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"}) return arts[:20] - except: return [] + except:return[] return JSONResponse(_cached("bdp_videos",_f)) - # ===== NEWS ===== -VNE_CATS={"thoi-su":("https://vnexpress.net/thoi-su","Thời Sự"),"the-gioi":("https://vnexpress.net/the-gioi","Thế Giới"),"kinh-doanh":("https://vnexpress.net/kinh-doanh","Kinh Doanh"),"the-thao":("https://vnexpress.net/the-thao","Thể Thao"),"giai-tri":("https://vnexpress.net/giai-tri","Giải Trí"),"suc-khoe":("https://vnexpress.net/suc-khoe","Sức Khỏe"),"phap-luat":("https://vnexpress.net/phap-luat","Pháp Luật"),"giao-duc":("https://vnexpress.net/giao-duc","Giáo Dục"),"du-lich":("https://vnexpress.net/du-lich","Du Lịch"),"doi-song":("https://vnexpress.net/doi-song","Đời Sống")} - def scrape_vne(cat_url): try: - soup=_get(cat_url); arts=[] + soup=_get(cat_url);arts=[] for it in soup.select("article.item-news")[:15]: a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a") - if not a: continue - t=a.get("title","") or a.get_text(strip=True); lk=a.get("href","") - if not t or not lk: continue - im=it.find("img"); img=(im.get("data-src") or im.get("src","")) if im else "" - if img and 'blank' in img: + if not a:continue + t=a.get("title","") or a.get_text(strip=True);lk=a.get("href","") + if not t or not lk:continue + im=it.find("img");img=(im.get("data-src") or im.get("src","")) if im else "" + if img and'blank'in img: src=it.find("source") - if src: img=src.get("srcset","").split(",")[0].strip().split(" ")[0] + if src:img=src.get("srcset","").split(",")[0].strip().split(" ")[0] arts.append({"title":t,"link":lk,"img":img,"source":"vne"}) return arts - except Exception: - return [] - + except:return[] +def scrape_vne_article(url): + try: + soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description") + og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else "" + cd=soup.select_one("article.fck_detail");body=[] + if cd: + for ch in cd.children: + if not hasattr(ch,'name') or not ch.name:continue + if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None) + elif ch.name=="figure": + im=ch.find("img") + if im:s=im.get("data-src") or im.get("src","");body.append({"type":"img","src":s}) + elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)}) + return{"title":h1.get_text(strip=True) if h1 else "","summary":desc.get_text(strip=True) if desc else "","og_image":og_img,"body":body,"source":"vne","url":url} + except:return None +def _scrape_dantri_homepage(cat_filter=None): + try: + soup=_get("https://dantri.com.vn/");arts=[];seen=set() + for a in soup.find_all("a",href=True): + href=a.get("href","");title=a.get("title","") or a.get_text(strip=True) + if not title or len(title)<15 or"javascript:" in href:continue + if not href.startswith("http"):href="https://dantri.com.vn"+href + if href in seen or not href.endswith(".htm"):continue + if cat_filter and f"/{cat_filter}/" not in href:continue + img_tag=a.find("img") + if not img_tag and a.parent:img_tag=a.parent.find("img") + img_src="" + if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","") + if not img_src or "cdn" not in img_src:continue + proxied_img="/api/proxy/img?url="+quote(img_src,safe="") + seen.add(href);arts.append({"title":title,"link":href,"img":proxied_img,"source":"dantri"}) + if len(arts)>=15:break + return arts + except:return[] +def scrape_dantri_hot():return _scrape_dantri_homepage() +def scrape_dantri_congnghe(): + try: + soup=_get("https://dantri.com.vn/");arts=[];seen=set() + for a in soup.find_all("a",href=True): + href=a.get("href","");title=a.get("title","") or a.get_text(strip=True) + if not title or len(title)<15 or"javascript:" in href:continue + if not href.startswith("http"):href="https://dantri.com.vn"+href + if href in seen or not href.endswith(".htm"):continue + if"/cong-nghe/" not in href:continue + img_tag=a.find("img") + if not img_tag and a.parent:img_tag=a.parent.find("img") + img_src="" + if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","") + if img_src and "cdn" in img_src:img_src="/api/proxy/img?url="+quote(img_src,safe="") + else:img_src="" + seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"dantri"}) + if len(arts)>=15:break + return arts + except:return[] def scrape_genk_ai(): + """Scrape AI articles from genk.vn - readable in-app""" try: r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15) - if r.status_code!=200: return [] - r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml"); articles=[]; seen=set() + if r.status_code!=200:return[] + r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml") + articles=[];seen=set() for a in soup.find_all("a",href=True): href=a.get("href","") - if not href.endswith(".chn") or href=="/ai.chn": continue - if href.startswith("/"): href="https://genk.vn"+href - if href in seen or "genk.vn" not in href: continue + if not href.endswith(".chn") or href=="/ai.chn":continue + if href.startswith("/"):href="https://genk.vn"+href + if href in seen or "genk.vn" not in href:continue title=a.get("title","") or a.get_text(strip=True) - if not title or len(title)<20: continue - container=a.parent; img_src="" + if not title or len(title)<20:continue + container=a.parent;img_src="" for _ in range(6): - if container is None: break + if container is None:break for img in container.find_all("img"): s=img.get("data-src","") or img.get("src","") - if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s; break - if img_src: break; container=container.parent + if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: + img_src=s;break + if img_src:break + container=container.parent seen.add(href) if not img_src: try: - og_r=requests.get(href,headers=HEADERS,timeout=8); og_r.encoding="utf-8" - og_soup=BeautifulSoup(og_r.text,"lxml"); og_tag=og_soup.find("meta",property="og:image") - if og_tag: img_src=og_tag.get("content","") - except: pass + og_r=requests.get(href,headers=HEADERS,timeout=8);og_r.encoding="utf-8" + og_soup=BeautifulSoup(og_r.text,"lxml");og_tag=og_soup.find("meta",property="og:image") + if og_tag:img_src=og_tag.get("content","") + except:pass articles.append({"title":title,"link":href,"img":img_src,"source":"genk"}) - if len(articles)>=30: break + if len(articles)>=30:break return articles - except: return [] + except:return[] +def scrape_dantri_article(url): + try: + r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml") + for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose() + h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else "" + if og_img and "cdnphoto.dantri" in og_img:og_img="/api/proxy/img?url="+quote(og_img,safe="") + content=soup.select_one("main") or soup.select_one("div.singular-content") or soup.select_one("article");body=[] + if content: + for el in content.find_all(["p","h2","h3","figure","img"],recursive=True): + if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None) + elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None) + elif el.name in("figure","img"): + im=el if el.name=="img" else el.find("img") + if im: + s=im.get("data-src") or im.get("src","") + if s and"base64" not in s: + if "cdnphoto.dantri" in s:s="/api/proxy/img?url="+quote(s,safe="") + body.append({"type":"img","src":s}) + desc="";sapo=soup.select_one("h2.singular-sapo") or soup.select_one("h2[class*=sapo]") + if not sapo: + og_desc=soup.find("meta",property="og:description") + if og_desc:desc=og_desc.get("content","") + else:desc=sapo.get_text(strip=True) + return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url} + except:return None +def scrape_bbc_vietnamese(): + try: + r=requests.get("https://www.bbc.com/vietnamese",headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set() + for a in soup.select("a[href*='/vietnamese/']"): + href=a.get("href","") + if not href or href=="/vietnamese" or href.count("/")<3:continue + if not href.startswith("http"):href="https://www.bbc.com"+href + if href in seen:continue + title=a.get_text(strip=True) + if not title or len(title)<15 or any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue + img="";container=a.parent + for _ in range(3): + if container: + im=container.find("img") + if im:img=im.get("src","") or im.get("data-src","");break + container=container.parent + seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc"}) + if len(arts)>=15:break + return arts + except:return[] +def scrape_bbc_article(url): + try: + r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1") + og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else "" + body=[] + for p in soup.select("[data-component='text-block'] p, article p, main p"): + t=p.get_text(strip=True) + if t and len(t)>20:body.append({"type":"p","text":t}) + return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url} + except:return None + +def scrape_ttvh_worldcup(): + """Scrape all World Cup 2026 articles from The Thao Van Hoa RSS.""" + try: + r=requests.get("https://thethaovanhoa.vn/rss/world-cup-2026.rss",headers=HEADERS,timeout=15);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"xml");arts=[];seen=set() + for it in soup.find_all("item"): + title=(it.find("title").get_text(strip=True) if it.find("title") else "") + link=(it.find("link").get_text(strip=True) if it.find("link") else "") + desc=(it.find("description").get_text(" ",strip=True) if it.find("description") else "") + img="";ds=BeautifulSoup(desc,"lxml");im=ds.find("img") + if im:img=im.get("src","") or im.get("data-src","") + if title and link and link not in seen: + seen.add(link);arts.append({"title":title,"link":link,"img":img,"source":"ttvh"}) + if arts:return arts + except:pass + try: + soup=_get("https://thethaovanhoa.vn/world-cup-2026.htm");arts=[];seen=set() + for a in soup.find_all("a",href=True): + href=a.get("href","") + if not href.startswith("http"):href="https://thethaovanhoa.vn"+href + if href in seen or "thethaovanhoa.vn" not in href:continue + if not re.search(r"/[^/]+-\d{8,}\.htm",href):continue + title=a.get("title","") or a.get_text(" ",strip=True) + img=None;p=a + for _ in range(5): + if p is None:break + img=p.find("img") + if img:break + p=p.parent + img_src="" + if img: + img_src=img.get("data-src","") or img.get("src","") or img.get("data-original","") or img.get("data-thumb","") + if len(title)<15:title=img.get("alt","") or img.get("title","") or title + if not title or len(title)<15:continue + seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"ttvh"}) + if len(arts)>=24:break + return arts + except:return[] + +def scrape_ttvh_article(url): + try: + soup=_get(url);h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else "" + og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else "" + desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else "" + cd=soup.select_one(".detail-content") or soup.select_one(".content-detail") or soup.select_one("article") or soup.select_one("main") + body=[] + if cd: + for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True): + if el.name=="p": + t=el.get_text(strip=True) + if t and len(t)>20 and "Theo dõi" not in t:body.append({"type":"p","text":t}) + elif el.name in ("h2","h3"): + t=el.get_text(strip=True) + if t:body.append({"type":"heading","text":t}) + elif el.name in ("figure","img"): + im=el if el.name=="img" else el.find("img") + if im: + src=im.get("data-src") or im.get("src","") or im.get("data-original","") + if src and "base64" not in src:body.append({"type":"img","src":src}) + if not body and desc:body=[{"type":"p","text":desc}] + return {"title":h1.get_text(strip=True) if h1 else fallback_title,"summary":desc,"og_image":og_img,"body":body,"source":"ttvh","url":url} + except:return None + +VNE_CATS={"thoi-su":("https://vnexpress.net/thoi-su","Thời Sự"),"the-gioi":("https://vnexpress.net/the-gioi","Thế Giới"),"kinh-doanh":("https://vnexpress.net/kinh-doanh","Kinh Doanh"),"the-thao":("https://vnexpress.net/the-thao","Thể Thao"),"giai-tri":("https://vnexpress.net/giai-tri","Giải Trí"),"suc-khoe":("https://vnexpress.net/suc-khoe","Sức Khỏe"),"phap-luat":("https://vnexpress.net/phap-luat","Pháp Luật"),"giao-duc":("https://vnexpress.net/giao-duc","Giáo Dục"),"du-lich":("https://vnexpress.net/du-lich","Du Lịch"),"doi-song":("https://vnexpress.net/doi-song","Đời Sống")} @app.get("/api/homepage") def api_homepage(): def _f(): articles=[] with ThreadPoolExecutor(12) as ex: futs={ex.submit(scrape_vne,VNE_CATS[k][0]):VNE_CATS[k][1] for k in["thoi-su","the-gioi","kinh-doanh","the-thao","giai-tri","phap-luat","giao-duc","du-lich","doi-song"]} + futs[ex.submit(scrape_bbc_vietnamese)]="BBC" for f in as_completed(futs): try: - for a in f.result(): a["group"]=futs[f]; articles.append(a) - except: pass + for a in f.result():a["group"]=futs[f];articles.append(a) + except:pass return articles return JSONResponse(_cached("homepage",_f)) - @app.get("/api/category/{cat_id}") def api_category(cat_id:str): def _f(): - if cat_id=="cong-nghe": return scrape_genk_ai() - if cat_id in VNE_CATS: - arts=scrape_vne(VNE_CATS[cat_id][0]) - [a.update({"group":VNE_CATS[cat_id][1]}) for a in arts] - return arts - return [] + if cat_id=="bbc":return scrape_bbc_vietnamese() + if cat_id=="cong-nghe":return scrape_genk_ai() + if cat_id in VNE_CATS:arts=scrape_vne(VNE_CATS[cat_id][0]);[a.update({"group":VNE_CATS[cat_id][1]}) for a in arts];return arts + return[] return JSONResponse(_cached(f"cat_{cat_id}",_f)) - @app.get("/api/categories") def api_categories(): - cats=[{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}] - for k,(u,n) in VNE_CATS.items(): cats.append({"id":k,"name":n,"source":"vne"}) + cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"},{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}] + for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"}) return JSONResponse(cats) - -@app.get("/api/proxy/xlb") -def api_xlb(path: str = Query(default=""), limit: int = Query(default=20)): - # Try xemlaibongda.top first (fast timeout), fallback to bongdaplus.vn - videos = _do_xlb_scrape_xlb(path, limit) - if not videos: - videos = _do_xlb_scrape_bdp(limit) - if not videos: - return JSONResponse({"videos": [], "error": "No videos available"}) - return JSONResponse({"videos": videos}) - -def _do_xlb_scrape_xlb(path, limit): +@app.get("/api/dantri_hot") +def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot)) +@app.get("/api/genk_ai") +def api_genk_ai():return JSONResponse(_cached("genk_ai",scrape_genk_ai,ttl=_cache_ttl)) +@app.get("/api/worldcup2026") +def api_worldcup2026():return JSONResponse(_cached("ttvh_worldcup",scrape_ttvh_worldcup,ttl=_cache_ttl)) +def scrape_genk_article(url): try: - url = f"https://xemlaibongda.top/{path}" if path else "https://xemlaibongda.top/" - r = requests.get(url, headers=HEADERS, timeout=8) - if r.status_code != 200: return [] - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - videos, seen = [], set() - for a in soup.find_all("a", href=True): - href = a.get("href", "") - if "/video/" not in href and "/xem-lai/" not in href: continue - if not href.startswith("http"): href = "https://xemlaibongda.top" + href - clean = href.split("?")[0].split("#")[0] - if clean in seen: continue - seen.add(clean) - img_src = "" - img = a.find("img") or (a.parent.find("img") if a.parent else None) - if not img: - p = a.parent - for _ in range(5): - if p and p.find("img"): img = p.find("img"); break - p = p.parent if p else None - if img: - img_src = (img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", "")) - if img_src.startswith("//"): img_src = "https:" + img_src - elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src - title = a.find("h3") - if not title: title = a.find("h2") - if not title: title = a.find("strong") - t = title.get_text(strip=True) if title else "" - if not t: - slug = clean.split("/video/")[-1].rstrip("/") - t = slug.replace("-", " ").title() - videos.append({"title": t[:100], "link": clean, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean)}) - if len(videos) >= limit: break - return videos - except Exception: - return [] - -def _do_xlb_scrape_bdp(limit): - """Fallback: scrape bongdaplus.vn videos for the xlb endpoint.""" - try: - return scrape_bongdaplus_videos(limit) - except Exception: - return [] + r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml") + h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else "" + og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else "" + desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else "" + cd=soup.select_one(".knc-content");body=[] + if cd: + for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True): + if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None) + elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None) + elif el.name in("figure","img"): + im=el if el.name=="img" else el.find("img") + if im:s=im.get("data-src") or im.get("src","");(body.append({"type":"img","src":s}) if s and"base64" not in s else None) + return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"genk","url":url} + except:return None @app.get("/api/article") def api_article(url:str=Query(...)): + if"vnexpress.net" in url:data=scrape_vne_article(url) + elif"bbc.com" in url:data=scrape_bbc_article(url) + elif"dantri.com.vn" in url:data=scrape_dantri_article(url) + elif"genk.vn" in url:data=scrape_genk_article(url) + elif"thethaovanhoa.vn" in url:data=scrape_ttvh_article(url) + else:data=None + return JSONResponse(data if data else{"error":"not supported"}) +def _web_context(topic): + """Collect real web/news context for a topic.""" + bits=[] try: - r2 = requests.get(url, headers=HEADERS, timeout=10) - if r2.status_code == 200: - r2.encoding = "utf-8" - soup = BeautifulSoup(r2.text, "lxml") - og = soup.find("meta", property="og:image") - return JSONResponse({"og_image": og.get("content", "") if og else ""}) - except: pass - return JSONResponse({"og_image": ""}) - -@app.get("/api/storage_status") -def api_storage_status(): - return JSONResponse({"persistent":os.path.isdir("/data")}) - -@app.get("/api/hot_topics") -def api_hot_topics(): - return JSONResponse({"topics":[]}) - -@app.get("/", response_class=HTMLResponse) -async def root(): - return HTMLResponse("

VNEWS v17

VTV Digital CDN ssaimh · No shorts Dantri/SKDS · Homepage full content

") \ No newline at end of file + rss="https://news.google.com/rss/search?q="+quote(topic)+"&hl=vi&gl=VN&ceid=VN:vi" + r=requests.get(rss,headers=HEADERS,timeout=12);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"xml") + for it in soup.find_all("item")[:8]: + title=it.find("title").get_text(" ",strip=True) if it.find("title") else "" + src=it.find("source").get_text(" ",strip=True) if it.find("source") else "" + if title:bits.append((title+(" — "+src if src else ""))[:280]) + except:pass + if bits:return "\n".join(bits) + try: + r=requests.get("https://html.duckduckgo.com/html/?q="+quote(topic),headers=HEADERS,timeout=12);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"lxml") + for res in soup.select(".result")[:6]: + t=res.select_one(".result__title");sn=res.select_one(".result__snippet") + line=((t.get_text(" ",strip=True) if t else "")+" — "+(sn.get_text(" ",strip=True) if sn else "")).strip(" —") + if line:bits.append(line[:280]) + except:pass + return "\n".join(bits) + +def _jina_read(url): + try: + ju="https://r.jina.ai/http://"+url + r=requests.get(ju,headers=HEADERS,timeout=25);r.encoding="utf-8" + if r.status_code!=200 or not r.text:return None + lines=[x.rstrip() for x in r.text.splitlines()] + title="";img="";body=[];summary="" + for ln in lines[:40]: + if ln.startswith("Title:"):title=ln.replace("Title:","",1).strip() + elif ln.startswith("Image:"):img=ln.replace("Image:","",1).strip() + elif ln.startswith("Description:"):summary=ln.replace("Description:","",1).strip() + for ln in lines: + t=ln.strip() + if not t or t.startswith(("Title:","URL Source:","Published Time:","Markdown Content:","Image:","Description:")):continue + if len(t)>40:body.append({"type":"p","text":t}) + if not body and summary:body=[{"type":"p","text":summary}] + return {"title":title or url,"summary":summary,"og_image":img,"body":body[:80],"source":"jina","url":url} + except:return None + +def _scrape_generic_article(url): + try: + hdr={**HEADERS,"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"} + r=requests.get(url,headers=hdr,timeout=15);r.encoding="utf-8" + ct=r.headers.get("content-type","").lower() + if r.status_code>=400 or "text/html" not in ct: + jr=_jina_read(url) + if jr:return jr + soup=BeautifulSoup(r.text,"lxml") + for tag in soup.find_all(["script","style","nav","footer","aside","form"]):tag.decompose() + h1=soup.find("h1") + ogt=soup.find("meta",property="og:title");title=h1.get_text(strip=True) if h1 else (ogt.get("content","") if ogt else "") + ogd=soup.find("meta",property="og:description");desc=ogd.get("content","") if ogd else "" + ogi=soup.find("meta",property="og:image");img=ogi.get("content","") if ogi else "" + main=soup.find("article") or soup.find("main") or soup.body + body=[] + if main: + for el in main.find_all(["p","h2","h3","figure","img"],recursive=True): + if el.name=="p": + t=el.get_text(" ",strip=True) + if t and len(t)>35:body.append({"type":"p","text":t}) + elif el.name in ("h2","h3"): + t=el.get_text(" ",strip=True) + if t:body.append({"type":"heading","text":t}) + elif el.name in ("figure","img"): + im=el if el.name=="img" else el.find("img") + if im: + src=im.get("data-src") or im.get("src","") or im.get("data-original","") + if src and "base64" not in src:body.append({"type":"img","src":src}) + if not body: + jr=_jina_read(url) + if jr and jr.get("body"):return jr + if not body and desc:body=[{"type":"p","text":desc}] + return {"title":title or url,"summary":desc,"og_image":img,"body":body,"source":"generic","url":url} + except: + return _jina_read(url) + +def _article_by_url(url): + if "vnexpress.net" in url:return scrape_vne_article(url) + if "bbc.com" in url:return scrape_bbc_article(url) + if "dantri.com.vn" in url:return scrape_dantri_article(url) + if "genk.vn" in url:return scrape_genk_article(url) + if "thethaovanhoa.vn" in url:return scrape_ttvh_article(url) + return _scrape_generic_article(url) + +def _call_qwen(prompt, max_tokens=1800): + """Try Qwen2.5-VL via HF router; return None if unavailable.""" + try: + token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("VAISTUDIO") + if not token:return None + headers={"Authorization":"Bearer "+token,"Content-Type":"application/json"} + payload={"model":"Qwen/Qwen2.5-VL-7B-Instruct","messages":[{"role":"user","content":prompt}],"max_tokens":max_tokens,"temperature":0.7} + r=requests.post("https://router.huggingface.co/v1/chat/completions",headers=headers,json=payload,timeout=75) + if r.status_code>=300:return None + j=r.json();return j.get("choices",[{}])[0].get("message",{}).get("content") + except:return None + +def _collect_article_text(data, limit=28000): + title=(data or {}).get("title","");summary=(data or {}).get("summary","") + parts=[] + if summary:parts.append(summary) + for b in (data or {}).get("body",[]): + if b.get("type")=="heading":parts.append("## "+b.get("text","") ) + elif b.get("type")=="p":parts.append(b.get("text","") ) + text="\n".join([p.strip() for p in parts if p and p.strip()]) + return title,text[:limit] + +def _ai_rewrite_article(data,tone="tu-nhien"): + title,text=_collect_article_text(data) + prompt=("Bạn là biên tập viên báo điện tử tiếng Việt. Hãy viết lại bài dưới đây bằng ngôn ngữ tự nhiên, mạch lạc, không cắt khúc, không bỏ ý quan trọng. " + "Giữ đúng sự thật, không bịa, không thêm thông tin ngoài bài. Văn phong: "+tone+". " + "Đầu ra gồm: tiêu đề hấp dẫn, đoạn sapo 2-3 câu, các đoạn nội dung ngắn dễ đọc, và 3 gạch đầu dòng điểm chính.\n\n" + "TIÊU ĐỀ GỐC: "+title+"\n\nNỘI DUNG GỐC:\n"+text) + out=_call_qwen(prompt,2200) + if out and len(out)>300:return out.strip() + paras=[p.strip() for p in text.split("\n") if len(p.strip())>30] + body="\n\n".join(paras[:18]) + bullets="\n".join(["• "+p[:220]+("..." if len(p)>220 else "") for p in paras[:5]]) + return ("Bản tin AI viết lại: "+title+"\n\n"+ + (paras[0] if paras else "")+"\n\n"+body+"\n\nĐiểm chính:\n"+bullets).strip() + +def _image_for_topic(topic): + return "https://image.pollinations.ai/prompt/"+quote("editorial illustration, Vietnamese news, "+topic,safe="")+"?width=1024&height=576&nologo=true" + +def _topic_articles(topic,limit=5): + items=[];seen=set() + try: + rss="https://news.google.com/rss/search?q="+quote(topic)+"&hl=vi&gl=VN&ceid=VN:vi" + r=requests.get(rss,headers=HEADERS,timeout=12);r.encoding="utf-8" + soup=BeautifulSoup(r.text,"xml") + for it in soup.find_all("item")[:limit*3]: + title=it.find("title").get_text(" ",strip=True) if it.find("title") else "" + link=it.find("link").get_text(strip=True) if it.find("link") else "" + src=it.find("source").get_text(" ",strip=True) if it.find("source") else "" + if not title or not link or link in seen:continue + seen.add(link);items.append({"title":title,"link":link,"source":src}) + if len(items)>=limit:break + except:pass + return items + +def _topic_article_context(topic): + """Filter readable article sources by topic, then summarize actual article bodies.""" + raw_keys=[k.lower() for k in re.findall(r"[\wÀ-ỹ]+",topic) if len(k)>2] + stop={"trong","năm","the","and","của","cho","với","một","các","những","hiện","nay"} + keys=[k for k in raw_keys if k not in stop] + candidates=[];seen=set() + def add_items(items): + for a in items or []: + link=a.get("link","");title=a.get("title","") + if not link or link in seen:continue + seen.add(link);candidates.append(a) + try:add_items(scrape_genk_ai()) + except:pass + try:add_items(scrape_dantri_congnghe()) + except:pass + if not candidates: + try:items=_scrape_dantri_homepage();add_items(items) + except:pass + candidates=[a for a in candidates if any(k in a.get("title","").lower() for k in keys)] + if not candidates:candidates=[a for a in (items or []) if any(k in a.get("title","").lower() for k in keys)] + texts=[] + for a in candidates[:8]: + try: + data=_article_by_url(a["link"]) + t=data.get("title","") if data else "" + b="\n".join(x.get("text","") for x in (data or {}).get("body",[]) if x.get("type")=="p") + if t and b:texts.append(f"[{t}]\n{b[:1200]}") + except:pass + return "\n\n".join(texts) + +@app.get("/api/topic_post") +async def api_topic_post(request:Request): + try:data=await request.json() + except:data={} + topic=str(data.get("topic","")).strip() + if not topic:return JSONResponse({"error":"missing topic"},status_code=400) + context=_topic_article_context(topic)+"\n\n"+_web_context(topic) \ No newline at end of file