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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VNEWS - FastAPI backend with livescore from bongda.com.vn"""
|
| 2 |
+
import hashlib, re, time
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 5 |
+
from fastapi import FastAPI, Query
|
| 6 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 7 |
+
from fastapi.staticfiles import StaticFiles
|
| 8 |
+
from urllib.parse import unquote, quote
|
| 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 |
+
BASE_24H = "https://www.24h.com.vn"
|
| 17 |
+
SPACE_URL = "https://bep40-vnews.hf.space"
|
| 18 |
+
_cache = {}
|
| 19 |
+
_cache_ttl = 300
|
| 20 |
+
_cache_ttl_live = 60
|
| 21 |
+
TOP_LEAGUES = ["Ngoại Hạng Anh","Champions League","LaLiga","Serie A","Bundesliga","Ligue 1"]
|
| 22 |
+
def _cached(key, fn, ttl=None):
|
| 23 |
+
now=time.time();t=ttl or _cache_ttl
|
| 24 |
+
if key in _cache and now-_cache[key]["t"]<t:return _cache[key]["d"]
|
| 25 |
+
try:data=fn()
|
| 26 |
+
except:data=_cache.get(key,{}).get("d",[])
|
| 27 |
+
_cache[key]={"d":data,"t":now};return data
|
| 28 |
+
def _get(url,headers=None):
|
| 29 |
+
h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
|
| 30 |
+
return BeautifulSoup(r.text,"lxml")
|
| 31 |
+
LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
|
| 32 |
+
def fetch_bongda_api(endpoint):
|
| 33 |
+
try:
|
| 34 |
+
r=requests.get(f"https://bongda.com.vn{endpoint}",headers=BONGDA_HEADERS,timeout=10)
|
| 35 |
+
if r.status_code==200:
|
| 36 |
+
data=r.json()
|
| 37 |
+
if data.get("status")=="success":return data.get("html","")
|
| 38 |
+
return ""
|
| 39 |
+
except:return ""
|
| 40 |
+
|
| 41 |
+
def _parse_match_from_li(li, status_type="live"):
|
| 42 |
+
"""Parse a match from a li.match-detail element."""
|
| 43 |
+
match_div=li.select_one("div.match")
|
| 44 |
+
if not match_div:return None
|
| 45 |
+
home_el=match_div.select_one(".home-team .name")
|
| 46 |
+
away_el=match_div.select_one(".away-team .name")
|
| 47 |
+
if not home_el or not away_el:return None
|
| 48 |
+
status_el=match_div.select_one(".status a")
|
| 49 |
+
league_el=li.find_previous("strong")
|
| 50 |
+
time_el=match_div.select_one(".match-time")
|
| 51 |
+
home_logo=match_div.select_one(".home-team .logo img")
|
| 52 |
+
away_logo=match_div.select_one(".away-team .logo img")
|
| 53 |
+
event_id=""
|
| 54 |
+
if status_el:
|
| 55 |
+
href=status_el.get("href","")
|
| 56 |
+
m=re.search(r'/tran-dau/(\d+)/',href)
|
| 57 |
+
if m:event_id=m.group(1)
|
| 58 |
+
spans=status_el.find_all("span") if status_el else []
|
| 59 |
+
score="";minute=""
|
| 60 |
+
if len(spans)>=3:score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}"
|
| 61 |
+
if len(spans)>=4:minute=spans[3].get_text(strip=True)
|
| 62 |
+
if not score and status_el and status_el.select_one(".vs"):score="VS"
|
| 63 |
+
league=league_el.get_text(strip=True) if league_el else ""
|
| 64 |
+
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}
|
| 65 |
+
|
| 66 |
+
@app.get("/api/livescore/live")
|
| 67 |
+
def api_livescore_live():
|
| 68 |
+
html=_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)
|
| 69 |
+
return JSONResponse({"html":html})
|
| 70 |
+
@app.get("/api/livescore/incoming")
|
| 71 |
+
def api_livescore_incoming():
|
| 72 |
+
html=_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)
|
| 73 |
+
return JSONResponse({"html":html})
|
| 74 |
+
@app.get("/api/livescore/today")
|
| 75 |
+
def api_livescore_today():
|
| 76 |
+
today=datetime.now().strftime("%Y-%m-%d")
|
| 77 |
+
html=_cached("ls_today",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}"),ttl=_cache_ttl)
|
| 78 |
+
return JSONResponse({"html":html})
|
| 79 |
+
@app.get("/api/livescore/results")
|
| 80 |
+
def api_livescore_results():
|
| 81 |
+
today=datetime.now().strftime("%Y-%m-%d")
|
| 82 |
+
html=_cached("ls_results",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}&status=finished"),ttl=_cache_ttl)
|
| 83 |
+
return JSONResponse({"html":html})
|
| 84 |
+
@app.get("/api/livescore/standings/{league}")
|
| 85 |
+
def api_livescore_standings(league:str):
|
| 86 |
+
tid=LEAGUE_IDS.get(league,27110)
|
| 87 |
+
html=_cached(f"ls_bxh_{league}",lambda:fetch_bongda_api(f"/api/league-table/home?tournament_id={tid}&is_detail=True"),ttl=_cache_ttl)
|
| 88 |
+
return JSONResponse({"html":html})
|
| 89 |
+
@app.get("/api/livescore/date/{date}")
|
| 90 |
+
def api_livescore_date(date:str):
|
| 91 |
+
html=fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")
|
| 92 |
+
return JSONResponse({"html":html})
|
| 93 |
+
@app.get("/api/match/{event_id}/commentaries")
|
| 94 |
+
def api_match_commentaries(event_id:int):
|
| 95 |
+
html=fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")
|
| 96 |
+
return JSONResponse({"html":html})
|
| 97 |
+
@app.get("/api/match/{event_id}/stats")
|
| 98 |
+
def api_match_stats(event_id:int):
|
| 99 |
+
html=fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")
|
| 100 |
+
return JSONResponse({"html":html})
|
| 101 |
+
|
| 102 |
+
@app.get("/api/livescore/featured")
|
| 103 |
+
def api_livescore_featured():
|
| 104 |
+
"""Trận tâm điểm: ưu tiên giải lớn (NHA, CL...), tìm trong live > today > incoming."""
|
| 105 |
+
def _f():
|
| 106 |
+
sources=[("/api/fixtures/live","live"),("/api/fixtures/get-by-date?date="+datetime.now().strftime("%Y-%m-%d"),"today"),("/api/fixtures/incoming","upcoming")]
|
| 107 |
+
for endpoint, stype in sources:
|
| 108 |
+
html=fetch_bongda_api(endpoint)
|
| 109 |
+
if not html or len(html)<100:continue
|
| 110 |
+
soup=BeautifulSoup(html,"lxml")
|
| 111 |
+
# First pass: find match from TOP league
|
| 112 |
+
for li in soup.select("li.match-detail"):
|
| 113 |
+
match=_parse_match_from_li(li, stype)
|
| 114 |
+
if not match or not match["event_id"]:continue
|
| 115 |
+
if any(tl in match["league"] for tl in TOP_LEAGUES):
|
| 116 |
+
# For "today" source, only pick upcoming/live (not finished)
|
| 117 |
+
if stype=="today" and "KT" in match.get("minute",""):continue
|
| 118 |
+
return match
|
| 119 |
+
# Second pass: any match with event_id
|
| 120 |
+
for li in soup.select("li.match-detail"):
|
| 121 |
+
match=_parse_match_from_li(li, stype)
|
| 122 |
+
if match and match["event_id"]:
|
| 123 |
+
if stype=="today" and "KT" in match.get("minute",""):continue
|
| 124 |
+
return match
|
| 125 |
+
return None
|
| 126 |
+
return JSONResponse(_cached("ls_featured",_f,ttl=_cache_ttl_live))
|
| 127 |
+
|
| 128 |
+
# ===== NEWS SCRAPERS =====
|
| 129 |
+
def scrape_vne(cat_url):
|
| 130 |
+
try:
|
| 131 |
+
soup=_get(cat_url);arts=[]
|
| 132 |
+
for it in soup.select("article.item-news")[:15]:
|
| 133 |
+
a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a")
|
| 134 |
+
if not a:continue
|
| 135 |
+
t=a.get("title","") or a.get_text(strip=True);lk=a.get("href","")
|
| 136 |
+
if not t or not lk:continue
|
| 137 |
+
im=it.find("img");img=(im.get("data-src") or im.get("src","")) if im else ""
|
| 138 |
+
if img and'blank'in img:
|
| 139 |
+
src=it.find("source")
|
| 140 |
+
if src:img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
|
| 141 |
+
desc=it.select_one("p.description")
|
| 142 |
+
arts.append({"title":t,"link":lk,"img":img,"summary":(desc.get_text(strip=True)[:150] if desc else ""),"source":"vne"})
|
| 143 |
+
return arts
|
| 144 |
+
except:return[]
|
| 145 |
+
def scrape_vne_article(url):
|
| 146 |
+
try:
|
| 147 |
+
soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description")
|
| 148 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 149 |
+
cd=soup.select_one("article.fck_detail");body=[]
|
| 150 |
+
if cd:
|
| 151 |
+
for ch in cd.children:
|
| 152 |
+
if not hasattr(ch,'name') or not ch.name:continue
|
| 153 |
+
if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 154 |
+
elif ch.name=="figure":
|
| 155 |
+
im=ch.find("img")
|
| 156 |
+
if im:s=im.get("data-src") or im.get("src","");cap=ch.find("figcaption");(body.append({"type":"img","src":s,"alt":cap.get_text(strip=True) if cap else ""}) if s else None)
|
| 157 |
+
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 158 |
+
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}
|
| 159 |
+
except:return None
|
| 160 |
+
def scrape_dantri_hot():
|
| 161 |
+
try:
|
| 162 |
+
soup=_get("https://dantri.com.vn/tin-nong.htm");arts=[];seen=set()
|
| 163 |
+
for a in soup.find_all("a",href=True):
|
| 164 |
+
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 165 |
+
if not title or len(title)<15 or"javascript:" in href:continue
|
| 166 |
+
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 167 |
+
if href in seen or not href.endswith(".htm"):continue
|
| 168 |
+
if href=="https://dantri.com.vn/tin-nong.htm":continue
|
| 169 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":"","source":"dantri"})
|
| 170 |
+
if len(arts)>=12:break
|
| 171 |
+
def _og(art):
|
| 172 |
+
try:r2=requests.get(art["link"],headers=HEADERS,timeout=8);r2.encoding="utf-8";og=BeautifulSoup(r2.text,"lxml").find("meta",property="og:image");art["img"]=og.get("content","") if og else ""
|
| 173 |
+
except:pass
|
| 174 |
+
with ThreadPoolExecutor(4) as ex:list(ex.map(_og,arts[:10]))
|
| 175 |
+
return[a for a in arts if a["img"]][:10]
|
| 176 |
+
except:return[]
|
| 177 |
+
def scrape_dantri_article(url):
|
| 178 |
+
try:
|
| 179 |
+
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 180 |
+
for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose()
|
| 181 |
+
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 182 |
+
content=soup.select_one("div.singular-content") or soup.select_one("article")
|
| 183 |
+
body=[]
|
| 184 |
+
if content:
|
| 185 |
+
for el in content.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 186 |
+
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 187 |
+
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 188 |
+
elif el.name=="figure" or el.name=="img":
|
| 189 |
+
im=el if el.name=="img" else el.find("img")
|
| 190 |
+
if im:s=im.get("data-src") or im.get("src","");(body.append({"type":"img","src":s,"alt":im.get("alt","")}) if s and"base64" not in s else None)
|
| 191 |
+
desc="";sapo=soup.select_one("h2.singular-sapo")
|
| 192 |
+
if sapo:desc=sapo.get_text(strip=True)
|
| 193 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url}
|
| 194 |
+
except:return None
|
| 195 |
+
def scrape_bdp_videos():
|
| 196 |
+
try:
|
| 197 |
+
soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
|
| 198 |
+
for a in soup.find_all("a",href=True):
|
| 199 |
+
href=a.get("href","")
|
| 200 |
+
if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue
|
| 201 |
+
if not href.startswith("http"):href=BASE_BDP+href
|
| 202 |
+
if href in seen:continue
|
| 203 |
+
title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip()
|
| 204 |
+
if not title or len(title)<5:continue
|
| 205 |
+
img_tag=a.find("img") or(a.parent.find("img") if a.parent else None)
|
| 206 |
+
img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else ""
|
| 207 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 208 |
+
return arts[:20]
|
| 209 |
+
except:return[]
|
| 210 |
+
def scrape_24h_highlights():
|
| 211 |
+
try:
|
| 212 |
+
soup=_get(f"{BASE_24H}/video-highlight-c953.html");arts=[];seen=set()
|
| 213 |
+
for a in soup.find_all("a",href=True):
|
| 214 |
+
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 215 |
+
if not title or len(title)<15 or"javascript:" in href:continue
|
| 216 |
+
if not href.startswith("http"):href=BASE_24H+href
|
| 217 |
+
if href in seen or"video" not in href.lower() or href.endswith("-c953.html"):continue
|
| 218 |
+
seen.add(href)
|
| 219 |
+
img=a.find("img");img_src=""
|
| 220 |
+
if img:img_src=img.get("data-original") or img.get("data-src") or img.get("src","")
|
| 221 |
+
if img_src and"base64" in img_src:img_src=""
|
| 222 |
+
arts.append({"title":title,"link":href,"img":img_src,"source":"24h"})
|
| 223 |
+
def _og(art):
|
| 224 |
+
if art["img"]:return
|
| 225 |
+
try:r=requests.get(art["link"],headers=HEADERS,timeout=8);r.encoding="utf-8";og=BeautifulSoup(r.text,"lxml").find("meta",property="og:image");art["img"]=og.get("content","") if og else ""
|
| 226 |
+
except:pass
|
| 227 |
+
need=[a for a in arts if not a["img"]][:10]
|
| 228 |
+
if need:
|
| 229 |
+
with ThreadPoolExecutor(5) as ex:list(ex.map(_og,need))
|
| 230 |
+
return arts[:30]
|
| 231 |
+
except:return[]
|
| 232 |
+
def scrape_24h_shorts():
|
| 233 |
+
try:
|
| 234 |
+
r=requests.get(f"{BASE_24H}/video/video-tin-tuc-cvd769.html",headers=HEADERS,timeout=15);r.encoding="utf-8"
|
| 235 |
+
soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
|
| 236 |
+
for art in soup.find_all("article"):
|
| 237 |
+
a=art.find("a",href=True)
|
| 238 |
+
if not a:continue
|
| 239 |
+
href=a.get("href","")
|
| 240 |
+
if not href.startswith("http"):href=BASE_24H+href
|
| 241 |
+
if href in seen:continue
|
| 242 |
+
img_tag=art.find("img");title=(img_tag.get("alt","") if img_tag else "") or a.get("title","") or a.get_text(strip=True)
|
| 243 |
+
if not title or len(title)<10:continue
|
| 244 |
+
img_src=""
|
| 245 |
+
if img_tag:img_src=img_tag.get("data-original") or img_tag.get("data-src") or img_tag.get("src","")
|
| 246 |
+
if img_src and"base64" in img_src:img_src=""
|
| 247 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"24h-shorts"})
|
| 248 |
+
return arts[:20]
|
| 249 |
+
except:return[]
|
| 250 |
+
def scrape_bbc_vietnamese():
|
| 251 |
+
try:
|
| 252 |
+
bbc_h={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB,en;q=0.9"}
|
| 253 |
+
r=requests.get("https://www.bbc.com/vietnamese",headers=bbc_h,timeout=15);r.encoding="utf-8"
|
| 254 |
+
soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
|
| 255 |
+
for a in soup.select("a[href*='/vietnamese/']"):
|
| 256 |
+
href=a.get("href","")
|
| 257 |
+
if not href or href=="/vietnamese" or href.count("/")<3:continue
|
| 258 |
+
if not href.startswith("http"):href="https://www.bbc.com"+href
|
| 259 |
+
if href in seen:continue
|
| 260 |
+
title=a.get_text(strip=True)
|
| 261 |
+
if not title or len(title)<15:continue
|
| 262 |
+
if any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue
|
| 263 |
+
img="";container=a.parent
|
| 264 |
+
for _ in range(3):
|
| 265 |
+
if container:
|
| 266 |
+
im=container.find("img")
|
| 267 |
+
if im:img=im.get("src","") or im.get("data-src","");break
|
| 268 |
+
container=container.parent
|
| 269 |
+
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc","summary":""})
|
| 270 |
+
if len(arts)>=15:break
|
| 271 |
+
return arts
|
| 272 |
+
except:return[]
|
| 273 |
+
def scrape_bbc_article(url):
|
| 274 |
+
try:
|
| 275 |
+
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 276 |
+
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 277 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 278 |
+
body=[]
|
| 279 |
+
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 280 |
+
t=p.get_text(strip=True)
|
| 281 |
+
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 282 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 283 |
+
except:return None
|
| 284 |
+
def extract_video_url(article_url):
|
| 285 |
+
try:
|
| 286 |
+
r=requests.get(article_url,headers={**HEADERS,"Referer":"https://www.24h.com.vn/"},timeout=10);r.encoding="utf-8"
|
| 287 |
+
m3u8s=re.findall(r'(https?://cdn\.24h\.com\.vn/[^\s"\'\\<>]+\.m3u8)',r.text)
|
| 288 |
+
esc=[u.replace('\\//','/').replace('\\/','/') for u in re.findall(r'(https?:\\/\\/cdn\.24h\.com\.vn\\/[^\s"\'<>]+\.m3u8)',r.text)]
|
| 289 |
+
all_urls=list(dict.fromkeys(m3u8s+esc));primary=[u for u in all_urls if'_720p' not in u] or [u for u in all_urls if'_720p' in u]
|
| 290 |
+
if not primary:return None
|
| 291 |
+
soup=BeautifulSoup(r.text,"lxml");og=soup.find("meta",property="og:image");poster=og.get("content","") if og else ""
|
| 292 |
+
return{"src":primary[0],"poster":poster}
|
| 293 |
+
except:return None
|
| 294 |
+
def extract_bdp_video(url):
|
| 295 |
+
try:
|
| 296 |
+
m=re.search(r'-(\d{6,})\.html',url)
|
| 297 |
+
if not m:return None
|
| 298 |
+
r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8"
|
| 299 |
+
soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer")
|
| 300 |
+
if not video:return None
|
| 301 |
+
source=video.find("source")
|
| 302 |
+
return{"src":source.get("src","") if source else "","poster":video.get("poster","")}
|
| 303 |
+
except:return None
|
| 304 |
+
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"),"cong-nghe":("https://vnexpress.net/so-hoa","Công Nghệ"),"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")}
|
| 305 |
+
@app.get("/api/homepage")
|
| 306 |
+
def api_homepage():
|
| 307 |
+
def _f():
|
| 308 |
+
articles=[]
|
| 309 |
+
with ThreadPoolExecutor(6) as ex:
|
| 310 |
+
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"]}
|
| 311 |
+
futs[ex.submit(scrape_bbc_vietnamese)]="BBC"
|
| 312 |
+
for f in as_completed(futs):
|
| 313 |
+
try:
|
| 314 |
+
for a in f.result():a["group"]=futs[f];articles.append(a)
|
| 315 |
+
except:pass
|
| 316 |
+
return articles
|
| 317 |
+
return JSONResponse(_cached("homepage",_f))
|
| 318 |
+
@app.get("/api/category/{cat_id}")
|
| 319 |
+
def api_category(cat_id:str):
|
| 320 |
+
def _f():
|
| 321 |
+
if cat_id=="bbc":return scrape_bbc_vietnamese()
|
| 322 |
+
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
|
| 323 |
+
return[]
|
| 324 |
+
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 325 |
+
@app.get("/api/categories")
|
| 326 |
+
def api_categories():
|
| 327 |
+
cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"}]
|
| 328 |
+
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 329 |
+
return JSONResponse(cats)
|
| 330 |
+
@app.get("/api/highlights")
|
| 331 |
+
def api_highlights():return JSONResponse(_cached("highlights",scrape_24h_highlights))
|
| 332 |
+
@app.get("/api/shorts")
|
| 333 |
+
def api_shorts():return JSONResponse(_cached("shorts",scrape_24h_shorts))
|
| 334 |
+
@app.get("/api/dantri_hot")
|
| 335 |
+
def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot))
|
| 336 |
+
@app.get("/api/bdp_videos")
|
| 337 |
+
def api_bdp_videos():return JSONResponse(_cached("bdp_videos",scrape_bdp_videos))
|
| 338 |
+
@app.get("/api/video_url")
|
| 339 |
+
def api_video_url(url:str=Query(...)):
|
| 340 |
+
if"24h.com.vn" in url:v=extract_video_url(url)
|
| 341 |
+
elif"bongdaplus.vn" in url:v=extract_bdp_video(url)
|
| 342 |
+
else:v=None
|
| 343 |
+
return JSONResponse(v if v else{"error":"not found"})
|
| 344 |
+
@app.get("/api/article")
|
| 345 |
+
def api_article(url:str=Query(...)):
|
| 346 |
+
if"vnexpress.net" in url:data=scrape_vne_article(url)
|
| 347 |
+
elif"bbc.com" in url:data=scrape_bbc_article(url)
|
| 348 |
+
elif"dantri.com.vn" in url:data=scrape_dantri_article(url)
|
| 349 |
+
else:data=None
|
| 350 |
+
return JSONResponse(data if data else{"error":"not supported"})
|
| 351 |
+
@app.get("/v")
|
| 352 |
+
async def video_share(url:str=Query(default=""),title:str=Query(default="VNEWS Video"),img:str=Query(default=""),type:str=Query(default="highlights")):
|
| 353 |
+
og_image=unquote(img) if img else "https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
|
| 354 |
+
decoded_url=unquote(url);decoded_title=unquote(title)
|
| 355 |
+
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>'
|
| 356 |
+
return HTMLResponse(f'''<!DOCTYPE html><html><head><meta charset="utf-8"><title>{decoded_title}</title><meta property="og:title" content="{decoded_title}"><meta property="og:image" content="{og_image}"></head><body style="background:#111;color:#fff;text-align:center;padding:40px"><p>⏳</p>{redirect_script}</body></html>''')
|
| 357 |
+
@app.get("/s")
|
| 358 |
+
async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default="")):
|
| 359 |
+
og_image=unquote(img) if img else "https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
|
| 360 |
+
decoded_url=unquote(url)
|
| 361 |
+
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>'
|
| 362 |
+
return HTMLResponse(f'''<!DOCTYPE html><html><head><meta charset="utf-8"><title>{unquote(title)}</title><meta property="og:title" content="{unquote(title)}"><meta property="og:image" content="{og_image}"></head><body>{redirect_script}</body></html>''')
|
| 363 |
+
@app.get("/")
|
| 364 |
+
async def index():
|
| 365 |
+
with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
|
| 366 |
+
app.mount("/static",StaticFiles(directory="/app/static"),name="static")
|