Spaces:
Running
Running
Upload vtv_api.py
Browse files- vtv_api.py +102 -467
vtv_api.py
CHANGED
|
@@ -1,490 +1,125 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
| 3 |
-
Fetches stream URLs from xemtv.us PHP endpoints (primary)
|
| 4 |
-
Fallback: FPTPlay CDN → VTVGo CDN → xemtv.net (legacy)
|
| 5 |
-
EPG data scraped from https://vtv.vn/lich-phat-song.htm
|
| 6 |
-
"""
|
| 7 |
-
import re, time, threading
|
| 8 |
import requests
|
| 9 |
from fastapi import APIRouter, Query
|
| 10 |
-
from fastapi.responses import JSONResponse
|
| 11 |
-
from bs4 import BeautifulSoup
|
| 12 |
-
from datetime import datetime, timedelta, timezone
|
| 13 |
-
|
| 14 |
-
VN_TZ = timezone(timedelta(hours=7))
|
| 15 |
|
| 16 |
router = APIRouter()
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
"
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
"
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
CHANNEL_NAMES = {
|
| 54 |
-
"vtv1": "VTV1",
|
| 55 |
-
"vtv2": "VTV2",
|
| 56 |
-
"vtv3": "VTV3",
|
| 57 |
-
"vtv4": "VTV4",
|
| 58 |
-
"vtv5": "VTV5",
|
| 59 |
-
"vtv6": "VTV6",
|
| 60 |
-
"vtv7": "VTV7",
|
| 61 |
-
"vtv8": "VTV8",
|
| 62 |
-
"vtv9": "VTV9",
|
| 63 |
-
"vtv10": "VTV10",
|
| 64 |
-
"vtvprime": "VTVPrime",
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
# ===== FALLBACK 1: FPTPlay CDN (new URLs 2025-2026) =====
|
| 68 |
-
FPTPLAY_URLS = {
|
| 69 |
-
"vtv1": "https://live-a.fptplay53.net/live/media/vtv1/live247-hls-avc/index.m3u8",
|
| 70 |
-
"vtv2": "https://live-a.fptplay53.net/live/media/vtv2/live247-hls-avc/index.m3u8",
|
| 71 |
-
"vtv3": "https://live-a.fptplay53.net/live/media/vtv3/live247-hls-avc/index.m3u8",
|
| 72 |
-
"vtv4": "https://live-a.fptplay53.net/live/media/vtv4/live247-hls-avc/index.m3u8",
|
| 73 |
-
"vtv5": "https://live-a.fptplay53.net/live/media/vtv5/live247-hls-avc/index.m3u8",
|
| 74 |
-
"vtv6": "https://live-a.fptplay53.net/live/media/vtv6/live247-hls-avc/index.m3u8",
|
| 75 |
-
"vtv7": "https://live-a.fptplay53.net/live/media/vtv7/live247-hls-avc/index.m3u8",
|
| 76 |
-
"vtv8": "https://live-a.fptplay53.net/live/media/vtv8/live-hls-avc/index.m3u8",
|
| 77 |
-
"vtv9": "https://live-a.fptplay53.net/live/media/vtv9/live247-hls-avc/index.m3u8",
|
| 78 |
-
"vtv10": "https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/index.m3u8",
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
# ===== FALLBACK 2: VTVGo CDN =====
|
| 82 |
-
VTVGO_FAILOVER = {
|
| 83 |
-
"vtv1": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv1-manifest.m3u8",
|
| 84 |
-
"vtv2": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv2-manifest.m3u8",
|
| 85 |
-
"vtv3": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv3-manifest.m3u8",
|
| 86 |
-
"vtv4": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv4-manifest.m3u8",
|
| 87 |
-
"vtv5": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv5-manifest.m3u8",
|
| 88 |
-
"vtv6": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv6-manifest.m3u8",
|
| 89 |
-
"vtv7": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv7-manifest.m3u8",
|
| 90 |
-
"vtv8": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv8-manifest.m3u8",
|
| 91 |
-
"vtv9": "https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv9-manifest.m3u8",
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
_vtv_cache = {}
|
| 95 |
-
_vtv_lock = threading.Lock()
|
| 96 |
-
_CACHE_TTL = 180
|
| 97 |
-
|
| 98 |
-
def _cached(key):
|
| 99 |
-
with _vtv_lock:
|
| 100 |
-
if key in _vtv_cache and time.time() - _vtv_cache[key]['t'] < _CACHE_TTL:
|
| 101 |
-
return _vtv_cache[key]['d']
|
| 102 |
-
return None
|
| 103 |
-
|
| 104 |
-
def _set_cache(key, data):
|
| 105 |
-
with _vtv_lock:
|
| 106 |
-
_vtv_cache[key] = {'t': time.time(), 'd': data}
|
| 107 |
-
|
| 108 |
-
def extract_m3u8_from_html(html):
|
| 109 |
-
if not html:
|
| 110 |
-
return None
|
| 111 |
-
m = re.search(r"file\s*:\s*['\"]([^'\"]*\.m3u8[^'\"]*)['\"]", html, re.IGNORECASE)
|
| 112 |
-
if m:
|
| 113 |
-
url = m.group(1).strip()
|
| 114 |
-
if len(url) > 20:
|
| 115 |
-
return url
|
| 116 |
-
m = re.search(r"(https?://[^\s\"'<>\\]+\.m3u8[^\s\"'<>\\]*)", html, re.IGNORECASE)
|
| 117 |
-
if m:
|
| 118 |
-
url = m.group(1).strip()
|
| 119 |
-
if len(url) > 20:
|
| 120 |
-
return url
|
| 121 |
-
return None
|
| 122 |
-
|
| 123 |
-
def fetch_xemtv_us_stream(channel_id):
|
| 124 |
-
php_url = XEMTV_US_ENDPOINTS.get(channel_id)
|
| 125 |
-
if not php_url:
|
| 126 |
-
return None
|
| 127 |
try:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
| 136 |
return None
|
| 137 |
|
| 138 |
-
def
|
| 139 |
-
php_url = XEMTV_LEGACY_ENDPOINTS.get(channel_id)
|
| 140 |
-
if not php_url:
|
| 141 |
-
return None
|
| 142 |
try:
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
except:
|
| 150 |
-
pass
|
| 151 |
return None
|
| 152 |
|
| 153 |
-
def
|
| 154 |
-
url = FPTPLAY_URLS.get(channel_id)
|
| 155 |
-
if not url:
|
| 156 |
-
return None
|
| 157 |
try:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
r = requests.get(url, headers=headers, timeout=15, allow_redirects=True, verify=False)
|
| 164 |
-
if r.status_code == 200 and '#EXTM3U' in r.text[:200]:
|
| 165 |
-
return url
|
| 166 |
-
except:
|
| 167 |
-
pass
|
| 168 |
return None
|
| 169 |
|
| 170 |
-
def
|
| 171 |
-
url = VTVGO_FAILOVER.get(channel_id)
|
| 172 |
-
if not url:
|
| 173 |
-
return None
|
| 174 |
try:
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
except:
|
| 180 |
-
pass
|
| 181 |
return None
|
| 182 |
|
| 183 |
-
def
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
"
|
| 191 |
-
|
| 192 |
-
"
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
"
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
"https://live.fptplay53.net/fnxhd1/vtv7hd_vhls.smil/chunklist_b5000000.m3u8":
|
| 201 |
-
"https://live-a.fptplay53.net/live/media/vtv7/live247-hls-avc/index.m3u8",
|
| 202 |
-
"https://live.fptplay53.net/epzhd1/vtv8hd_vhls.smil/c.hunklist.m3u8":
|
| 203 |
-
"https://live-a.fptplay53.net/live/media/vtv8/live-hls-avc/index.m3u8",
|
| 204 |
-
"https://live.fptplay53.net/epzhd1/vtv8hd_vhls.smil/chunklist.m3u8":
|
| 205 |
-
"https://live-a.fptplay53.net/live/media/vtv8/live-hls-avc/index.m3u8",
|
| 206 |
-
"https://live.fptplay53.net/fnxhd1/vtv9hd_vhls.smil/chunklist.m3u8":
|
| 207 |
-
"https://live-a.fptplay53.net/live/media/vtv9/live247-hls-avc/index.m3u8",
|
| 208 |
-
"https://live.fptplay53.net/fnxhd1/vtv10hd_vhls.smil/chunklist.m3u8":
|
| 209 |
-
"https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/index.m3u8",
|
| 210 |
-
"https://live-a.fptplay53.net/live/media/VTV5HD/live_hls_avc/index.m3u8":
|
| 211 |
-
"https://live-a.fptplay53.net/live/media/vtv5/live247-hls-avc/index.m3u8",
|
| 212 |
-
}
|
| 213 |
-
return old_to_new.get(url, url)
|
| 214 |
-
|
| 215 |
-
def fetch_vtv_stream(channel_id):
|
| 216 |
-
"""Fetch VTV stream with multi-source fallback chain:
|
| 217 |
-
1. xemtv.us (primary - new domain, most reliable)
|
| 218 |
-
2. FPTPlay CDN (fallback - new URLs)
|
| 219 |
-
3. VTVGo CDN (fallback)
|
| 220 |
-
4. xemtv.net legacy (last resort)
|
| 221 |
-
"""
|
| 222 |
-
channel_id = channel_id.lower().strip()
|
| 223 |
-
name_map = {
|
| 224 |
-
'vtvct': 'vtv10', 'vtv-can-tho': 'vtv10', 'vtv can tho': 'vtv10',
|
| 225 |
-
'vtv_can_tho': 'vtv10', 'cantho': 'vtv10',
|
| 226 |
-
'vietnam_vtv1': 'vtv1', 'vietnam_vtv2': 'vtv2', 'vietnam_vtv3': 'vtv3',
|
| 227 |
-
'vietnam_vtv4': 'vtv4', 'vietnam_vtv5': 'vtv5', 'vietnam_vtv6': 'vtv6',
|
| 228 |
-
'vietnam_vtv7': 'vtv7', 'vietnam_vtv8': 'vtv8', 'vietnam_vtv9': 'vtv9',
|
| 229 |
-
}
|
| 230 |
-
channel_id = name_map.get(channel_id, channel_id)
|
| 231 |
-
cached = _cached(channel_id)
|
| 232 |
-
if cached is not None:
|
| 233 |
-
return cached
|
| 234 |
-
|
| 235 |
-
if channel_id == 'vtvprime':
|
| 236 |
-
url = fetch_xemtv_us_stream('vtvprime') or fetch_xemtv_legacy_stream('vtvprime')
|
| 237 |
-
if url:
|
| 238 |
-
url = normalize_fptplay_url(url)
|
| 239 |
-
_set_cache(channel_id, url)
|
| 240 |
-
return url
|
| 241 |
-
|
| 242 |
-
# Source 1: xemtv.us (primary)
|
| 243 |
-
url = fetch_xemtv_us_stream(channel_id)
|
| 244 |
-
if url:
|
| 245 |
-
url = normalize_fptplay_url(url)
|
| 246 |
-
_set_cache(channel_id, url)
|
| 247 |
-
return url
|
| 248 |
-
|
| 249 |
-
# Source 2: FPTPlay CDN
|
| 250 |
-
url = fetch_fptplay_stream(channel_id)
|
| 251 |
-
if url:
|
| 252 |
-
_set_cache(channel_id, url)
|
| 253 |
-
return url
|
| 254 |
-
|
| 255 |
-
# Source 3: VTVGo CDN
|
| 256 |
-
url = fetch_vtvgo_stream(channel_id)
|
| 257 |
-
if url:
|
| 258 |
-
_set_cache(channel_id, url)
|
| 259 |
-
return url
|
| 260 |
-
|
| 261 |
-
# Source 4: xemtv.net legacy (last resort)
|
| 262 |
-
url = fetch_xemtv_legacy_stream(channel_id)
|
| 263 |
-
if url:
|
| 264 |
-
url = normalize_fptplay_url(url)
|
| 265 |
-
_set_cache(channel_id, url)
|
| 266 |
-
return url
|
| 267 |
-
|
| 268 |
-
_set_cache(channel_id, None)
|
| 269 |
return None
|
| 270 |
|
| 271 |
-
@router.get("/api/vtv/streams")
|
| 272 |
-
def api_vtv_streams():
|
| 273 |
-
result = {}
|
| 274 |
-
for ch_id in CHANNEL_NAMES:
|
| 275 |
-
stream_url = fetch_vtv_stream(ch_id)
|
| 276 |
-
result[ch_id] = {"name": CHANNEL_NAMES[ch_id], "stream_url": stream_url, "status": "ok" if stream_url else "offline"}
|
| 277 |
-
return JSONResponse(result)
|
| 278 |
-
|
| 279 |
@router.get("/api/vtv/stream/{channel_id}")
|
| 280 |
def api_vtv_stream(channel_id: str):
|
| 281 |
-
|
| 282 |
-
if
|
| 283 |
-
return JSONResponse(
|
| 284 |
-
return JSONResponse({"error": "
|
| 285 |
-
|
| 286 |
-
@router.get("/api/
|
| 287 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
try:
|
| 289 |
-
|
| 290 |
-
if
|
| 291 |
-
|
| 292 |
-
elif "xemtv.net" in url:
|
| 293 |
-
headers["Referer"] = "https://hd.xemtv.net/"
|
| 294 |
-
r = requests.get(url, headers=headers, timeout=15, allow_redirects=True, verify=False)
|
| 295 |
-
if r.status_code != 200:
|
| 296 |
-
return Response(status_code=502, content="upstream error")
|
| 297 |
-
return Response(content=r.text.encode("utf-8"), media_type="text/html; charset=utf-8", headers={"Access-Control-Allow-Origin": "*"})
|
| 298 |
-
except:
|
| 299 |
-
return Response(status_code=502, content="proxy error")
|
| 300 |
-
|
| 301 |
-
@router.get("/api/proxy/m3u8/vtv")
|
| 302 |
-
def proxy_vtv_m3u8(url: str = Query(...)):
|
| 303 |
-
try:
|
| 304 |
-
headers = {"User-Agent": UA["User-Agent"], "Accept": "*/*"}
|
| 305 |
-
if "fptplay" in url:
|
| 306 |
-
headers["Referer"] = "https://fptplay.vn/"
|
| 307 |
-
headers["Origin"] = "https://fptplay.vn"
|
| 308 |
-
elif "xemtv" in url:
|
| 309 |
-
headers["Referer"] = "https://xemtv.us/"
|
| 310 |
-
elif "vtvgo" in url or "vtvdigital" in url:
|
| 311 |
-
headers["Referer"] = "https://vtvgo.vn/"
|
| 312 |
-
r = requests.get(url, headers=headers, timeout=15, allow_redirects=True, verify=False)
|
| 313 |
-
if r.status_code != 200:
|
| 314 |
-
return Response(status_code=502, content="upstream error")
|
| 315 |
-
content = r.text
|
| 316 |
-
lines = content.split('\n')
|
| 317 |
-
rewritten = []
|
| 318 |
-
base_url = url.rsplit('/', 1)[0] + '/'
|
| 319 |
for line in lines:
|
| 320 |
-
line
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
seg_url = line
|
| 325 |
-
if not seg_url.startswith('http'):
|
| 326 |
-
seg_url = base_url + seg_url
|
| 327 |
-
if seg_url.endswith('.m3u8'):
|
| 328 |
-
rewritten.append("/api/proxy/m3u8/vtv?url=" + requests.utils.quote(seg_url, safe=""))
|
| 329 |
-
else:
|
| 330 |
-
rewritten.append("/api/proxy/seg/vtv?url=" + requests.utils.quote(seg_url, safe=""))
|
| 331 |
-
return Response(content='\n'.join(rewritten).encode("utf-8"), media_type="application/vnd.apple.mpegurl", headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache"})
|
| 332 |
-
except Exception as e:
|
| 333 |
-
return Response(status_code=502, content="proxy error: " + str(e))
|
| 334 |
-
|
| 335 |
-
@router.get("/api/proxy/seg/vtv")
|
| 336 |
-
def proxy_vtv_segment(url: str = Query(...)):
|
| 337 |
-
try:
|
| 338 |
-
headers = {"User-Agent": UA["User-Agent"], "Accept": "*/*"}
|
| 339 |
-
if "fptplay" in url:
|
| 340 |
-
headers["Referer"] = "https://fptplay.vn/"
|
| 341 |
-
headers["Origin"] = "https://fptplay.vn"
|
| 342 |
-
r = requests.get(url, headers=headers, timeout=30, allow_redirects=True, verify=False)
|
| 343 |
-
if r.status_code != 200:
|
| 344 |
-
return Response(status_code=502, content="upstream error")
|
| 345 |
-
data = r.content
|
| 346 |
-
if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47:
|
| 347 |
-
data = data[188:]
|
| 348 |
-
return Response(content=data, media_type="video/mp2t", headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=3600"})
|
| 349 |
-
except:
|
| 350 |
-
return Response(status_code=502, content="proxy error")
|
| 351 |
-
|
| 352 |
-
_epg_cache = {}
|
| 353 |
-
_epg_cache_time = 0
|
| 354 |
-
_EPG_CACHE_TTL = 1800
|
| 355 |
-
|
| 356 |
-
VTV_CHANNEL_MAP = {
|
| 357 |
-
"vtv1": "vtv1", "vtv2": "vtv2", "vtv3": "vtv3", "vtv4": "vtv4",
|
| 358 |
-
"vtv5": "vtv5", "vtv5-tay-nam-bo": "vtv5", "vtv5-tay-nguyen": "vtv5",
|
| 359 |
-
"vtv7": "vtv7", "vtv8": "vtv8", "vtv6": "vtv6", "vtv9": "vtv9",
|
| 360 |
-
"vtv-can-tho": "vtv10",
|
| 361 |
-
}
|
| 362 |
-
|
| 363 |
-
def _fetch_epg_from_vtv():
|
| 364 |
-
global _epg_cache, _epg_cache_time
|
| 365 |
-
now_ts = time.time()
|
| 366 |
-
if _epg_cache and now_ts - _epg_cache_time < _EPG_CACHE_TTL:
|
| 367 |
-
return _epg_cache
|
| 368 |
-
epg_data = {}
|
| 369 |
-
try:
|
| 370 |
-
headers = {
|
| 371 |
-
"User-Agent": UA["User-Agent"], "Accept-Language": "vi-VN,vi;q=0.9",
|
| 372 |
-
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 373 |
-
"Referer": "https://vtv.vn/",
|
| 374 |
-
}
|
| 375 |
-
r = requests.get("https://vtv.vn/lich-phat-song.htm", headers=headers, timeout=20)
|
| 376 |
-
if r.status_code != 200:
|
| 377 |
-
return epg_data
|
| 378 |
-
r.encoding = "utf-8"
|
| 379 |
-
soup = BeautifulSoup(r.text, "lxml")
|
| 380 |
-
channel_order = []
|
| 381 |
-
list_channel = soup.find(class_=re.compile(r'list-channel'))
|
| 382 |
-
if list_channel:
|
| 383 |
-
for link in list_channel.find_all('a', href=re.compile(r'truyen-hinh-truc-tuyen/([^.]+)\.htm')):
|
| 384 |
-
ch_id = re.search(r'truyen-hinh-truc-tuyen/([^.]+)\.htm', link.get('href', ''))
|
| 385 |
-
if ch_id:
|
| 386 |
-
channel_order.append(ch_id.group(1))
|
| 387 |
-
if not channel_order:
|
| 388 |
-
for link in soup.find_all('a', href=re.compile(r'truyen-hinh-truc-tuyen/([^.]+)\.htm')):
|
| 389 |
-
ch_id = re.search(r'truyen-hinh-truc-tuyen/([^.]+)\.htm', link.get('href', ''))
|
| 390 |
-
if ch_id and ch_id.group(1) not in channel_order:
|
| 391 |
-
channel_order.append(ch_id.group(1))
|
| 392 |
-
prog_containers = soup.find_all('ul', class_=re.compile(r'\bprograms\b'))
|
| 393 |
-
for i, container in enumerate(prog_containers):
|
| 394 |
-
if i >= len(channel_order):
|
| 395 |
-
break
|
| 396 |
-
vtv_ch_id = channel_order[i]
|
| 397 |
-
our_ch_id = VTV_CHANNEL_MAP.get(vtv_ch_id, vtv_ch_id)
|
| 398 |
-
if our_ch_id not in epg_data:
|
| 399 |
-
epg_data[our_ch_id] = []
|
| 400 |
-
for li in container.find_all('li', class_=re.compile(r'\bprogram\b')):
|
| 401 |
-
time_span = li.find('span', class_=re.compile(r'\btime\b'))
|
| 402 |
-
title_span = li.find('span', class_=re.compile(r'\btitle\b'))
|
| 403 |
-
genre_a = li.find('a', class_=re.compile(r'\bgenre\b'))
|
| 404 |
-
time_str = time_span.get_text(strip=True) if time_span else ""
|
| 405 |
-
title = ""
|
| 406 |
-
if genre_a:
|
| 407 |
-
title = genre_a.get_text(strip=True)
|
| 408 |
-
if not title and title_span:
|
| 409 |
-
title = title_span.get_text(strip=True)
|
| 410 |
-
if not time_str or not title:
|
| 411 |
-
continue
|
| 412 |
-
start_dt = _parse_time(time_str)
|
| 413 |
-
if not start_dt:
|
| 414 |
-
continue
|
| 415 |
-
epg_data[our_ch_id].append({"time": time_str[:5], "title": title[:80], "start_dt": start_dt})
|
| 416 |
-
for ch_id in epg_data:
|
| 417 |
-
epg_data[ch_id].sort(key=lambda x: x.get("start_dt") or datetime.min)
|
| 418 |
-
seen = set()
|
| 419 |
-
unique = []
|
| 420 |
-
for p in epg_data[ch_id]:
|
| 421 |
-
key = (p["time"], p["title"])
|
| 422 |
-
if key not in seen:
|
| 423 |
-
seen.add(key)
|
| 424 |
-
unique.append(p)
|
| 425 |
-
epg_data[ch_id] = unique
|
| 426 |
-
except Exception as e:
|
| 427 |
-
print(f"EPG vtv.vn error: {e}")
|
| 428 |
-
_epg_cache = epg_data
|
| 429 |
-
_epg_cache_time = now_ts
|
| 430 |
-
return epg_data
|
| 431 |
-
|
| 432 |
-
def _parse_time(time_str):
|
| 433 |
-
if not time_str:
|
| 434 |
-
return None
|
| 435 |
-
time_str = time_str.strip().replace("h", ":").replace("H", ":")
|
| 436 |
-
m = re.search(r'(\d{1,2}):(\d{2})', time_str)
|
| 437 |
-
if m:
|
| 438 |
-
try:
|
| 439 |
-
hour, minute = int(m.group(1)), int(m.group(2))
|
| 440 |
-
now = datetime.now(VN_TZ)
|
| 441 |
-
return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
| 442 |
-
except:
|
| 443 |
-
pass
|
| 444 |
-
return None
|
| 445 |
-
|
| 446 |
-
def _get_epg_for_channel(channel_id):
|
| 447 |
-
epg_data = _fetch_epg_from_vtv()
|
| 448 |
-
programmes = epg_data.get(channel_id, [])
|
| 449 |
-
if not programmes:
|
| 450 |
-
return []
|
| 451 |
-
now = datetime.now(VN_TZ)
|
| 452 |
-
result = []
|
| 453 |
-
for i, p in enumerate(programmes):
|
| 454 |
-
start_dt = p.get("start_dt")
|
| 455 |
-
stop_dt = None
|
| 456 |
-
if i + 1 < len(programmes):
|
| 457 |
-
stop_dt = programmes[i + 1].get("start_dt")
|
| 458 |
-
is_now = False
|
| 459 |
-
if start_dt:
|
| 460 |
-
if stop_dt:
|
| 461 |
-
is_now = start_dt <= now < stop_dt
|
| 462 |
-
else:
|
| 463 |
-
is_now = start_dt <= now
|
| 464 |
-
end_time = ""
|
| 465 |
-
if stop_dt:
|
| 466 |
-
end_time = stop_dt.strftime("%H:%M")
|
| 467 |
-
result.append({"time": p["time"], "title": p["title"], "end_time": end_time, "now": is_now})
|
| 468 |
-
return result
|
| 469 |
-
|
| 470 |
-
@router.get("/api/vtv/epg/{channel_id}")
|
| 471 |
-
def api_vtv_epg(channel_id: str):
|
| 472 |
-
channel_id = channel_id.lower().strip()
|
| 473 |
-
if channel_id not in CHANNEL_NAMES:
|
| 474 |
-
return JSONResponse({"error": "channel not found"}, status_code=404)
|
| 475 |
-
programs = _get_epg_for_channel(channel_id)
|
| 476 |
-
return JSONResponse({
|
| 477 |
-
"channel": channel_id, "channel_name": CHANNEL_NAMES.get(channel_id, channel_id),
|
| 478 |
-
"date": datetime.now(VN_TZ).strftime("%Y-%m-%d"), "programs": programs,
|
| 479 |
-
})
|
| 480 |
-
|
| 481 |
-
@router.get("/api/vtv/epg")
|
| 482 |
-
def api_vtv_epg_refresh():
|
| 483 |
-
global _epg_cache, _epg_cache_time
|
| 484 |
-
_epg_cache = {}
|
| 485 |
-
_epg_cache_time = 0
|
| 486 |
-
epg_data = _fetch_epg_from_vtv()
|
| 487 |
-
return JSONResponse({
|
| 488 |
-
"status": "refreshed", "channels": len(epg_data),
|
| 489 |
-
"total_programmes": sum(len(v) for v in epg_data),
|
| 490 |
-
})
|
|
|
|
| 1 |
+
"""VTV API - xemtv.us primary, FPTPlay/VTVGo/canthotv fallback"""
|
| 2 |
+
import re, json, os, time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import requests
|
| 4 |
from fastapi import APIRouter, Query
|
| 5 |
+
from fastapi.responses import JSONResponse
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
router = APIRouter()
|
| 8 |
|
| 9 |
+
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"}
|
| 10 |
+
BASE = "https://xemtv.us"
|
| 11 |
+
_cache = {}
|
| 12 |
+
_cache_ttl = 300
|
| 13 |
+
|
| 14 |
+
CHANNELS = [
|
| 15 |
+
{"id":"vtv1","name":"VTV1","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/VTV1_logo.svg/120px-VTV1_logo.svg.png"},
|
| 16 |
+
{"id":"vtv2","name":"VTV2","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/VTV2_logo.svg/120px-VTV2_logo.svg.png"},
|
| 17 |
+
{"id":"vtv3","name":"VTV3","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/VTV3_logo.svg/120px-VTV3_logo.svg.png"},
|
| 18 |
+
{"id":"vtv4","name":"VTV4","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV4_logo.svg/120px-VTV4_logo.svg.png"},
|
| 19 |
+
{"id":"vtv5","name":"VTV5","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV5_logo.svg/120px-VTV5_logo.svg.png"},
|
| 20 |
+
{"id":"vtv6","name":"VTV6","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV6_logo.svg/120px-VTV6_logo.svg.png"},
|
| 21 |
+
{"id":"vtv7","name":"VTV7","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV7_logo.svg/120px-VTV7_logo.svg.png"},
|
| 22 |
+
{"id":"vtv8","name":"VTV8","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV8_logo.svg/120px-VTV8_logo.svg.png"},
|
| 23 |
+
{"id":"vtv9","name":"VTV9","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV9_logo.svg/120px-VTV9_logo.svg.png"},
|
| 24 |
+
{"id":"vtv10","name":"VTV10","logo":"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/VTV10_logo.svg/120px-VTV10_logo.svg.png"},
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
def _get(url, headers=None):
|
| 28 |
+
h = headers or HEADERS
|
| 29 |
+
r = requests.get(url, headers=h, timeout=15)
|
| 30 |
+
r.encoding = "utf-8"
|
| 31 |
+
return r.text
|
| 32 |
+
|
| 33 |
+
def _cached(key, fn, ttl=None):
|
| 34 |
+
now = time.time(); t = ttl or _cache_ttl
|
| 35 |
+
if key in _cache and now - _cache[key]["t"] < t: return _cache[key]["d"]
|
| 36 |
+
try: data = fn()
|
| 37 |
+
except: data = _cache.get(key, {}).get("d", None)
|
| 38 |
+
if data: _cache[key] = {"d": data, "t": now}
|
| 39 |
+
return data
|
| 40 |
+
|
| 41 |
+
def _xemtv_stream(channel_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
+
url = f"https://xemtv.us/{channel_id}.html"
|
| 44 |
+
html = _get(url)
|
| 45 |
+
m = re.search(r'(https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*)', html)
|
| 46 |
+
if m: return m.group(1)
|
| 47 |
+
m = re.search(r'src\s*=\s*["\']([^\s"\']+\.m3u8[^\s"\']*)["\']', html)
|
| 48 |
+
if m: return m.group(1)
|
| 49 |
+
m = re.search(r'file\s*:\s*["\']([^\s"\']+\.m3u8[^\s"\']*)["\']', html)
|
| 50 |
+
if m: return m.group(1)
|
| 51 |
+
except: pass
|
| 52 |
return None
|
| 53 |
|
| 54 |
+
def _fptplay_stream(channel_id):
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
+
fpt_map = {"vtv3":"vtv3","vtv6":"vtv6","vtv1":"vtv1","vtv2":"vtv2"}
|
| 57 |
+
cid = fpt_map.get(channel_id, channel_id)
|
| 58 |
+
url = f"https://fptplay.vn/xem-truyen-hinh/{cid}"
|
| 59 |
+
html = _get(url)
|
| 60 |
+
m = re.search(r'(https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*)', html)
|
| 61 |
+
if m: return m.group(1)
|
| 62 |
+
except: pass
|
|
|
|
| 63 |
return None
|
| 64 |
|
| 65 |
+
def _vtvgo_stream(channel_id):
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
+
url = f"https://vtvgo.vn/xem-truyen-hinh/{channel_id}.html"
|
| 68 |
+
html = _get(url)
|
| 69 |
+
m = re.search(r'(https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*)', html)
|
| 70 |
+
if m: return m.group(1)
|
| 71 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
return None
|
| 73 |
|
| 74 |
+
def _canthotv_stream(channel_id):
|
|
|
|
|
|
|
|
|
|
| 75 |
try:
|
| 76 |
+
url = f"https://canthotv.vn/xem-truyen-hinh/{channel_id}"
|
| 77 |
+
html = _get(url)
|
| 78 |
+
m = re.search(r'(https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*)', html)
|
| 79 |
+
if m: return m.group(1)
|
| 80 |
+
except: pass
|
|
|
|
| 81 |
return None
|
| 82 |
|
| 83 |
+
def get_stream(channel_id):
|
| 84 |
+
fn = lambda: _get_stream_uncached(channel_id)
|
| 85 |
+
return _cached(f"stream_{channel_id}", fn, ttl=60)
|
| 86 |
+
|
| 87 |
+
def _get_stream_uncached(channel_id):
|
| 88 |
+
sources = [
|
| 89 |
+
("xemtv.us", _xemtv_stream),
|
| 90 |
+
("FPTPlay", _fptplay_stream),
|
| 91 |
+
("VTVGo", _vtvgo_stream),
|
| 92 |
+
("CanThoTv", _canthotv_stream),
|
| 93 |
+
]
|
| 94 |
+
for name, fn in sources:
|
| 95 |
+
try:
|
| 96 |
+
url = fn(channel_id)
|
| 97 |
+
if url and ".m3u8" in url:
|
| 98 |
+
return {"url": url, "source": name, "channel_id": channel_id}
|
| 99 |
+
except: continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
return None
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
@router.get("/api/vtv/stream/{channel_id}")
|
| 103 |
def api_vtv_stream(channel_id: str):
|
| 104 |
+
stream = get_stream(channel_id)
|
| 105 |
+
if stream:
|
| 106 |
+
return JSONResponse(stream)
|
| 107 |
+
return JSONResponse({"error": "Stream not found"}, status_code=404)
|
| 108 |
+
|
| 109 |
+
@router.get("/api/vtv/channels")
|
| 110 |
+
def api_vtv_channels():
|
| 111 |
+
return JSONResponse(CHANNELS)
|
| 112 |
+
|
| 113 |
+
@router.get("/api/vtv/proxy")
|
| 114 |
+
def api_vtv_proxy(url: str = Query(...)):
|
| 115 |
+
from fastapi.responses import Response
|
| 116 |
+
from urllib.parse import quote
|
| 117 |
try:
|
| 118 |
+
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 119 |
+
if r.status_code != 200: return Response(status_code=502)
|
| 120 |
+
lines = r.text.strip().split('\n'); rewritten = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
for line in lines:
|
| 122 |
+
if line.startswith('#') or not line.strip(): rewritten.append(line)
|
| 123 |
+
else: rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe=""))
|
| 124 |
+
return Response(content='\n'.join(rewritten).encode('utf-8'), media_type="application/vnd.apple.mpegurl", headers={"Access-Control-Allow-Origin":"*"})
|
| 125 |
+
except: return Response(status_code=502)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|