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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube VTV shorts"""
|
| 2 |
+
import re, time, subprocess, json, os, threading
|
| 3 |
+
import html as html_lib
|
| 4 |
+
from datetime import datetime, timezone, timedelta
|
| 5 |
+
|
| 6 |
+
VN_TZ = timezone(timedelta(hours=7))
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
from fastapi import FastAPI, Query, Request
|
| 9 |
+
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response
|
| 10 |
+
from urllib.parse import quote
|
| 11 |
+
import requests
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
# ===== VTV CHANNELS API =====
|
| 17 |
+
from vtv_api import router as vtv_router
|
| 18 |
+
app.include_router(vtv_router)
|
| 19 |
+
|
| 20 |
+
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"}
|
| 21 |
+
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"}
|
| 22 |
+
BASE_BDP = "https://bongdaplus.vn"
|
| 23 |
+
_cache = {}
|
| 24 |
+
_cache_ttl = 300
|
| 25 |
+
_cache_ttl_live = 60
|
| 26 |
+
_cache_ttl_yt = 1800
|
| 27 |
+
|
| 28 |
+
# ===== VTV NAM BO SHORTS FALLBACK =====
|
| 29 |
+
SHORTS_FALLBACK = [
|
| 30 |
+
{"id":"nqlLH6chLRo","title":"Tin nóng VTV Nam Bộ | #shorts","channel":"vtvnambo"},
|
| 31 |
+
{"id":"E7Kq0v3hG6w","title":"VTV Nam Bộ - Tin tức miền Nam | #shorts","channel":"vtvnambo"},
|
| 32 |
+
{"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","channel":"baodantri7941"},
|
| 33 |
+
{"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","channel":"baodantri7941"},
|
| 34 |
+
{"id":"tvPewsc2ph4","title":"Tính năng ẩn trên iPhone giúp giảm mỏi mắt","channel":"baodantri7941"},
|
| 35 |
+
{"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","channel":"baodantri7941"},
|
| 36 |
+
{"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ù","channel":"baodantri7941"},
|
| 37 |
+
{"id":"Htzvwg6iOBM","title":"Xe điện Audi S6 Sportback e-tron có gì đặc biệt?","channel":"baodantri7941"},
|
| 38 |
+
{"id":"iMdFmWvYdlo","title":"Cô gái người Nga yêu thời trang và đất nước Việt Nam","channel":"baodantri7941"},
|
| 39 |
+
{"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","channel":"baodantri7941"},
|
| 40 |
+
{"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","channel":"baodantri7941"},
|
| 41 |
+
{"id":"VAfgNNgZDRs","title":"Khởi tố 4 đối tượng ném bom xăng vào nhà dân ở Đồng Nai","channel":"baodantri7941"},
|
| 42 |
+
{"id":"sBH_-zGh0Xw","title":"Vì sao Times New Roman vẫn nổi tiếng sau hàng chục năm?","channel":"baodantri7941"},
|
| 43 |
+
{"id":"woKn5f2bLHM","title":"Quảng Ninh ngập sâu diện rộng sau đợt mưa lớn","channel":"baodantri7941"},
|
| 44 |
+
{"id":"bcpgRoxbLPw","title":"Giông lốc quật bay mái tôn ở TP.HCM","channel":"baodantri7941"},
|
| 45 |
+
{"id":"ZIIC5osy544","title":"Bé trai Trung Quốc rơi từ tầng 11 vẫn sống sót kỳ diệu","channel":"baodantri7941"},
|
| 46 |
+
{"id":"uTMJ49NQpyc","title":"Sau lớp mascot 40kg Câu chuyện mưu sinh của người trẻ ở TPHCM","channel":"baodantri7941"},
|
| 47 |
+
{"id":"7Pd6vZ2Lz1M","title":"Hành động ấm lòng của người đàn ông tìm kiếm 5 học sinh tử vong ở sông Lô","channel":"baosuckhoedoisongboyte"},
|
| 48 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 49 |
+
{"id":"IUOprcJyYr4","title":"Phụ nữ táo bón có phải do lười ăn rau?","channel":"baosuckhoedoisongboyte"},
|
| 50 |
+
{"id":"YY8ojFNE-AU","title":"Quái xế tự quay clip nẹt pô đánh võng đăng TikTok bị xử lý","channel":"baosuckhoedoisongboyte"},
|
| 51 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 52 |
+
{"id":"FoxhFyz2skY","title":"Người đàn ông nước ngoài đập phá ô tô bẻ cần gạt nước ở Đà Nẵng","channel":"baosuckhoedoisongboyte"},
|
| 53 |
+
{"id":"R1oC_I8dFPU","title":"Thanh niên buông tay lái đứng trên xe máy khi đổ đèo ở Đắk Lắk","channel":"baosuckhoedoisongboyte"},
|
| 54 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 55 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 56 |
+
{"id":"pXWt0QbAzRQ","title":"Va chạm giao thông người phụ nữ lăng mạ tài xế ô tô","channel":"baosuckhoedoisongboyte"},
|
| 57 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 58 |
+
{"id":"AxhVTQutsuo","title":"Xuất tinh sớm và những hiểu lầm thường gặp","channel":"baosuckhoedoisongboyte"},
|
| 59 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 60 |
+
{"id":"IDt_S6q59Ro","title":"Chở bạn gái không đội mũ bảo hiểm thanh niên đấm CSGT","channel":"baosuckhoedoisongboyte"},
|
| 61 |
+
{"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","channel":"baosuckhoedoisongboyte"},
|
| 62 |
+
]
|
| 63 |
+
for _v in SHORTS_FALLBACK:
|
| 64 |
+
_v.setdefault("link", "https://www.youtube.com/watch?v="+_v["id"])
|
| 65 |
+
_v.setdefault("img", "https://i.ytimg.com/vi/"+_v["id"]+"/hqdefault.jpg")
|
| 66 |
+
_v.setdefault("source", "yt")
|
| 67 |
+
|
| 68 |
+
SHORT_STATS_FILE = "/data/short_stats.json" if os.path.isdir("/data") else "/app/short_stats.json"
|
| 69 |
+
_short_lock = threading.Lock()
|
| 70 |
+
def _load_short_db():
|
| 71 |
+
try:
|
| 72 |
+
if os.path.exists(SHORT_STATS_FILE):
|
| 73 |
+
with open(SHORT_STATS_FILE,"r",encoding="utf-8") as f: return json.load(f)
|
| 74 |
+
except: pass
|
| 75 |
+
return {}
|
| 76 |
+
def _save_short_db(db):
|
| 77 |
+
try:
|
| 78 |
+
os.makedirs(os.path.dirname(SHORT_STATS_FILE), exist_ok=True)
|
| 79 |
+
tmp = SHORT_STATS_FILE + ".tmp"
|
| 80 |
+
with open(tmp,"w",encoding="utf-8") as f: json.dump(db, f, ensure_ascii=False)
|
| 81 |
+
os.replace(tmp, SHORT_STATS_FILE)
|
| 82 |
+
except: pass
|
| 83 |
+
def _short_default(): return {"views":0,"likes":0,"shares":0,"comments":[]}
|
| 84 |
+
|
| 85 |
+
PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
|
| 86 |
+
LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
|
| 87 |
+
HL_LEAGUES = {
|
| 88 |
+
"premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴"},
|
| 89 |
+
"fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"},
|
| 90 |
+
"bundesliga":{"path":"duc/bundesliga","name":"Bundesliga","emoji":"🇩🇪"},
|
| 91 |
+
"serie-a":{"path":"italy/serie-a","name":"Serie A","emoji":"🇮🇹"},
|
| 92 |
+
"la-liga":{"path":"tay-ban-nha/la-liga","name":"La Liga","emoji":"🇪🇸"},
|
| 93 |
+
"champions-league":{"path":"cup-chau-au/uefa-champions-league","name":"Champions League","emoji":"⭐"},
|
| 94 |
+
"europa-league":{"path":"cup-chau-au/uefa-europa-league","name":"Europa League","emoji":"🟠"},
|
| 95 |
+
"world-cup":{"path":"the-gioi/world-cup","name":"World Cup 2026","emoji":"🌍"},
|
| 96 |
+
}
|
| 97 |
+
def _cached(key, fn, ttl=None):
|
| 98 |
+
now=time.time(); t=ttl or _cache_ttl
|
| 99 |
+
if key in _cache and now-_cache[key]["t"]<t: return _cache[key]["d"]
|
| 100 |
+
try: data=fn()
|
| 101 |
+
except: data=_cache.get(key,{}).get("d",[])
|
| 102 |
+
_cache[key]={"d":data,"t":now}; return data
|
| 103 |
+
def _get(url, headers=None):
|
| 104 |
+
h=headers or HEADERS; r=requests.get(url, headers=h, timeout=15); r.encoding="utf-8"
|
| 105 |
+
return BeautifulSoup(r.text,"lxml")
|
| 106 |
+
def fetch_bongda_api(endpoint):
|
| 107 |
+
try:
|
| 108 |
+
r=requests.get(f"https://bongda.com.vn{endpoint}", headers=BONGDA_HEADERS, timeout=10)
|
| 109 |
+
if r.status_code==200:
|
| 110 |
+
data=r.json()
|
| 111 |
+
if data.get("status")=="success": return data.get("html","")
|
| 112 |
+
return ""
|
| 113 |
+
except: return ""
|
| 114 |
+
|
| 115 |
+
def _parse_match_from_li(li, status_type="live"):
|
| 116 |
+
match_div=li.select_one("div.match")
|
| 117 |
+
if not match_div: return None
|
| 118 |
+
home_el=match_div.select_one(".home-team .name"); away_el=match_div.select_one(".away-team .name")
|
| 119 |
+
if not home_el or not away_el: return None
|
| 120 |
+
status_el=match_div.select_one(".status a"); league_el=li.find_previous("strong"); time_el=match_div.select_one(".match-time")
|
| 121 |
+
home_logo=match_div.select_one(".home-team .logo img"); away_logo=match_div.select_one(".away-team .logo img")
|
| 122 |
+
event_id=""
|
| 123 |
+
if status_el:
|
| 124 |
+
href=status_el.get("href",""); m=re.search(r'/tran-dau/(\d+)/',href)
|
| 125 |
+
if m: event_id=m.group(1)
|
| 126 |
+
spans=status_el.find_all("span") if status_el else []; score=""; minute=""
|
| 127 |
+
if len(spans)>=3: score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}"
|
| 128 |
+
if len(spans)>=4: minute=spans[3].get_text(strip=True)
|
| 129 |
+
if not score and status_el and status_el.select_one(".vs"): score="VS"
|
| 130 |
+
league=league_el.get_text(strip=True) if league_el else ""
|
| 131 |
+
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}
|
| 132 |
+
|
| 133 |
+
# ===== VIDEO PROXY =====
|
| 134 |
+
@app.get("/api/proxy/m3u8")
|
| 135 |
+
def proxy_m3u8(url: str = Query(...)):
|
| 136 |
+
try:
|
| 137 |
+
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 138 |
+
if r.status_code != 200: return Response(status_code=502, content="upstream error")
|
| 139 |
+
lines = r.text.strip().split('\n'); rewritten = []
|
| 140 |
+
for line in lines:
|
| 141 |
+
if line.startswith('#') or not line.strip(): rewritten.append(line)
|
| 142 |
+
else: rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe=""))
|
| 143 |
+
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"})
|
| 144 |
+
except: return Response(status_code=502, content="proxy error")
|
| 145 |
+
|
| 146 |
+
@app.get("/api/proxy/seg")
|
| 147 |
+
def proxy_segment(url: str = Query(...)):
|
| 148 |
+
try:
|
| 149 |
+
r = requests.get(url, headers=HEADERS, timeout=30)
|
| 150 |
+
if r.status_code != 200: return Response(status_code=502, content="upstream error")
|
| 151 |
+
data = r.content
|
| 152 |
+
if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47: data = data[188:]
|
| 153 |
+
return Response(content=data, media_type="video/mp2t", headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=3600"})
|
| 154 |
+
except: return Response(status_code=502, content="proxy error")
|
| 155 |
+
|
| 156 |
+
@app.get("/api/proxy/video")
|
| 157 |
+
def proxy_video(url: str = Query(...), request: Request = None):
|
| 158 |
+
try:
|
| 159 |
+
req_headers = dict(HEADERS)
|
| 160 |
+
if request and request.headers.get("range"): req_headers["Range"] = request.headers["range"]
|
| 161 |
+
r = requests.get(url, headers=req_headers, timeout=30, stream=True)
|
| 162 |
+
resp_headers = {"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes","Content-Type":r.headers.get("Content-Type","video/mp4")}
|
| 163 |
+
if "Content-Range" in r.headers: resp_headers["Content-Range"] = r.headers["Content-Range"]
|
| 164 |
+
if "Content-Length" in r.headers: resp_headers["Content-Length"] = r.headers["Content-Length"]
|
| 165 |
+
return StreamingResponse(r.iter_content(chunk_size=256*1024), status_code=r.status_code, headers=resp_headers)
|
| 166 |
+
except: return Response(status_code=502, content="proxy error")
|
| 167 |
+
|
| 168 |
+
@app.get("/api/proxy/img")
|
| 169 |
+
def proxy_img(url: str = Query(...)):
|
| 170 |
+
try:
|
| 171 |
+
r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10)
|
| 172 |
+
if r.status_code != 200: return Response(status_code=502)
|
| 173 |
+
ct = r.headers.get("Content-Type", "image/jpeg")
|
| 174 |
+
return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
|
| 175 |
+
except: return Response(status_code=502)
|
| 176 |
+
|
| 177 |
+
# ===== XEMLAIBONGDA HIGHLIGHTS =====
|
| 178 |
+
def _scrape_xemlaibongda_page(page_path, limit=20):
|
| 179 |
+
try:
|
| 180 |
+
url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
|
| 181 |
+
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 182 |
+
if r.status_code != 200: return []
|
| 183 |
+
r.encoding = "utf-8"; soup = BeautifulSoup(r.text, "lxml"); videos = []; seen = set()
|
| 184 |
+
selectors = ['a[href*="/video/"]','a[href*="/xem-lai/"]','.video-item a','.post-item a','.item a','article a']
|
| 185 |
+
links = []
|
| 186 |
+
for sel in selectors: links.extend(soup.select(sel))
|
| 187 |
+
for a in links:
|
| 188 |
+
href = a.get("href", "")
|
| 189 |
+
if not href: continue
|
| 190 |
+
is_video = "/video/" in href or "/xem-lai/" in href
|
| 191 |
+
if not is_video:
|
| 192 |
+
parent = a.parent
|
| 193 |
+
if not (parent and parent.find(class_=re.compile(r'vid|play|highlight'))): continue
|
| 194 |
+
if not href.startswith("http"): href = "https://xemlaibongda.top" + href
|
| 195 |
+
if href in seen: continue
|
| 196 |
+
seen.add(href)
|
| 197 |
+
img = a.find("img")
|
| 198 |
+
if not img and a.parent: img = a.parent.find("img")
|
| 199 |
+
if not img:
|
| 200 |
+
p = a.parent
|
| 201 |
+
for _ in range(3):
|
| 202 |
+
if p and p.find("img"): img = p.find("img"); break
|
| 203 |
+
p = p.parent if p else None
|
| 204 |
+
img_src = ""
|
| 205 |
+
if img:
|
| 206 |
+
img_src = img.get("data-src","") or img.get("src","") or img.get("data-lazy","") or img.get("data-original","")
|
| 207 |
+
if img_src.startswith("//"): img_src = "https:" + img_src
|
| 208 |
+
elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src
|
| 209 |
+
title = ""
|
| 210 |
+
for tag in ["h3","h2","h4",".title",".post-title",".entry-title",".video-title"]:
|
| 211 |
+
t = a.select_one(tag) if hasattr(a,'select_one') else None
|
| 212 |
+
if t: title = t.get_text(" ",strip=True); break
|
| 213 |
+
if not title: title = a.get("title","")
|
| 214 |
+
if not title: title = a.get("aria-label","")
|
| 215 |
+
if not title:
|
| 216 |
+
img_for_alt = a.find("img")
|
| 217 |
+
if img_for_alt: title = img_for_alt.get("alt","")
|
| 218 |
+
if not title:
|
| 219 |
+
slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
|
| 220 |
+
title = slug.replace("-"," ").replace("_"," ")
|
| 221 |
+
title = re.sub(r'\d{4}-\d{2}-\d{2}','',title).strip().title()
|
| 222 |
+
if not title or len(title) < 3: continue
|
| 223 |
+
videos.append({"title":title,"link":href,"img":img_src,"source":"xemlaibongda"})
|
| 224 |
+
if len(videos) >= limit: break
|
| 225 |
+
return videos
|
| 226 |
+
except: return []
|
| 227 |
+
|
| 228 |
+
def scrape_xemlaibongda(): return _scrape_xemlaibongda_page("", 20)
|
| 229 |
+
def scrape_highlights_by_league(league_key):
|
| 230 |
+
if league_key not in HL_LEAGUES: return []
|
| 231 |
+
return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20)
|
| 232 |
+
def scrape_all_league_highlights():
|
| 233 |
+
results = {}
|
| 234 |
+
def _fetch(key): return key, scrape_highlights_by_league(key)
|
| 235 |
+
with ThreadPoolExecutor(8) as ex:
|
| 236 |
+
futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
|
| 237 |
+
for f in as_completed(futs):
|
| 238 |
+
try:
|
| 239 |
+
key, vids = f.result()
|
| 240 |
+
if vids: results[key] = vids
|
| 241 |
+
except: pass
|
| 242 |
+
return results
|
| 243 |
+
|
| 244 |
+
def extract_xemlaibongda_video(url):
|
| 245 |
+
try:
|
| 246 |
+
r=requests.get(url, headers=HEADERS, timeout=15)
|
| 247 |
+
if r.status_code!=200: return None
|
| 248 |
+
r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml"); video=soup.find("video")
|
| 249 |
+
if video:
|
| 250 |
+
src=video.get("src",""); poster=video.get("poster","")
|
| 251 |
+
if not src:
|
| 252 |
+
source=video.find("source")
|
| 253 |
+
if source: src=source.get("src","")
|
| 254 |
+
if src: return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
|
| 255 |
+
m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
|
| 256 |
+
if m3u8s:
|
| 257 |
+
og=soup.find("meta",property="og:image"); poster=og.get("content","") if og else ""
|
| 258 |
+
return{"src":m3u8s[0],"poster":poster,"type":"hls"}
|
| 259 |
+
return None
|
| 260 |
+
except: return None
|
| 261 |
+
|
| 262 |
+
# ===== YOUTUBE SHORTS SCRAPING =====
|
| 263 |
+
def _yt_channel_shorts_requests(channel, count=15):
|
| 264 |
+
try:
|
| 265 |
+
url=f"https://www.youtube.com/@{channel}/shorts"
|
| 266 |
+
r=requests.get(url, headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"}, timeout=15)
|
| 267 |
+
if r.status_code!=200: return []
|
| 268 |
+
html=r.text; ids=[]; items=[]
|
| 269 |
+
for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
|
| 270 |
+
vid=m.group(1)
|
| 271 |
+
if vid in ids: continue
|
| 272 |
+
ids.append(vid)
|
| 273 |
+
snip=html[max(0,m.start()-900):m.start()+1600]
|
| 274 |
+
title=""
|
| 275 |
+
mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip)
|
| 276 |
+
if not mt: mt=re.search(r'"accessibilityText":"([^"]+)"',snip)
|
| 277 |
+
if mt: title=html_lib.unescape(mt.group(1)).replace('\n',' ').strip()
|
| 278 |
+
if not title: title="YouTube Short"
|
| 279 |
+
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})
|
| 280 |
+
if len(items)>=count: break
|
| 281 |
+
return items
|
| 282 |
+
except: return []
|
| 283 |
+
|
| 284 |
+
def scrape_shorts():
|
| 285 |
+
vids=[]
|
| 286 |
+
with ThreadPoolExecutor(3) as ex:
|
| 287 |
+
futs=[ex.submit(_yt_channel_shorts_requests,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]]
|
| 288 |
+
for f in as_completed(futs):
|
| 289 |
+
try:
|
| 290 |
+
r=f.result()
|
| 291 |
+
if r: vids.extend(r)
|
| 292 |
+
except: pass
|
| 293 |
+
merged=[]; seen=set()
|
| 294 |
+
for v in vids:
|
| 295 |
+
vid=v.get("id")
|
| 296 |
+
if not vid or vid in seen: continue
|
| 297 |
+
seen.add(vid); merged.append(v)
|
| 298 |
+
for v in SHORTS_FALLBACK:
|
| 299 |
+
vid=v.get("id")
|
| 300 |
+
if not vid or vid in seen: continue
|
| 301 |
+
seen.add(vid); merged.append(v)
|
| 302 |
+
return merged[:60]
|
| 303 |
+
|
| 304 |
+
# ===== VTV NAM BO & WC SHORTS - using yt-dlp =====
|
| 305 |
+
from yt_scraper import get_vtvnambo_shorts, get_wc_related_shorts
|
| 306 |
+
|
| 307 |
+
@app.get("/api/shorts/vtvnamo")
|
| 308 |
+
def api_shorts_vtvnamo(count: int = Query(default=50, le=100)):
|
| 309 |
+
items = get_vtvnambo_shorts(count)
|
| 310 |
+
if not items:
|
| 311 |
+
items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"]
|
| 312 |
+
nql = [v for v in items if v.get("id") == "nqlLH6chLRo"]
|
| 313 |
+
rest = [v for v in items if v.get("id") != "nqlLH6chLRo"]
|
| 314 |
+
items = nql + rest
|
| 315 |
+
return JSONResponse(items)
|
| 316 |
+
|
| 317 |
+
@app.get("/api/shorts/wc")
|
| 318 |
+
def api_shorts_wc(count: int = Query(default=50, le=100)):
|
| 319 |
+
items = get_wc_related_shorts(count)
|
| 320 |
+
if not items:
|
| 321 |
+
items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"]
|
| 322 |
+
nql = [v for v in items if v.get("id") == "nqlLH6chLRo"]
|
| 323 |
+
rest = [v for v in items if v.get("id") != "nqlLH6chLRo"]
|
| 324 |
+
items = nql + rest
|
| 325 |
+
return JSONResponse(items)
|
| 326 |
+
|
| 327 |
+
# ===== LIVESCORE =====
|
| 328 |
+
@app.get("/api/livescore/live")
|
| 329 |
+
def api_livescore_live(): return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
|
| 330 |
+
@app.get("/api/livescore/incoming")
|
| 331 |
+
def api_livescore_incoming(): return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)})
|
| 332 |
+
@app.get("/api/livescore/today")
|
| 333 |
+
def api_livescore_today():
|
| 334 |
+
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)})
|
| 335 |
+
@app.get("/api/livescore/results")
|
| 336 |
+
def api_livescore_results():
|
| 337 |
+
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)})
|
| 338 |
+
@app.get("/api/livescore/standings/{league}")
|
| 339 |
+
def api_livescore_standings(league:str):
|
| 340 |
+
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)})
|
| 341 |
+
@app.get("/api/livescore/date/{date}")
|
| 342 |
+
def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
|
| 343 |
+
@app.get("/api/match/{event_id}/commentaries")
|
| 344 |
+
def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
|
| 345 |
+
@app.get("/api/match/{event_id}/stats")
|
| 346 |
+
def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
|
| 347 |
+
|
| 348 |
+
from match_detail_v2 import fetch_match_detail, fetch_match_detail_by_url
|
| 349 |
+
|
| 350 |
+
@app.get("/api/match/{event_id}/detail")
|
| 351 |
+
def api_match_detail(event_id: int, url: str = Query(default="")):
|
| 352 |
+
try:
|
| 353 |
+
if url: data = fetch_match_detail_by_url(url)
|
| 354 |
+
else: data = fetch_match_detail(event_id)
|
| 355 |
+
return JSONResponse(data)
|
| 356 |
+
except Exception as e: return JSONResponse({"event_id": event_id, "found": False, "error": str(e)})
|
| 357 |
+
|
| 358 |
+
@app.get("/api/livescore/featured")
|
| 359 |
+
def api_livescore_featured():
|
| 360 |
+
def _f():
|
| 361 |
+
sources=[("/api/fixtures/live","live"),("/api/fixtures/get-by-date?date="+datetime.now(VN_TZ).strftime("%Y-%m-%d"),"today"),("/api/fixtures/incoming","upcoming")]
|
| 362 |
+
for endpoint, stype in sources:
|
| 363 |
+
html=fetch_bongda_api(endpoint)
|
| 364 |
+
if not html or len(html)<100:continue
|
| 365 |
+
soup=BeautifulSoup(html,"lxml");all_matches=[]
|
| 366 |
+
for li in soup.select("li.match-detail"):
|
| 367 |
+
match=_parse_match_from_li(li, stype)
|
| 368 |
+
if not match or not match["event_id"]:continue
|
| 369 |
+
if stype=="today" and "KT" in match.get("minute",""):continue
|
| 370 |
+
all_matches.append(match)
|
| 371 |
+
if not all_matches:continue
|
| 372 |
+
for pl in PRIORITY_LEAGUES:
|
| 373 |
+
for match in all_matches:
|
| 374 |
+
if pl in match["league"]:return match
|
| 375 |
+
return all_matches[0]
|
| 376 |
+
return None
|
| 377 |
+
return JSONResponse(_cached("ls_featured",_f,ttl=30))
|
| 378 |
+
|
| 379 |
+
@app.get("/api/shorts")
|
| 380 |
+
def api_shorts(channel: str = Query(default="")):
|
| 381 |
+
if channel == "vtvnambo": return api_shorts_vtvnamo()
|
| 382 |
+
if channel == "wc": return api_shorts_wc()
|
| 383 |
+
return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt))
|
| 384 |
+
|
| 385 |
+
@app.get("/api/short-stats")
|
| 386 |
+
def api_short_stats(ids:str=Query(default="")):
|
| 387 |
+
arr=[x for x in ids.split(",") if x]
|
| 388 |
+
with _short_lock:
|
| 389 |
+
db=_load_short_db();out={}
|
| 390 |
+
for vid in arr:
|
| 391 |
+
st=db.get(vid) or _short_default()
|
| 392 |
+
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]}
|
| 393 |
+
return JSONResponse({"stats":out})
|
| 394 |
+
|
| 395 |
+
@app.post("/api/short-action")
|
| 396 |
+
async def api_short_action(request:Request):
|
| 397 |
+
try: body=await request.json()
|
| 398 |
+
except: body={}
|
| 399 |
+
vid=str(body.get("id","")).strip(); action=str(body.get("action","")).strip(); txt=str(body.get("text","")).strip()
|
| 400 |
+
if not vid: return JSONResponse({"error":"missing id"},status_code=400)
|
| 401 |
+
with _short_lock:
|
| 402 |
+
db=_load_short_db(); st=db.get(vid) or _short_default()
|
| 403 |
+
if action=="view": st["views"]=int(st.get("views",0))+1
|
| 404 |
+
elif action=="like": st["likes"]=int(st.get("likes",0))+1
|
| 405 |
+
elif action=="share": st["shares"]=int(st.get("shares",0))+1
|
| 406 |
+
elif action=="comment" and txt:
|
| 407 |
+
comments=st.get("comments",[])
|
| 408 |
+
comments.insert(0,{"text":txt[:180],"ts":int(time.time())})
|
| 409 |
+
st["comments"]=comments[:80]
|
| 410 |
+
st["updated"]=int(time.time()); db[vid]=st; _save_short_db(db)
|
| 411 |
+
out={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]}
|
| 412 |
+
return JSONResponse({"stats":out})
|
| 413 |
+
|
| 414 |
+
@app.get("/api/highlights")
|
| 415 |
+
def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl))
|
| 416 |
+
@app.get("/api/highlights/leagues")
|
| 417 |
+
def api_highlights_leagues(): return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
|
| 418 |
+
@app.get("/api/highlights/{league}")
|
| 419 |
+
def api_highlights_league(league:str):
|
| 420 |
+
if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"})
|
| 421 |
+
return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
|
| 422 |
+
|
| 423 |
+
@app.get("/api/video_url")
|
| 424 |
+
def api_video_url(url:str=Query(...)):
|
| 425 |
+
if "youtube.com" in url or "youtu.be" in url:
|
| 426 |
+
m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
|
| 427 |
+
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"})
|
| 428 |
+
if "xemlaibongda.top" in url:
|
| 429 |
+
v=extract_xemlaibongda_video(url)
|
| 430 |
+
if v:
|
| 431 |
+
if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
|
| 432 |
+
return JSONResponse(v)
|
| 433 |
+
return JSONResponse({"error":"not found"})
|
| 434 |
+
|
| 435 |
+
@app.get("/api/bdp_videos")
|
| 436 |
+
def api_bdp_videos():
|
| 437 |
+
def _f():
|
| 438 |
+
try:
|
| 439 |
+
soup=_get(f"{BASE_BDP}/video"); arts=[]; seen=set()
|
| 440 |
+
for a in soup.find_all("a",href=True):
|
| 441 |
+
href=a.get("href","")
|
| 442 |
+
if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue
|
| 443 |
+
if not href.startswith("http"): href=BASE_BDP+href
|
| 444 |
+
if href in seen: continue
|
| 445 |
+
title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip()
|
| 446 |
+
if not title or len(title)<5: continue
|
| 447 |
+
img_tag=a.find("img") or(a.parent.find("img") if a.parent else None)
|
| 448 |
+
img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else ""
|
| 449 |
+
seen.add(href); arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 450 |
+
return arts[:20]
|
| 451 |
+
except: return []
|
| 452 |
+
return JSONResponse(_cached("bdp_videos",_f))
|
| 453 |
+
|
| 454 |
+
# ===== NEWS =====
|
| 455 |
+
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-trí","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")}
|
| 456 |
+
|
| 457 |
+
def scrape_vne(cat_url):
|
| 458 |
+
try:
|
| 459 |
+
soup=_get(cat_url); arts=[]
|
| 460 |
+
for it in soup.select("article.item-news")[:15]:
|
| 461 |
+
a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a")
|
| 462 |
+
if not a: continue
|
| 463 |
+
t=a.get("title","") or a.get_text(strip=True); lk=a.get("href","")
|
| 464 |
+
if not t or not lk: continue
|
| 465 |
+
im=it.find("img"); img=(im.get("data-src") or im.get("src","")) if im else ""
|
| 466 |
+
if img and 'blank' in img:
|
| 467 |
+
src=it.find("source")
|
| 468 |
+
if src: img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
|
| 469 |
+
arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
|
| 470 |
+
return arts
|
| 471 |
+
except: return []
|
| 472 |
+
|
| 473 |
+
def scrape_genk_ai():
|
| 474 |
+
try:
|
| 475 |
+
r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
|
| 476 |
+
if r.status_code!=200: return []
|
| 477 |
+
r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml"); articles=[]; seen=set()
|
| 478 |
+
for a in soup.find_all("a",href=True):
|
| 479 |
+
href=a.get("href","")
|
| 480 |
+
if not href.endswith(".chn") or href=="/ai.chn": continue
|
| 481 |
+
if href.startswith("/"): href="https://genk.vn"+href
|
| 482 |
+
if href in seen or "genk.vn" not in href: continue
|
| 483 |
+
title=a.get("title","") or a.get_text(strip=True)
|
| 484 |
+
if not title or len(title)<20: continue
|
| 485 |
+
container=a.parent; img_src=""
|
| 486 |
+
for _ in range(6):
|
| 487 |
+
if container is None: break
|
| 488 |
+
for img in container.find_all("img"):
|
| 489 |
+
s=img.get("data-src","") or img.get("src","")
|
| 490 |
+
if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s; break
|
| 491 |
+
if img_src: break
|
| 492 |
+
container=container.parent
|
| 493 |
+
seen.add(href)
|
| 494 |
+
if not img_src:
|
| 495 |
+
try:
|
| 496 |
+
og_r=requests.get(href,headers=HEADERS,timeout=8); og_r.encoding="utf-8"
|
| 497 |
+
og_soup=BeautifulSoup(og_r.text,"lxml"); og_tag=og_soup.find("meta",property="og:image")
|
| 498 |
+
if og_tag: img_src=og_tag.get("content","")
|
| 499 |
+
except: pass
|
| 500 |
+
articles.append({"title":title,"link":href,"img":img_src,"source":"genk"})
|
| 501 |
+
if len(articles)>=30: break
|
| 502 |
+
return articles
|
| 503 |
+
except: return []
|
| 504 |
+
|
| 505 |
+
@app.get("/api/homepage")
|
| 506 |
+
def api_homepage():
|
| 507 |
+
def _f():
|
| 508 |
+
articles=[]
|
| 509 |
+
with ThreadPoolExecutor(12) as ex:
|
| 510 |
+
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"]}
|
| 511 |
+
for f in as_completed(futs):
|
| 512 |
+
try:
|
| 513 |
+
for a in f.result(): a["group"]=futs[f]; articles.append(a)
|
| 514 |
+
except: pass
|
| 515 |
+
return articles
|
| 516 |
+
return JSONResponse(_cached("homepage",_f))
|
| 517 |
+
|
| 518 |
+
@app.get("/api/category/{cat_id}")
|
| 519 |
+
def api_category(cat_id:str):
|
| 520 |
+
def _f():
|
| 521 |
+
if cat_id=="cong-nghe": return scrape_genk_ai()
|
| 522 |
+
if cat_id in VNE_CATS:
|
| 523 |
+
arts=scrape_vne(VNE_CATS[cat_id][0])
|
| 524 |
+
[a.update({"group":VNE_CATS[cat_id][1]}) for a in arts]
|
| 525 |
+
return arts
|
| 526 |
+
return []
|
| 527 |
+
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 528 |
+
|
| 529 |
+
@app.get("/api/categories")
|
| 530 |
+
def api_categories():
|
| 531 |
+
cats=[{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}]
|
| 532 |
+
for k,(u,n) in VNE_CATS.items(): cats.append({"id":k,"name":n,"source":"vne"})
|
| 533 |
+
return JSONResponse(cats)
|
| 534 |
+
|
| 535 |
+
@app.get("/api/article")
|
| 536 |
+
def api_article(url:str=Query(...)):
|
| 537 |
+
return JSONResponse({"error":"not supported"})
|
| 538 |
+
|
| 539 |
+
@app.get("/api/storage_status")
|
| 540 |
+
def api_storage_status():
|
| 541 |
+
return JSONResponse({"persistent":os.path.isdir("/data")})
|
| 542 |
+
|
| 543 |
+
@app.get("/api/hot_topics")
|
| 544 |
+
def api_hot_topics():
|
| 545 |
+
return JSONResponse({"topics":[]})
|
| 546 |
+
|
| 547 |
+
@app.get("/", response_class=HTMLResponse)
|
| 548 |
+
async def root():
|
| 549 |
+
return HTMLResponse("<h1>VNEWS</h1><p>Running</p>")
|