bep40 commited on
Commit
45b83ff
·
verified ·
1 Parent(s): a922f94

Upload vtv_api.py with huggingface_hub

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