-
Notifications
You must be signed in to change notification settings - Fork 19
/
movistar_epg.py
executable file
·1170 lines (935 loc) · 42.4 KB
/
movistar_epg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import aiofiles
import aiohttp
import asyncio
import logging
import os
import re
import sys
import time
import tomli
import ujson
import unicodedata
import urllib.parse
from aiohttp.client_exceptions import ClientOSError, ServerDisconnectedError
from aiohttp.resolver import AsyncResolver
from datetime import datetime, timedelta
from filelock import FileLock, Timeout
from glob import glob
from psutil import Process, boot_time
from sanic import Sanic, response
from sanic_prometheus import monitor
from sanic.exceptions import NotFound, ServiceUnavailable
if hasattr(asyncio, "exceptions"):
from asyncio.exceptions import CancelledError
else:
from asyncio import CancelledError
from mu7d import EXT, IPTV_DNS, UA, UA_U7D, URL_MVTV, VID_EXTS, WIN32, YEAR_SECONDS
from mu7d import find_free_port, get_iptv_ip, get_safe_filename, get_title_meta, glob_safe, ongoing_vods
from mu7d import launch, mu7d_config, remove, _version
app = Sanic("movistar_epg")
log = logging.getLogger("EPG")
@app.listener("before_server_start")
async def before_server_start(app, loop):
global _IPTV, _SESSION_CLOUD, _last_epg
app.config.FALLBACK_ERROR_FORMAT = "json"
app.config.KEEP_ALIVE_TIMEOUT = YEAR_SECONDS
if not WIN32:
[signal.signal(sig, cleanup_handler) for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)]
app.add_task(alive())
banner = f"Movistar U7D - EPG v{_version}"
log.info("-" * len(banner))
log.info(banner)
log.info("-" * len(banner))
if IPTV_BW_SOFT:
app.add_task(network_saturation())
log.info(f"Ignoring RECORDINGS_THREADS => BW: {IPTV_BW_SOFT}-{IPTV_BW_HARD} kbps / {IPTV_IFACE}")
_SESSION_CLOUD = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(
keepalive_timeout=YEAR_SECONDS,
resolver=AsyncResolver(nameservers=[IPTV_DNS]) if not WIN32 else None,
),
headers={"User-Agent": UA},
json_serialize=ujson.dumps,
)
await reload_epg()
if _CHANNELS and _EPGDATA:
if not _last_epg:
_last_epg = int(os.path.getmtime(GUIDE))
if RECORDINGS:
global _RECORDINGS
if not os.path.exists(RECORDINGS):
os.makedirs(RECORDINGS)
return
oldest_epg = 9999999999
for channel_id in _EPGDATA:
first = next(iter(_EPGDATA[channel_id]))
if first < oldest_epg:
oldest_epg = first
_indexed = set()
try:
async with aiofiles.open(recordings, encoding="utf8") as f:
recordingsdata = ujson.loads(await f.read())
int_recordings = {}
for str_channel in recordingsdata:
channel_id = int(str_channel)
int_recordings[channel_id] = {}
for str_timestamp in recordingsdata[str_channel]:
timestamp = int(str_timestamp)
recording = recordingsdata[str_channel][str_timestamp]
try:
filename = recording["filename"]
except KeyError:
log.warning(f'Dropping old style "{recording}" from recordings.json')
continue
if not does_recording_exist(filename):
if timestamp > oldest_epg:
log.warning(f'Archived recording "{filename}" not found on disk')
elif channel_id in _CLOUD and timestamp in _CLOUD[channel_id]:
log.warning(f'Archived Cloud Recording "{filename}" not found on disk')
else:
continue
else:
_indexed.add(os.path.join(RECORDINGS, filename + VID_EXT))
[os.utime(file, (-1, timestamp)) for file in get_recording_files(filename)]
int_recordings[channel_id][timestamp] = recording
_RECORDINGS = int_recordings
except (TypeError, ValueError) as ex:
log.error(f'Failed to parse "recordings.json". It will be reset!!!: {repr(ex)}')
except FileNotFoundError:
pass
for file in sorted(set(glob(f"{RECORDINGS}/**/*{VID_EXT}", recursive=True)) - _indexed):
timestamp = os.path.getmtime(file)
[os.utime(file, (-1, timestamp)) for file in get_recording_files(os.path.splitext(file)[0])]
await update_recordings(True)
app.add_task(update_epg_cron())
_IPTV = get_iptv_ip()
if not WIN32:
[signal.signal(sig, signal.SIG_DFL) for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)]
@app.listener("after_server_start")
async def after_server_start(app, loop):
if _last_epg and RECORDINGS:
global _t_timers
uptime = int(datetime.now().timestamp() - boot_time())
if not _t_timers and int(datetime.now().replace(minute=0, second=0).timestamp()) <= _last_epg:
delay = max(10, 180 - uptime)
if delay > 10:
log.info(f"Waiting {delay}s to check recording timers since the system just booted...")
_t_timers = app.add_task(timers_check(delay))
elif not _t_timers:
log.warning("Delaying timers_check until the EPG is updated...")
log.info(f"Manual timers check => {U7D_URL}/timers_check")
@app.listener("before_server_stop")
def before_server_stop(app=None, loop=None):
[task.cancel() for task in asyncio.all_tasks()]
async def alive():
async with aiohttp.ClientSession(headers={"User-Agent": UA_U7D}) as session:
for i in range(10):
try:
await session.get("https://openwrt.marcet.info/u7d/alive")
break
except Exception:
await asyncio.sleep(6)
async def cancel_app():
await asyncio.sleep(1)
if not WIN32:
os.kill(U7D_PARENT, signal.SIGTERM)
else:
app.stop()
def check_task(task):
if WIN32 and task.result() not in win32_normal_retcodes:
log.debug(f"Check task: [{task}]:[{task.result()}] Exiting!!!")
Process().terminate()
def cleanup_handler(signum, frame):
before_server_stop()
asyncio.get_event_loop().stop()
def does_recording_exist(filename):
return bool(
[
file
for file in glob_safe(os.path.join(RECORDINGS, f"{filename}.*"))
if os.path.splitext(file)[1] in VID_EXTS
]
)
def get_channel_dir(channel_id):
return "%03d. %s" % (_CHANNELS[channel_id]["number"], _CHANNELS[channel_id]["name"])
def get_epg(channel_id, program_id, cloud=False):
guide = _CLOUD if cloud else _EPGDATA
if channel_id not in guide:
log.error(f"{channel_id=} not found")
return
for timestamp in sorted(guide[channel_id]):
_epg = guide[channel_id][timestamp]
if program_id == _epg["pid"]:
return _epg, timestamp
log.error(f"{channel_id=} {program_id=} not found")
def get_program_id(channel_id, url=None, cloud=False):
if not url:
start = int(time.time())
elif len(url) == 10:
start = int(url)
elif not url.isdigit():
start = int(flussonic_regex.match(url).groups()[0])
elif len(url) == 12:
start = int(datetime.strptime(url, "%Y%m%d%H%M").timestamp())
elif len(url) == 14:
start = int(datetime.strptime(url, "%Y%m%d%H%M%S").timestamp())
else:
return
channel = _CHANNELS[channel_id]["name"]
last_timestamp = new_start = 0
if not cloud:
if start not in _EPGDATA[channel_id]:
for timestamp in _EPGDATA[channel_id]:
if timestamp > start:
break
last_timestamp = timestamp
if not last_timestamp:
return
start, new_start = last_timestamp, start
program_id, duration = [_EPGDATA[channel_id][start][t] for t in ["pid", "duration"]]
else:
if channel_id not in _CLOUD:
return
if start in _CLOUD[channel_id]:
duration = _CLOUD[channel_id][start]["duration"]
else:
for timestamp in _CLOUD[channel_id]:
duration = _CLOUD[channel_id][timestamp]["duration"]
if start > timestamp and start < timestamp + duration:
start, new_start = timestamp, start
if not new_start:
return
program_id = _CLOUD[channel_id][start]["pid"]
return {
"channel": channel,
"program_id": program_id,
"start": start,
"duration": duration,
"offset": new_start - start if new_start else 0,
}
def get_recording_files(fname):
basename = os.path.basename(fname)
metadata = os.path.join(RECORDINGS, os.path.join(os.path.dirname(fname), "metadata"))
files = glob_safe(os.path.join(RECORDINGS, f"{fname}*"))
files += glob_safe(os.path.join(metadata, f"{basename}*"))
return filter(lambda file: os.access(file, os.W_OK), files)
def get_recording_name(channel_id, timestamp, cloud=False):
guide = _CLOUD if cloud else _EPGDATA
daily_news_program = (
not guide[channel_id][timestamp]["is_serie"] and guide[channel_id][timestamp]["genre"] == "06"
)
if RECORDINGS_PER_CHANNEL:
path = os.path.join(RECORDINGS, get_channel_dir(channel_id))
else:
path = RECORDINGS
if guide[channel_id][timestamp]["serie"]:
path = os.path.join(path, get_safe_filename(guide[channel_id][timestamp]["serie"]))
elif daily_news_program:
path = os.path.join(path, get_safe_filename(guide[channel_id][timestamp]["full_title"]))
path = path.rstrip(".").rstrip(",")
filename = os.path.join(path, get_safe_filename(guide[channel_id][timestamp]["full_title"]))
if daily_news_program:
filename += f' - {datetime.fromtimestamp(timestamp).strftime("%Y%m%d")}'
return filename[len(RECORDINGS) + 1 :]
@app.route("/archive/<channel_id:int>/<program_id:int>", methods=["OPTIONS", "PUT"])
async def handle_archive(request, channel_id, program_id, cloud=False):
global _RECORDINGS, _t_timers
cloud = request.args.get("cloud") == "1" if request else cloud
try:
_epg, timestamp = get_epg(channel_id, program_id, cloud)
except TypeError:
raise NotFound(f"Requested URL {request.raw_url.decode()} not found")
filename = get_recording_name(channel_id, timestamp, cloud)
if not RECORDINGS:
return response.json({"status": "RECORDINGS not configured"}, 404)
log_suffix = '[%s] [%s] [%s] [%s] "%s"' % (
_CHANNELS[channel_id]["name"],
channel_id,
program_id,
timestamp,
filename,
)
if not _t_timers or _t_timers.done():
_t_timers = app.add_task(timers_check(delay=5))
recorded = int(request.args.get("recorded", 0))
if recorded:
if request.method == "OPTIONS" and recorded < 45:
log.error(f"Recording WRONG: {log_suffix}")
return response.json({"status": "Recording WRONG"}, status=202)
async with recordings_inc_lock:
if channel_id not in _RECORDINGS_INC:
_RECORDINGS_INC[channel_id] = {}
if program_id not in _RECORDINGS_INC[channel_id]:
_RECORDINGS_INC[channel_id][program_id] = []
_RECORDINGS_INC[channel_id][program_id].append(recorded)
_t = _RECORDINGS_INC[channel_id][program_id]
if request.method == "OPTIONS" and len(_t) > 2 and _t[-3] == _t[-2] and _t[-2] == _t[-1]:
log.warning(f"Recording Incomplete KEEP: {log_suffix}: {_t}")
return response.json({"status": "Recording Incomplete KEEP"}, status=201)
elif request.method == "PUT" and len(_t) > 3 and _t[-4] == _t[-3] and _t[-3] == _t[-2]:
log.warning(f"Recording Incomplete KEPT: {log_suffix}: {_t}")
async with recordings_inc_lock:
del _RECORDINGS_INC[channel_id][program_id]
else:
log.error(f"Recording Incomplete RETRY: {log_suffix}: {_t}")
return response.json({"status": "Recording Incomplete RETRY"}, status=202)
elif request.method == "OPTIONS":
log.debug(f"Recording OK: {log_suffix}")
return response.json({"status": "Recording OK"}, status=200)
def _prune_duplicates():
global _RECORDINGS
found = [ts for ts in _RECORDINGS[channel_id] if _RECORDINGS[channel_id][ts]["filename"] in filename]
if found:
for ts in found:
duplicate = _RECORDINGS[channel_id][ts]["filename"]
old_files = sorted(set(get_recording_files(duplicate)) - set(get_recording_files(filename)))
[remove(file) for file in old_files]
[log.warning(f'REMOVED DUPLICATED "{file}"') for file in old_files]
del _RECORDINGS[channel_id][ts]
log.debug(f"Checking for {filename}")
if does_recording_exist(filename):
async with recordings_lock:
if channel_id not in _RECORDINGS:
_RECORDINGS[channel_id] = {}
_prune_duplicates()
_RECORDINGS[channel_id][timestamp] = {"filename": filename}
app.add_task(update_recordings(channel_id))
msg = f"Recording ARCHIVED: {log_suffix}"
log.info(msg)
return response.json({"status": msg}, ensure_ascii=False)
else:
msg = f"Recording NOT ARCHIVED: {log_suffix}"
log.error(msg)
return response.json({"status": msg}, ensure_ascii=False, status=203)
@app.get("/channels/")
async def handle_channels(request):
return response.json(_CHANNELS) if _CHANNELS else response.empty(404)
@app.get("/program_id/<channel_id:int>/<url>")
async def handle_program_id(request, channel_id, url):
try:
return response.json(get_program_id(channel_id, url, request.args.get("cloud") == "1"))
except (AttributeError, KeyError):
raise NotFound(f"Requested URL {request.raw_url.decode()} not found")
@app.post("/prom_event/<method>")
async def handle_prom_event(request, method):
try:
return response.empty(200)
finally:
await prom_event(request, method)
@app.get("/record/<channel_id:int>/<url>")
async def handle_record_program(request, channel_id, url):
cloud = request.args.get("cloud") == "1"
mp4 = request.args.get("mp4") == "1"
vo = request.args.get("vo") == "1"
try:
channel, program_id, start, duration, offset = get_program_id(channel_id, url, cloud).values()
except AttributeError:
raise NotFound(f"Requested URL {request.raw_url.decode()} not found")
if request.args.get("time"):
record_time = int(request.args.get("time"))
else:
record_time = duration - offset
msg = await record_program(channel_id, program_id, offset, record_time, cloud, mp4, vo)
if msg:
raise ServiceUnavailable(msg)
return response.json(
{
"status": "OK",
"channel": channel,
"channel_id": channel_id,
"program_id": program_id,
"start": start,
"offset": offset,
"time": record_time,
}
)
@app.get("/reload_epg")
async def handle_reload_epg(request):
app.add_task(reload_epg())
return response.json({"status": "EPG Reload Queued"}, 200)
@app.get("/timers_check")
async def handle_timers_check(request):
global _t_timers
if not RECORDINGS:
return response.json({"status": "RECORDINGS not configured"}, 404)
if _NETWORK_SATURATION:
return response.json({"status": await log_network_saturated()}, 404)
if _t_timers and not _t_timers.done():
raise ServiceUnavailable("Already processing timers")
_t_timers = app.add_task(timers_check())
return response.json({"status": "Timers check queued"}, 200)
async def kill_vod():
vods = await ongoing_vods()
if not vods:
return
try:
vod = vods[-1]
proc = vod.children()[0]
except IndexError:
await asyncio.sleep(1)
return await kill_vod()
ffmpeg = " ".join(proc.cmdline()).split(RECORDINGS)[1][1:-4]
log.warning(f'KILLING ffmpeg [{proc.pid}] "{ffmpeg}"')
vod.terminate()
async def log_network_saturated(nr_procs=None, _wait=False):
global _last_bw_warning
level = _NETWORK_SATURATION
msg = ""
if level:
msg = f"Network {'Hard' if level == 2 else 'Soft' if level == 1 else ''} Saturated. "
if not nr_procs:
if _wait: # when called by network_saturation(), we wait so the recordings count is always correct
await asyncio.sleep(1)
nr_procs = len(await ongoing_vods())
msg += f"Recording {nr_procs} streams." if nr_procs else ""
if not _last_bw_warning or (time.time() - _last_bw_warning[0] > 5 or _last_bw_warning[1] != msg):
_last_bw_warning = (time.time(), msg)
log.warning(msg)
return msg
async def network_bw_control():
async with network_bw_lock:
await log_network_saturated()
await kill_vod()
await asyncio.sleep(2)
async def network_saturation():
global _NETWORK_SATURATION
iface_rx = f"/sys/class/net/{IPTV_IFACE}/statistics/rx_bytes"
before = last = 0
while True:
async with aiofiles.open(iface_rx) as f:
now, cur = time.time(), int((await f.read())[:-1])
if last:
tp = (cur - last) * 0.008 / (now - before)
_NETWORK_SATURATION = 2 if tp > IPTV_BW_HARD else 1 if (IPTV_BW_SOFT and tp > IPTV_BW_SOFT) else 0
if _NETWORK_SATURATION:
if _t_timers and not _t_timers.done():
_t_timers.cancel()
app.add_task(log_network_saturated(_wait=True))
if _NETWORK_SATURATION == 2 and not network_bw_lock.locked():
app.add_task(network_bw_control())
before, last = now, cur
await asyncio.sleep(1)
async def prom_event(request, method):
cloud = request.json.get("cloud", False)
_event = get_program_id(request.json["channel_id"], request.json.get("url"), cloud)
_epg, _ = get_epg(request.json["channel_id"], _event["program_id"], cloud)
if method == "add":
offset = "[%d/%d]" % (_event["offset"], _event["duration"])
request.app.ctx.metrics["RQS_LATENCY"].labels(
request.json["method"],
request.json["endpoint"] + _epg["full_title"] + f" _ {offset}",
request.json["id"],
).observe(float(request.json["lat"]))
else:
start, end = _event["offset"], _event["offset"] + request.json["offset"]
offset = "[%d-%d/%d]" % (start, end, _event["duration"])
for _metric in request.app.ctx.metrics["RQS_LATENCY"]._metrics:
if (request.json["method"] and request.json["id"]) in _metric:
request.app.ctx.metrics["RQS_LATENCY"].remove(*_metric)
break
log.info(
f'{request.json["msg"]} [{_event["channel"]}] [{request.json["channel_id"]}] '
f'[{_event["program_id"]}] [{_event["start"]}] "{_epg["full_title"]}" _ {offset}'
)
async def reap_vod_child(process, filename):
retcode = await process.wait()
if WIN32 and retcode not in win32_normal_retcodes:
log.debug(f"Reap VOD Child: [{process}]:[{retcode}] Exiting!!!")
Process().terminate()
if retcode == -9 or WIN32 and retcode:
ongoing = await ongoing_vods(filename=filename)
if ongoing:
log.debug('Reap VOD Child: Killing child: "%s"' % " ".join(ongoing[0].cmdline()))
ongoing[0].terminate()
global _t_timers
if not _t_timers or _t_timers.done():
_t_timers = app.add_task(timers_check(delay=5))
log.debug(f"Reap VOD Child: [{process}]:[{retcode}] DONE")
async def record_program(channel_id, program_id, offset=0, record_time=0, cloud=False, mp4=False, vo=False):
timestamp = get_epg(channel_id, program_id, cloud)[1]
filename = get_recording_name(channel_id, timestamp, cloud)
if await ongoing_vods(channel_id, program_id, filename):
msg = f'Recording already ongoing: [{channel_id}] [{program_id}] "{filename}"'
log.warning(msg)
return msg
elif _NETWORK_SATURATION:
return await log_network_saturated()
port = find_free_port(_IPTV)
cmd = [sys.executable] if EXT == ".py" else []
cmd += [f"movistar_vod{EXT}", str(channel_id), str(program_id), "-p", str(port), "-w"]
cmd += ["-o", filename]
cmd += ["-s", str(offset)] if offset else []
cmd += ["-t", str(record_time)] if record_time else []
cmd += ["--cloud"] if cloud else []
cmd += ["--mp4"] if mp4 else []
cmd += ["--vo"] if vo else []
log.debug('Launching: "%s"' % " ".join(cmd))
process = await asyncio.create_subprocess_exec(*cmd)
app.add_task(reap_vod_child(process, filename))
async def reload_epg():
global _CHANNELS, _CLOUD, _EPGDATA
if (
not os.path.exists(CHANNELS)
and os.path.exists(config_data)
and os.path.exists(epg_data)
and os.path.exists(epg_metadata)
and os.path.exists(GUIDE)
and os.path.exists(GUIDE + ".gz")
):
log.warning("Missing channel list! Need to download it. Please be patient...")
cmd = [sys.executable] if EXT == ".py" else []
cmd += [f"movistar_tvg{EXT}", "--m3u", CHANNELS]
async with tvgrab_lock:
task = app.add_task(launch(cmd))
await task
check_task(task)
if not os.path.exists(CHANNELS):
return app.add_task(cancel_app())
elif (
not os.path.exists(config_data)
or not os.path.exists(epg_data)
or not os.path.exists(epg_metadata)
or not os.path.exists(GUIDE)
or not os.path.exists(GUIDE + ".gz")
):
log.warning("Missing channels data! Need to download it. Please be patient...")
return await update_epg()
async with epg_lock:
int_channels, int_epgdata, services = {}, {}, {}
try:
async with aiofiles.open(epg_metadata, encoding="utf8") as f:
metadata = ujson.loads(await f.read())["data"]
async with aiofiles.open(config_data, encoding="utf8") as f:
packages = ujson.loads(await f.read())["data"]["tvPackages"]
for package in packages.split("|") if packages != "ALL" else metadata["packages"]:
services = {**services, **metadata["packages"][package]["services"]}
channels = metadata["channels"]
for channel in [chan for chan in channels if chan in services]:
int_channels[int(channel)] = channels[channel]
int_channels[int(channel)]["id"] = int(channels[channel]["id"])
int_channels[int(channel)]["number"] = int(services[channel])
if "replacement" in channels[channel]:
int_channels[int(channel)]["replacement"] = int(channels[channel]["replacement"])
_CHANNELS = int_channels
except (FileNotFoundError, TypeError, ValueError) as ex:
log.error(f"Failed to load Channels metadata {repr(ex)}")
if os.path.exists(epg_metadata):
os.remove(epg_metadata)
return await reload_epg()
try:
async with aiofiles.open(epg_data, encoding="utf8") as f:
epgdata = ujson.loads(await f.read())["data"]
for channel in epgdata:
int_epgdata[int(channel)] = {}
for timestamp in epgdata[channel]:
int_epgdata[int(channel)][int(timestamp)] = epgdata[channel][timestamp]
_EPGDATA = int_epgdata
except (FileNotFoundError, TypeError, ValueError) as ex:
log.error(f"Failed to load EPG data {repr(ex)}")
if os.path.exists(epg_data):
os.remove(epg_data)
return await reload_epg()
log.info(f"Channels & EPG Updated => {U7D_URL}/MovistarTV.m3u - {U7D_URL}/guide.xml.gz")
await update_cloud()
nr_epg = sum([len(_EPGDATA[channel]) for channel in _EPGDATA])
log.info(f"Total: {len(_EPGDATA)} Channels & {nr_epg} EPG entries")
async def timers_check(delay=0):
await asyncio.sleep(delay)
if not os.path.exists(timers):
log.debug("timers_check: no timers.conf found")
return
nr_procs = len(await ongoing_vods())
if _NETWORK_SATURATION or nr_procs >= RECORDINGS_THREADS:
await log_network_saturated(nr_procs)
return
if epg_lock.locked(): # If EPG is being updated, wait until it is done
await epg_lock.acquire()
epg_lock.release()
log.info("Processing timers")
try:
async with aiofiles.open(timers, encoding="utf8") as f:
try:
_timers = tomli.loads(await f.read())
except ValueError:
_timers = ujson.loads(await f.read())
except (TypeError, ValueError) as ex:
log.error(f"Failed to parse timers.conf: {repr(ex)}")
return
deflang = _timers.get("default_language", "")
sync_cloud = _timers.get("sync_cloud", False)
def _clean(string):
return unicodedata.normalize("NFKD", string).encode("ASCII", "ignore").decode("utf8")
async def _record(cloud=False):
nonlocal channel_id, channel_name, ongoing, queued, nr_procs, recs, timer_match, timestamp, vo
filename = get_recording_name(channel_id, timestamp, cloud)
if filename in ongoing or (channel_id, timestamp) in queued:
return
guide = _CLOUD if cloud else _EPGDATA
duration, pid, title = [guide[channel_id][timestamp][t] for t in ["duration", "pid", "full_title"]]
if not cloud and timestamp + duration >= _last_epg:
return
if channel_id in recs and filename in str(recs[channel_id]):
return
if cloud or re.search(_clean(timer_match), _clean(title), re.IGNORECASE):
if await record_program(channel_id, pid, 0, 0 if cloud else duration, cloud, MP4_OUTPUT, vo):
return
log.info(
f"Found {'Cloud Recording' if cloud else 'MATCH'}: "
f'[{channel_name}] [{channel_id}] [{pid}] [{timestamp}] "{filename}"'
f"{' [VO]' if vo else ''}"
)
queued.append((channel_id, timestamp))
await asyncio.sleep(2.5 if not WIN32 else 4)
nr_procs += 1
if nr_procs >= RECORDINGS_THREADS:
await log_network_saturated(nr_procs)
return -1
async with recordings_lock:
recs = _RECORDINGS.copy()
ongoing = await ongoing_vods(_all=True) # we want to check against all ongoing vods, also in pp
log.debug(f"Ongoing VODs: [{ongoing}]")
queued = []
for str_channel_id in _timers.get("match", {}):
channel_id = int(str_channel_id)
if channel_id not in _EPGDATA:
log.warning(f"Channel [{channel_id}] not found in EPG")
continue
channel_name = _CHANNELS[channel_id]["name"]
for timer_match in _timers["match"][str_channel_id]:
fixed_timer = 0
lang = deflang
if " ## " in timer_match:
match_split = timer_match.split(" ## ")
timer_match = match_split[0]
for res in match_split[1:3]:
if res[0].isnumeric():
try:
hour, minute = [int(t) for t in res.split(":")]
fixed_timer = int(
datetime.now().replace(hour=hour, minute=minute, second=0).timestamp()
)
log.debug(f'[{channel_name}] "{timer_match}" {hour:02}:{minute:02} {fixed_timer}')
except ValueError:
log.warning(f'Failed to parse [{channel_name}] "{timer_match}" [{res}] correctly')
else:
lang = res
vo = lang == "VO"
timestamps = [ts for ts in reversed(_EPGDATA[channel_id]) if ts < _last_epg]
if fixed_timer:
# fixed timers are checked daily, so we want today's and all of last week
fixed_timestamps = [fixed_timer] if fixed_timer < _last_epg else []
fixed_timestamps += [fixed_timer - i * 24 * 3600 for i in range(1, 8)]
found_ts = []
for ts in timestamps:
for fixed_ts in fixed_timestamps:
if abs(ts - fixed_ts) <= 900:
found_ts.append(ts)
break
timestamps = found_ts
log.debug(f"Checking timer: [{channel_name}] [{channel_id}] [{_clean(timer_match)}]")
for timestamp in [
ts for ts in timestamps if (channel_id not in recs or ts not in recs[channel_id])
]:
if await _record():
return
if sync_cloud:
vo = _timers["sync_cloud_language"] == "VO" if "sync_cloud_language" in _timers else False
for channel_id in _CLOUD:
for timestamp in [
ts for ts in _CLOUD[channel_id] if (channel_id not in recs or ts not in recs[channel_id])
]:
if await _record(cloud=True):
return
async def update_cloud():
global _CLOUD, _EPGDATA
try:
async with aiofiles.open(cloud_data, encoding="utf8") as f:
clouddata = ujson.loads(await f.read())["data"]
int_clouddata = {}
for channel in clouddata:
int_clouddata[int(channel)] = {}
for timestamp in clouddata[channel]:
int_clouddata[int(channel)][int(timestamp)] = clouddata[channel][timestamp]
_CLOUD = int_clouddata
except (FileNotFoundError, TypeError, ValueError):
if os.path.exists(cloud_data):
os.remove(cloud_data)
try:
params = {"action": "recordingList", "mode": 0, "state": 2, "firstItem": 0, "numItems": 999}
async with _SESSION_CLOUD.get(URL_MVTV, params=params) as r:
cloud_recordings = (await r.json())["resultData"]["result"]
except (ClientOSError, KeyError, ServerDisconnectedError):
cloud_recordings = None
if not cloud_recordings:
log.info("No cloud recordings found")
return
def _fill_cloud_event():
nonlocal data, meta, pid, timestamp, year
episode = meta["episode"] or data.get("episode")
season = meta["season"] or data.get("season")
serie = meta["serie"] or data.get("seriesName")
return {
"age_rating": data["ageRatingID"],
"duration": data["duration"],
"end": int(str(data["endTime"])[:-3]),
"episode": episode,
"full_title": meta["full_title"],
"genre": data["theme"],
"is_serie": meta["is_serie"],
"pid": pid,
"season": season,
"start": int(timestamp),
"year": year,
"serie": serie,
"serie_id": data.get("seriesID"),
}
new_cloud = {}
for _event in cloud_recordings:
channel_id = _event["serviceUID"]
timestamp = int(_event["beginTime"] / 1000)
if channel_id not in new_cloud:
new_cloud[channel_id] = {}
if timestamp not in new_cloud[channel_id]:
if channel_id in _EPGDATA and timestamp in _EPGDATA[channel_id]:
new_cloud[channel_id][timestamp] = _EPGDATA[channel_id][timestamp]
elif channel_id in _CLOUD and timestamp in _CLOUD[channel_id]:
new_cloud[channel_id][timestamp] = _CLOUD[channel_id][timestamp]
else:
pid = _event["productID"]
params = {"action": "epgInfov2", "productID": pid, "channelID": channel_id}
async with _SESSION_CLOUD.get(URL_MVTV, params=params) as r:
_data = (await r.json())["resultData"]
year = _data.get("productionDate")
params = {"action": "getRecordingData", "extInfoID": pid, "channelID": channel_id, "mode": 1}
async with _SESSION_CLOUD.get(URL_MVTV, params=params) as r:
data = (await r.json())["resultData"]
if not data: # There can be events with no data sometimes
continue
meta = get_title_meta(data["name"], data.get("seriesID"))
new_cloud[channel_id][timestamp] = _fill_cloud_event()
if meta["episode_title"]:
new_cloud[channel_id][timestamp]["episode_title"] = meta["episode_title"]
updated = False
if new_cloud and (not _CLOUD or set(new_cloud) != set(_CLOUD)):
updated = True
else:
for id in new_cloud:
if set(new_cloud[id]) != set(_CLOUD[id]):
updated = True
break
for channel_id in new_cloud:
if channel_id not in _EPGDATA:
_EPGDATA[channel_id] = {}
for timestamp in list(set(new_cloud[channel_id]) - set(_EPGDATA[channel_id])):
_EPGDATA[channel_id][timestamp] = new_cloud[channel_id][timestamp]
if updated:
_CLOUD = new_cloud
async with aiofiles.open(cloud_data, "w", encoding="utf8") as f:
await f.write(ujson.dumps({"data": _CLOUD}, ensure_ascii=False, indent=4, sort_keys=True))
if updated or not os.path.exists(CHANNELS_CLOUD) or not os.path.exists(GUIDE_CLOUD):
if not os.path.exists(CHANNELS_CLOUD) or not os.path.exists(GUIDE_CLOUD):
log.warning("Missing Cloud Recordings data! Need to download it. Please be patient...")
cmd = [sys.executable] if EXT == ".py" else []
cmd += [f"movistar_tvg{EXT}", "--cloud_m3u", CHANNELS_CLOUD, "--cloud_recordings", GUIDE_CLOUD]
async with tvgrab_lock:
task = app.add_task(launch(cmd))
await task
check_task(task)
log.info(f"Cloud Recordings Updated => {U7D_URL}/MovistarTVCloud.m3u - {U7D_URL}/cloud.xml")
async def update_epg(abort_on_error=False):
global _last_epg, _t_timers
cmd = [sys.executable] if EXT == ".py" else []
cmd += [f"movistar_tvg{EXT}", "--m3u", CHANNELS, "--guide", GUIDE]
for i in range(3):
async with tvgrab_lock:
task = app.add_task(launch(cmd))
await task
check_task(task)
if task.result():
if i < 2:
await asyncio.sleep(3)
log.error(f"[{i+2}/3]...")
elif abort_on_error or not _CHANNELS or not _EPGDATA:
app.add_task(cancel_app())
else:
await reload_epg()
_last_epg = int(datetime.now().replace(minute=0, second=0).timestamp())
if RECORDINGS and (not _t_timers or _t_timers.done()):
_t_timers = app.add_task(timers_check(delay=10))
break
async def update_epg_cron():
last_datetime = datetime.now().replace(minute=0, second=0, microsecond=0)
if os.path.getmtime(GUIDE) < last_datetime.timestamp():
log.warning("EPG too old. Updating it...")
await update_epg(abort_on_error=True)
await asyncio.sleep((last_datetime + timedelta(hours=1) - datetime.now()).total_seconds())
while True:
await asyncio.gather(asyncio.sleep(3600), update_epg())
async def update_recordings(archive=False):
def _dump_files(files, channel=False, latest=False):
m3u = ""
for file in files:
filename, ext = os.path.splitext(file)
relname = filename[len(RECORDINGS) + 1 :]
if os.path.exists(filename + ".jpg"):
logo = relname + ".jpg"
else:
_logo = glob_safe(f"{filename}*.jpg")
if len(_logo) and os.path.isfile(_logo[0]):
logo = _logo[0][len(RECORDINGS) + 1 :]
else:
logo = ""
path, name = [t.replace(",", ":").replace(" - ", ": ") for t in os.path.split(relname)]
m3u += '#EXTINF:-1 group-title="'
m3u += '# Recientes"' if latest else f'{path}"' if path else '#"'
m3u += f' tvg-logo="{U7D_URL}/recording/?' if logo else ""
m3u += (urllib.parse.quote(logo) + '"') if logo else ""
m3u += f",{path} - " if (channel and path) else ","
m3u += f"{name}\n{U7D_URL}/recording/?"
m3u += urllib.parse.quote(relname + ext) + "\n"
return m3u