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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube FPT shorts"""
|
| 2 |
+
import hashlib, re, time, subprocess, json
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 5 |
+
from fastapi import FastAPI, Query, Request
|
| 6 |
+
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response
|
| 7 |
+
from fastapi.staticfiles import StaticFiles
|
| 8 |
+
from urllib.parse import unquote, quote, urlencode
|
| 9 |
+
import requests
|
| 10 |
+
from bs4 import BeautifulSoup
|
| 11 |
+
|
| 12 |
+
app = FastAPI()
|
| 13 |
+
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"}
|
| 14 |
+
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"}
|
| 15 |
+
BASE_BDP = "https://bongdaplus.vn"
|
| 16 |
+
SPACE_URL = "https://bep40-vnews.hf.space"
|
| 17 |
+
_cache = {}
|
| 18 |
+
_cache_ttl = 300
|
| 19 |
+
_cache_ttl_live = 60
|
| 20 |
+
_cache_ttl_yt = 1800
|
| 21 |
+
PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
|
| 22 |
+
LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
|
| 23 |
+
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-qualifiers","name":"World Cup 2026","emoji":"🌍"}}
|
| 24 |
+
def _cached(key, fn, ttl=None):
|
| 25 |
+
now=time.time();t=ttl or _cache_ttl
|
| 26 |
+
if key in _cache and now-_cache[key]["t"]<t:return _cache[key]["d"]
|
| 27 |
+
try:data=fn()
|
| 28 |
+
except:data=_cache.get(key,{}).get("d",[])
|
| 29 |
+
_cache[key]={"d":data,"t":now};return data
|
| 30 |
+
def _get(url,headers=None):
|
| 31 |
+
h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
|
| 32 |
+
return BeautifulSoup(r.text,"lxml")
|
| 33 |
+
def fetch_bongda_api(endpoint):
|
| 34 |
+
try:
|
| 35 |
+
r=requests.get(f"https://bongda.com.vn{endpoint}",headers=BONGDA_HEADERS,timeout=10)
|
| 36 |
+
if r.status_code==200:
|
| 37 |
+
data=r.json()
|
| 38 |
+
if data.get("status")=="success":return data.get("html","")
|
| 39 |
+
return ""
|
| 40 |
+
except:return ""
|
| 41 |
+
def _parse_match_from_li(li, status_type="live"):
|
| 42 |
+
match_div=li.select_one("div.match")
|
| 43 |
+
if not match_div:return None
|
| 44 |
+
home_el=match_div.select_one(".home-team .name");away_el=match_div.select_one(".away-team .name")
|
| 45 |
+
if not home_el or not away_el:return None
|
| 46 |
+
status_el=match_div.select_one(".status a");league_el=li.find_previous("strong");time_el=match_div.select_one(".match-time")
|
| 47 |
+
home_logo=match_div.select_one(".home-team .logo img");away_logo=match_div.select_one(".away-team .logo img")
|
| 48 |
+
event_id=""
|
| 49 |
+
if status_el:
|
| 50 |
+
href=status_el.get("href","");m=re.search(r'/tran-dau/(\d+)/',href)
|
| 51 |
+
if m:event_id=m.group(1)
|
| 52 |
+
spans=status_el.find_all("span") if status_el else [];score="";minute=""
|
| 53 |
+
if len(spans)>=3:score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}"
|
| 54 |
+
if len(spans)>=4:minute=spans[3].get_text(strip=True)
|
| 55 |
+
if not score and status_el and status_el.select_one(".vs"):score="VS"
|
| 56 |
+
league=league_el.get_text(strip=True) if league_el else ""
|
| 57 |
+
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}
|
| 58 |
+
@app.get("/api/proxy/m3u8")
|
| 59 |
+
def proxy_m3u8(url: str = Query(...)):
|
| 60 |
+
try:
|
| 61 |
+
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 62 |
+
if r.status_code != 200:return Response(status_code=502, content="upstream error")
|
| 63 |
+
lines = r.text.strip().split('\n');rewritten = []
|
| 64 |
+
for line in lines:
|
| 65 |
+
if line.startswith('#') or not line.strip():rewritten.append(line)
|
| 66 |
+
else:rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe=""))
|
| 67 |
+
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"})
|
| 68 |
+
except:return Response(status_code=502, content="proxy error")
|
| 69 |
+
@app.get("/api/proxy/seg")
|
| 70 |
+
def proxy_segment(url: str = Query(...)):
|
| 71 |
+
try:
|
| 72 |
+
r = requests.get(url, headers=HEADERS, timeout=30)
|
| 73 |
+
if r.status_code != 200:return Response(status_code=502, content="upstream error")
|
| 74 |
+
data = r.content
|
| 75 |
+
if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47:data = data[188:]
|
| 76 |
+
return Response(content=data,media_type="video/mp2t",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=3600"})
|
| 77 |
+
except:return Response(status_code=502, content="proxy error")
|
| 78 |
+
@app.get("/api/proxy/video")
|
| 79 |
+
def proxy_video(url: str = Query(...), request: Request = None):
|
| 80 |
+
try:
|
| 81 |
+
req_headers = dict(HEADERS)
|
| 82 |
+
if request and request.headers.get("range"):req_headers["Range"] = request.headers["range"]
|
| 83 |
+
r = requests.get(url, headers=req_headers, timeout=30, stream=True)
|
| 84 |
+
resp_headers = {"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes","Content-Type":r.headers.get("Content-Type","video/mp4")}
|
| 85 |
+
if "Content-Range" in r.headers:resp_headers["Content-Range"] = r.headers["Content-Range"]
|
| 86 |
+
if "Content-Length" in r.headers:resp_headers["Content-Length"] = r.headers["Content-Length"]
|
| 87 |
+
return StreamingResponse(r.iter_content(chunk_size=256*1024),status_code=r.status_code,headers=resp_headers)
|
| 88 |
+
except:return Response(status_code=502, content="proxy error")
|
| 89 |
+
@app.get("/api/proxy/img")
|
| 90 |
+
def proxy_img(url: str = Query(...)):
|
| 91 |
+
try:
|
| 92 |
+
r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10)
|
| 93 |
+
if r.status_code != 200:return Response(status_code=502)
|
| 94 |
+
ct = r.headers.get("Content-Type", "image/jpeg")
|
| 95 |
+
return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
|
| 96 |
+
except:return Response(status_code=502)
|
| 97 |
+
def _scrape_xemlaibongda_page(page_path, limit=20):
|
| 98 |
+
try:
|
| 99 |
+
url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
|
| 100 |
+
r=requests.get(url,headers=HEADERS,timeout=15)
|
| 101 |
+
if r.status_code!=200:return[]
|
| 102 |
+
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");videos=[];seen=set()
|
| 103 |
+
for a in soup.find_all("a",href=True):
|
| 104 |
+
href=a.get("href","")
|
| 105 |
+
if"/video/" not in href:continue
|
| 106 |
+
if not href.startswith("http"):href="https://xemlaibongda.top"+href
|
| 107 |
+
if href in seen:continue
|
| 108 |
+
seen.add(href);slug=href.split("/video/")[-1].rstrip("/")
|
| 109 |
+
title=slug.replace("-"," ").title()
|
| 110 |
+
title=re.sub(r'\d{4}\s*\d{2}\s*\d{2}$','',title).strip()
|
| 111 |
+
title=re.sub(r'\s+V\s+',' vs ',title);title=re.sub(r'\s+Vs\s+',' vs ',title)
|
| 112 |
+
img=a.find("img") or (a.parent.find("img") if a.parent else None)
|
| 113 |
+
img_src=""
|
| 114 |
+
if img:img_src=img.get("data-src","") or img.get("src","") or img.get("data-lazy","")
|
| 115 |
+
if not img_src:img_src=f"https://img.refooty.com/thumbnail/{slug}.webp"
|
| 116 |
+
videos.append({"title":title,"link":href,"img":img_src,"source":"xemlaibongda"})
|
| 117 |
+
if len(videos)>=limit:break
|
| 118 |
+
return videos
|
| 119 |
+
except:return[]
|
| 120 |
+
def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20)
|
| 121 |
+
def scrape_highlights_by_league(league_key):
|
| 122 |
+
if league_key not in HL_LEAGUES:return[]
|
| 123 |
+
return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20)
|
| 124 |
+
def scrape_all_league_highlights():
|
| 125 |
+
results = {}
|
| 126 |
+
def _fetch(key):return key, scrape_highlights_by_league(key)
|
| 127 |
+
with ThreadPoolExecutor(8) as ex:
|
| 128 |
+
futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
|
| 129 |
+
for f in as_completed(futs):
|
| 130 |
+
try:
|
| 131 |
+
key, vids = f.result()
|
| 132 |
+
if vids:results[key] = vids
|
| 133 |
+
except:pass
|
| 134 |
+
return results
|
| 135 |
+
def extract_xemlaibongda_video(url):
|
| 136 |
+
try:
|
| 137 |
+
r=requests.get(url,headers=HEADERS,timeout=15)
|
| 138 |
+
if r.status_code!=200:return None
|
| 139 |
+
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");video=soup.find("video")
|
| 140 |
+
if video:
|
| 141 |
+
src=video.get("src","");poster=video.get("poster","")
|
| 142 |
+
if not src:
|
| 143 |
+
source=video.find("source")
|
| 144 |
+
if source:src=source.get("src","")
|
| 145 |
+
if src:return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
|
| 146 |
+
m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
|
| 147 |
+
if m3u8s:
|
| 148 |
+
og=soup.find("meta",property="og:image");poster=og.get("content","") if og else ""
|
| 149 |
+
return{"src":m3u8s[0],"poster":poster,"type":"hls"}
|
| 150 |
+
return None
|
| 151 |
+
except:return None
|
| 152 |
+
def _yt_playlist(channel_path, count=15):
|
| 153 |
+
try:
|
| 154 |
+
result=subprocess.run(["yt-dlp","--flat-playlist","--dump-json","--no-download","--playlist-end",str(count),f"https://www.youtube.com/@fptbongdaofficial/{channel_path}"],capture_output=True,text=True,timeout=60)
|
| 155 |
+
videos=[]
|
| 156 |
+
for line in result.stdout.strip().split('\n'):
|
| 157 |
+
if not line:continue
|
| 158 |
+
try:
|
| 159 |
+
info=json.loads(line);vid=info.get("id","");title=info.get("title","")
|
| 160 |
+
if not vid or not title:continue
|
| 161 |
+
videos.append({"title":title,"link":f"https://www.youtube.com/watch?v={vid}","img":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","source":"fpt","id":vid})
|
| 162 |
+
except:pass
|
| 163 |
+
return videos
|
| 164 |
+
except:return[]
|
| 165 |
+
def scrape_fpt_shorts():return _yt_playlist("shorts", 15)
|
| 166 |
+
@app.get("/api/livescore/live")
|
| 167 |
+
def api_livescore_live():return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
|
| 168 |
+
@app.get("/api/livescore/incoming")
|
| 169 |
+
def api_livescore_incoming():return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)})
|
| 170 |
+
@app.get("/api/livescore/today")
|
| 171 |
+
def api_livescore_today():
|
| 172 |
+
today=datetime.now().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)})
|
| 173 |
+
@app.get("/api/livescore/results")
|
| 174 |
+
def api_livescore_results():
|
| 175 |
+
today=datetime.now().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)})
|
| 176 |
+
@app.get("/api/livescore/standings/{league}")
|
| 177 |
+
def api_livescore_standings(league:str):
|
| 178 |
+
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)})
|
| 179 |
+
@app.get("/api/livescore/date/{date}")
|
| 180 |
+
def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
|
| 181 |
+
@app.get("/api/match/{event_id}/commentaries")
|
| 182 |
+
def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
|
| 183 |
+
@app.get("/api/match/{event_id}/stats")
|
| 184 |
+
def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
|
| 185 |
+
@app.get("/api/livescore/featured")
|
| 186 |
+
def api_livescore_featured():
|
| 187 |
+
def _f():
|
| 188 |
+
sources=[("/api/fixtures/live","live"),("/api/fixtures/get-by-date?date="+datetime.now().strftime("%Y-%m-%d"),"today"),("/api/fixtures/incoming","upcoming")]
|
| 189 |
+
for endpoint, stype in sources:
|
| 190 |
+
html=fetch_bongda_api(endpoint)
|
| 191 |
+
if not html or len(html)<100:continue
|
| 192 |
+
soup=BeautifulSoup(html,"lxml");all_matches=[]
|
| 193 |
+
for li in soup.select("li.match-detail"):
|
| 194 |
+
match=_parse_match_from_li(li, stype)
|
| 195 |
+
if not match or not match["event_id"]:continue
|
| 196 |
+
if stype=="today" and "KT" in match.get("minute",""):continue
|
| 197 |
+
all_matches.append(match)
|
| 198 |
+
if not all_matches:continue
|
| 199 |
+
for pl in PRIORITY_LEAGUES:
|
| 200 |
+
for match in all_matches:
|
| 201 |
+
if pl in match["league"]:return match
|
| 202 |
+
return all_matches[0]
|
| 203 |
+
return None
|
| 204 |
+
return JSONResponse(_cached("ls_featured",_f,ttl=30))
|
| 205 |
+
@app.get("/api/shorts")
|
| 206 |
+
def api_shorts():return JSONResponse(_cached("fpt_shorts",scrape_fpt_shorts,ttl=_cache_ttl_yt))
|
| 207 |
+
@app.get("/api/highlights")
|
| 208 |
+
def api_highlights():return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl))
|
| 209 |
+
@app.get("/api/highlights/leagues")
|
| 210 |
+
def api_highlights_leagues():return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
|
| 211 |
+
@app.get("/api/highlights/{league}")
|
| 212 |
+
def api_highlights_league(league:str):
|
| 213 |
+
if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"})
|
| 214 |
+
return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
|
| 215 |
+
@app.get("/api/highlights_config")
|
| 216 |
+
def api_highlights_config():return JSONResponse(HL_LEAGUES)
|
| 217 |
+
@app.get("/api/video_url")
|
| 218 |
+
def api_video_url(url:str=Query(...)):
|
| 219 |
+
if "youtube.com" in url or "youtu.be" in url:
|
| 220 |
+
m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
|
| 221 |
+
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"})
|
| 222 |
+
if "xemlaibongda.top" in url:
|
| 223 |
+
v=extract_xemlaibongda_video(url)
|
| 224 |
+
if v:
|
| 225 |
+
if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
|
| 226 |
+
return JSONResponse(v)
|
| 227 |
+
if "bongdaplus.vn" in url:
|
| 228 |
+
try:
|
| 229 |
+
m=re.search(r'-(\d{6,})\.html',url)
|
| 230 |
+
if m:
|
| 231 |
+
r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8"
|
| 232 |
+
soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer")
|
| 233 |
+
if video:
|
| 234 |
+
source=video.find("source");src=source.get("src","") if source else "";poster=video.get("poster","")
|
| 235 |
+
if src:return JSONResponse({"src":"/api/proxy/video?url="+quote(src,safe=""),"poster":poster,"type":"video"})
|
| 236 |
+
except:pass
|
| 237 |
+
return JSONResponse({"error":"not found"})
|
| 238 |
+
@app.get("/api/bdp_videos")
|
| 239 |
+
def api_bdp_videos():
|
| 240 |
+
def _f():
|
| 241 |
+
try:
|
| 242 |
+
soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
|
| 243 |
+
for a in soup.find_all("a",href=True):
|
| 244 |
+
href=a.get("href","")
|
| 245 |
+
if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue
|
| 246 |
+
if not href.startswith("http"):href=BASE_BDP+href
|
| 247 |
+
if href in seen:continue
|
| 248 |
+
title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip()
|
| 249 |
+
if not title or len(title)<5:continue
|
| 250 |
+
img_tag=a.find("img") or(a.parent.find("img") if a.parent else None)
|
| 251 |
+
img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else ""
|
| 252 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 253 |
+
return arts[:20]
|
| 254 |
+
except:return[]
|
| 255 |
+
return JSONResponse(_cached("bdp_videos",_f))
|
| 256 |
+
def scrape_vne(cat_url):
|
| 257 |
+
try:
|
| 258 |
+
soup=_get(cat_url);arts=[]
|
| 259 |
+
for it in soup.select("article.item-news")[:15]:
|
| 260 |
+
a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a")
|
| 261 |
+
if not a:continue
|
| 262 |
+
t=a.get("title","") or a.get_text(strip=True);lk=a.get("href","")
|
| 263 |
+
if not t or not lk:continue
|
| 264 |
+
im=it.find("img");img=(im.get("data-src") or im.get("src","")) if im else ""
|
| 265 |
+
if img and'blank'in img:
|
| 266 |
+
src=it.find("source")
|
| 267 |
+
if src:img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
|
| 268 |
+
arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
|
| 269 |
+
return arts
|
| 270 |
+
except:return[]
|
| 271 |
+
def scrape_vne_article(url):
|
| 272 |
+
try:
|
| 273 |
+
soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description")
|
| 274 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 275 |
+
cd=soup.select_one("article.fck_detail");body=[]
|
| 276 |
+
if cd:
|
| 277 |
+
for ch in cd.children:
|
| 278 |
+
if not hasattr(ch,'name') or not ch.name:continue
|
| 279 |
+
if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 280 |
+
elif ch.name=="figure":
|
| 281 |
+
im=ch.find("img")
|
| 282 |
+
if im:s=im.get("data-src") or im.get("src","");body.append({"type":"img","src":s})
|
| 283 |
+
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 284 |
+
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}
|
| 285 |
+
except:return None
|
| 286 |
+
def _scrape_dantri_homepage(cat_filter=None):
|
| 287 |
+
try:
|
| 288 |
+
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
| 289 |
+
for a in soup.find_all("a",href=True):
|
| 290 |
+
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 291 |
+
if not title or len(title)<15 or"javascript:" in href:continue
|
| 292 |
+
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 293 |
+
if href in seen or not href.endswith(".htm"):continue
|
| 294 |
+
if cat_filter and f"/{cat_filter}/" not in href:continue
|
| 295 |
+
img_tag=a.find("img")
|
| 296 |
+
if not img_tag and a.parent:img_tag=a.parent.find("img")
|
| 297 |
+
img_src=""
|
| 298 |
+
if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
|
| 299 |
+
if not img_src or "cdn" not in img_src:continue
|
| 300 |
+
proxied_img="/api/proxy/img?url="+quote(img_src,safe="")
|
| 301 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":proxied_img,"source":"dantri"})
|
| 302 |
+
if len(arts)>=15:break
|
| 303 |
+
return arts
|
| 304 |
+
except:return[]
|
| 305 |
+
def scrape_dantri_hot():return _scrape_dantri_homepage()
|
| 306 |
+
def scrape_dantri_congnghe():
|
| 307 |
+
try:
|
| 308 |
+
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
| 309 |
+
for a in soup.find_all("a",href=True):
|
| 310 |
+
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 311 |
+
if not title or len(title)<15 or"javascript:" in href:continue
|
| 312 |
+
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 313 |
+
if href in seen or not href.endswith(".htm"):continue
|
| 314 |
+
if"/cong-nghe/" not in href:continue
|
| 315 |
+
img_tag=a.find("img")
|
| 316 |
+
if not img_tag and a.parent:img_tag=a.parent.find("img")
|
| 317 |
+
img_src=""
|
| 318 |
+
if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
|
| 319 |
+
if img_src and "cdn" in img_src:img_src="/api/proxy/img?url="+quote(img_src,safe="")
|
| 320 |
+
else:img_src=""
|
| 321 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"dantri"})
|
| 322 |
+
if len(arts)>=15:break
|
| 323 |
+
return arts
|
| 324 |
+
except:return[]
|
| 325 |
+
def scrape_genk_ai():
|
| 326 |
+
try:
|
| 327 |
+
r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
|
| 328 |
+
if r.status_code!=200:return[]
|
| 329 |
+
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 330 |
+
articles=[];seen=set()
|
| 331 |
+
for a in soup.find_all("a",href=True):
|
| 332 |
+
href=a.get("href","")
|
| 333 |
+
if not href.endswith(".chn") or href=="/ai.chn":continue
|
| 334 |
+
if href.startswith("/"):href="https://genk.vn"+href
|
| 335 |
+
if href in seen or "genk.vn" not in href:continue
|
| 336 |
+
title=a.get("title","") or a.get_text(strip=True)
|
| 337 |
+
if not title or len(title)<20:continue
|
| 338 |
+
container=a.parent;img_src=""
|
| 339 |
+
for _ in range(6):
|
| 340 |
+
if container is None:break
|
| 341 |
+
for img in container.find_all("img"):
|
| 342 |
+
s=img.get("data-src","") or img.get("src","")
|
| 343 |
+
if s and "mediacdn" in s and "avatar" not in s and "logo" not in s:
|
| 344 |
+
img_src=s;break
|
| 345 |
+
if img_src:break
|
| 346 |
+
container=container.parent
|
| 347 |
+
seen.add(href);articles.append({"title":title,"link":href,"img":img_src,"source":"genk"})
|
| 348 |
+
if len(articles)>=15:break
|
| 349 |
+
return articles
|
| 350 |
+
except:return[]
|
| 351 |
+
def scrape_dantri_article(url):
|
| 352 |
+
try:
|
| 353 |
+
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 354 |
+
for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose()
|
| 355 |
+
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 356 |
+
if og_img and "cdnphoto.dantri" in og_img:og_img="/api/proxy/img?url="+quote(og_img,safe="")
|
| 357 |
+
content=soup.select_one("main") or soup.select_one("div.singular-content") or soup.select_one("article");body=[]
|
| 358 |
+
if content:
|
| 359 |
+
for el in content.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 360 |
+
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 361 |
+
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 362 |
+
elif el.name in("figure","img"):
|
| 363 |
+
im=el if el.name=="img" else el.find("img")
|
| 364 |
+
if im:
|
| 365 |
+
s=im.get("data-src") or im.get("src","")
|
| 366 |
+
if s and"base64" not in s:
|
| 367 |
+
if "cdnphoto.dantri" in s:s="/api/proxy/img?url="+quote(s,safe="")
|
| 368 |
+
body.append({"type":"img","src":s})
|
| 369 |
+
desc="";sapo=soup.select_one("h2.singular-sapo") or soup.select_one("h2[class*=sapo]")
|
| 370 |
+
if not sapo:
|
| 371 |
+
og_desc=soup.find("meta",property="og:description")
|
| 372 |
+
if og_desc:desc=og_desc.get("content","")
|
| 373 |
+
else:desc=sapo.get_text(strip=True)
|
| 374 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url}
|
| 375 |
+
except:return None
|
| 376 |
+
def scrape_bbc_vietnamese():
|
| 377 |
+
try:
|
| 378 |
+
r=requests.get("https://www.bbc.com/vietnamese",headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 379 |
+
soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
|
| 380 |
+
for a in soup.select("a[href*='/vietnamese/']"):
|
| 381 |
+
href=a.get("href","")
|
| 382 |
+
if not href or href=="/vietnamese" or href.count("/")<3:continue
|
| 383 |
+
if not href.startswith("http"):href="https://www.bbc.com"+href
|
| 384 |
+
if href in seen:continue
|
| 385 |
+
title=a.get_text(strip=True)
|
| 386 |
+
if not title or len(title)<15 or any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue
|
| 387 |
+
img="";container=a.parent
|
| 388 |
+
for _ in range(3):
|
| 389 |
+
if container:
|
| 390 |
+
im=container.find("img")
|
| 391 |
+
if im:img=im.get("src","") or im.get("data-src","");break
|
| 392 |
+
container=container.parent
|
| 393 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc"})
|
| 394 |
+
if len(arts)>=15:break
|
| 395 |
+
return arts
|
| 396 |
+
except:return[]
|
| 397 |
+
def scrape_bbc_article(url):
|
| 398 |
+
try:
|
| 399 |
+
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 400 |
+
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 401 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 402 |
+
body=[]
|
| 403 |
+
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 404 |
+
t=p.get_text(strip=True)
|
| 405 |
+
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 406 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 407 |
+
except:return None
|
| 408 |
+
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")}
|
| 409 |
+
@app.get("/api/homepage")
|
| 410 |
+
def api_homepage():
|
| 411 |
+
def _f():
|
| 412 |
+
articles=[]
|
| 413 |
+
with ThreadPoolExecutor(12) as ex:
|
| 414 |
+
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"]}
|
| 415 |
+
futs[ex.submit(scrape_bbc_vietnamese)]="BBC"
|
| 416 |
+
futs[ex.submit(scrape_dantri_congnghe)]="Công Nghệ"
|
| 417 |
+
for f in as_completed(futs):
|
| 418 |
+
try:
|
| 419 |
+
for a in f.result():a["group"]=futs[f];articles.append(a)
|
| 420 |
+
except:pass
|
| 421 |
+
return articles
|
| 422 |
+
return JSONResponse(_cached("homepage",_f))
|
| 423 |
+
@app.get("/api/category/{cat_id}")
|
| 424 |
+
def api_category(cat_id:str):
|
| 425 |
+
def _f():
|
| 426 |
+
if cat_id=="bbc":return scrape_bbc_vietnamese()
|
| 427 |
+
if cat_id=="cong-nghe":return scrape_dantri_congnghe()
|
| 428 |
+
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
|
| 429 |
+
return[]
|
| 430 |
+
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 431 |
+
@app.get("/api/categories")
|
| 432 |
+
def api_categories():
|
| 433 |
+
cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"},{"id":"cong-nghe","name":"Công Nghệ","source":"dantri"}]
|
| 434 |
+
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 435 |
+
return JSONResponse(cats)
|
| 436 |
+
@app.get("/api/dantri_hot")
|
| 437 |
+
def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot))
|
| 438 |
+
@app.get("/api/genk_ai")
|
| 439 |
+
def api_genk_ai():return JSONResponse(_cached("genk_ai",scrape_genk_ai,ttl=_cache_ttl))
|
| 440 |
+
def scrape_genk_article(url):
|
| 441 |
+
try:
|
| 442 |
+
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 443 |
+
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 444 |
+
desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
|
| 445 |
+
cd=soup.select_one(".knc-content");body=[]
|
| 446 |
+
if cd:
|
| 447 |
+
for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 448 |
+
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 449 |
+
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 450 |
+
elif el.name in("figure","img"):
|
| 451 |
+
im=el if el.name=="img" else el.find("img")
|
| 452 |
+
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)
|
| 453 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"genk","url":url}
|
| 454 |
+
except:return None
|
| 455 |
+
@app.get("/api/article")
|
| 456 |
+
def api_article(url:str=Query(...)):
|
| 457 |
+
if"vnexpress.net" in url:data=scrape_vne_article(url)
|
| 458 |
+
elif"bbc.com" in url:data=scrape_bbc_article(url)
|
| 459 |
+
elif"dantri.com.vn" in url:data=scrape_dantri_article(url)
|
| 460 |
+
elif"genk.vn" in url:data=scrape_genk_article(url)
|
| 461 |
+
else:data=None
|
| 462 |
+
return JSONResponse(data if data else{"error":"not supported"})
|
| 463 |
+
@app.get("/v")
|
| 464 |
+
async def video_share(url:str=Query(default=""),title:str=Query(default="VNEWS Video"),img:str=Query(default=""),type:str=Query(default="highlights")):
|
| 465 |
+
decoded_url=unquote(url);decoded_title=unquote(title)
|
| 466 |
+
redirect_script=f'<script>localStorage.setItem("pending_video",JSON.stringify({{"url":"{decoded_url}","type":"{type}"}}));location.href="{SPACE_URL}";</script>' if decoded_url else f'<script>location.href="{SPACE_URL}";</script>'
|
| 467 |
+
return HTMLResponse(f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>{decoded_title}</title></head><body style="background:#111;color:#fff;text-align:center;padding:40px"><p>⏳</p>{redirect_script}</body></html>')
|
| 468 |
+
@app.get("/s")
|
| 469 |
+
async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default="")):
|
| 470 |
+
decoded_url=unquote(url)
|
| 471 |
+
redirect_script=f'<script>localStorage.setItem("pending_article","{decoded_url}");location.href="{SPACE_URL}";</script>' if decoded_url else f'<script>location.href="{SPACE_URL}";</script>'
|
| 472 |
+
return HTMLResponse(f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>{unquote(title)}</title></head><body>{redirect_script}</body></html>')
|
| 473 |
+
@app.get("/")
|
| 474 |
+
async def index():
|
| 475 |
+
with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
|
| 476 |
+
app.mount("/static",StaticFiles(directory="/app/static"),name="static")
|