-
Notifications
You must be signed in to change notification settings - Fork 19
/
movistar_tvg.py
executable file
·1416 lines (1295 loc) · 55.4 KB
/
movistar_tvg.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
#
# Based on tv_grab_es_movistartv by Willow:
# Source: https://github.com/MovistarTV/tv_grab_es_movistartv
import aiohttp
import argparse
import asyncio
import codecs
import defusedxml.ElementTree as ElTr
import glob
import gzip
import logging
import os
import random
import re
import socket
import struct
import sys
import threading
import time
import ujson as json
from aiohttp.resolver import AsyncResolver
from contextlib import closing
from datetime import date, datetime, timedelta
from filelock import FileLock, Timeout
from queue import Queue
from xml.dom import minidom # nosec B408
from xml.etree.ElementTree import Element, ElementTree, SubElement # nosec B405
from mu7d import IPTV_DNS, UA, UA_U7D, WIN32, YEAR_SECONDS
from mu7d import get_iptv_ip, get_title_meta, mu7d_config, _version
log = logging.getLogger("TVG")
epg_channels = [
"2543",
"4455",
"4919",
"2524",
"1825",
"1826",
"2526",
"884",
"4714",
"3223",
"844",
"1221",
"4063",
"2544",
"3063",
"657",
"663",
"4716",
"4715",
"3185",
"1616",
"578",
"4467",
"5104",
"743",
"582",
"3603",
"3443",
"5029",
"3103",
"4990",
]
demarcations = {
"Andalucia": 15,
"Aragon": 34,
"Asturias": 13,
"Cantabria": 29,
"Catalunya": 1,
"Castilla la Mancha": 38,
"Castilla y Leon": 4,
"Comunidad Valenciana": 6,
"Extremadura": 32,
"Galicia": 24,
"Islas Baleares": 10,
"Islas Canarias": 37,
"La Rioja": 31,
"Madrid": 19,
"Murcia": 12,
"Navarra": 35,
"Pais Vasco": 36,
}
end_points = {
"epNoCach1": "http://www-60.svc.imagenio.telefonica.net:2001",
"epNoCach2": "http://nc2.svc.imagenio.telefonica.net:2001",
"epNoCach4": "http://nc4.svc.imagenio.telefonica.net:2001",
"epNoCach5": "http://nc5.svc.imagenio.telefonica.net:2001",
"epNoCach6": "http://nc6.svc.imagenio.telefonica.net:2001",
}
genre_map = {
"0": {
"0": "Arts / Culture (without music)",
"1": "Popular culture / Traditional arts",
"2": "Popular culture / Traditional arts",
"3": "Arts magazines / Culture magazines",
"4": "Fine arts",
"5": "Fashion",
"6": "Broadcasting / Press",
"7": "Performing arts",
"8": "Performing arts",
"9": "Arts magazines / Culture magazines",
"A": "New media",
"B": "Popular culture / Traditional arts",
"C": "Film / Cinema",
"D": "Arts magazines / Culture magazines",
"E": "Performing arts",
"F": "Experimental film / Video",
},
"1": {
"0": "Movie / Drama",
"1": "Adventure / Western / War",
"2": "Romance",
"3": "Soap / Melodrama / Folkloric",
"4": "Serious / Classical / Religious / Historical movie / Drama",
"5": "Science fiction / Fantasy / Horror",
"6": "Detective / Thriller",
"7": "Comedy",
"8": "Serious / Classical / Religious / Historical movie / Drama",
"9": "Movie / drama",
"A": "Adventure / Western / War",
"B": "Movie / drama",
"C": "Adult movie / Drama",
"D": "Science fiction / Fantasy / Horror",
"E": "Adult movie / Drama",
"F": "Science fiction / Fantasy / Horror",
},
"2": {
"0": "Social / Political issues / Economics",
"1": "Magazines / Reports / Documentary",
"2": "Economics / Social advisory",
"3": "Social / Political issues / Economics",
"4": "Social / Political issues / Economics",
"5": "Social / Political issues / Economics",
"6": "Social / Political issues / Economics",
"7": "Social / Political issues / Economics",
"8": "Social / Political issues / Economics",
"9": "Social / Political issues / Economics",
"A": "Social / Political issues / Economics",
"B": "Social / Political issues / Economics",
"C": "Social / Political issues / Economics",
"D": "Social / Political issues / Economics",
"E": "Social / Political issues / Economics",
"F": "Social / Political issues / Economics",
},
"4": {
"0": "Sports",
"1": "Motor sport",
"2": "Team sports (excluding football)",
"3": "Water sport",
"4": "Team sports (excluding football)",
"5": "Team sports (excluding football)",
"6": "Martial sports",
"7": "Football / Soccer",
"8": "Water sport",
"9": "Team sports (excluding football)",
"A": "Athletics",
"B": "Sports",
"C": "Motor sport",
"D": "Sports",
"E": "Sports",
"F": "Tennis / Squash",
},
"5": {
"0": "Children's / Youth programs",
"1": "Entertainment programs for 10 to 16",
"2": "Pre-school children's programs",
"3": "Entertainment programs for 6 to 14",
"4": "Children's / Youth programs",
"5": "Informational / Educational / School programs",
"6": "Entertainment programs for 6 to 14",
"7": "Children's / Youth programs",
"8": "Children's / Youth programs",
"9": "Children's / Youth programs",
"A": "Children's / Youth programs",
"B": "Children's / Youth programs",
"C": "Children's / Youth programs",
"D": "Children's / Youth programs",
"E": "Children's / Youth programs",
"F": "Children's / Youth programs",
},
"6": {
"0": "Music / Ballet / Dance",
"1": "Musical / Opera",
"2": "Serious music / Classical music",
"3": "Rock / Pop",
"4": "Music / Ballet / Dance",
"5": "Music / Ballet / Dance",
"6": "Music / Ballet / Dance",
"7": "Musical / Opera",
"8": "Ballet",
"9": "Jazz",
"A": "Music / Ballet / Dance",
"B": "Rock / Pop",
"C": "Music / Ballet / Dance",
"D": "Music / Ballet / Dance",
"E": "Music / Ballet / Dance",
"F": "Music / Ballet / Dance",
},
"7": {
"0": "Show / Game show",
"1": "Variety show",
"2": "Variety show",
"3": "Variety show",
"4": "Talk show",
"5": "Variety show",
"6": "Variety show",
"7": "Variety show",
"8": "Variety show",
"9": "Variety show",
"A": "Variety show",
"B": "Show / Game show",
"C": "Talk show",
"D": "Show / Game show",
"E": "Show / Game show",
"F": "Show / Game show",
},
"8": {
"0": "Education / Science / Factual topics",
"1": "Further education",
"2": "Social / Spiritual sciences",
"3": "Medicine / Physiology / Psychology",
"4": "Social / Spiritual sciences",
"5": "Technology / Natural sciences",
"6": "Social / Spiritual sciences",
"7": "Education / Science / Factual topics",
"8": "Further education",
"9": "Nature / Animals / Environment",
"A": "Foreign countries / Expeditions",
"B": "Further education",
"C": "Social / Spiritual sciences",
"D": "Further education",
"E": "Education / Science / Factual topics",
"F": "Education / Science / Factual topics",
},
"9": {
"0": "Movie / Drama",
"1": "Adult movie / Drama",
"2": "Adult movie / Drama",
"3": "Adult movie / Drama",
"4": "Adult movie / Drama",
"5": "Adult movie / Drama",
"6": "Adult movie / Drama",
"7": "Adult movie / Drama",
"8": "Adult movie / Drama",
"9": "Adult movie / Drama",
"A": "Adult movie / Drama",
"B": "Adult movie / Drama",
"C": "Adult movie / Drama",
"D": "Adult movie / Drama",
"E": "Adult movie / Drama",
"F": "Adult movie / Drama",
},
}
class MulticastEPGFetcher(threading.Thread):
def __init__(self, queue, exc_queue):
threading.Thread.__init__(self, daemon=True)
self.queue = queue
self.exc_queue = exc_queue
def run(self):
while True:
mcast = self.queue.get()
try:
iptv.get_day(mcast["mcast_grp"], mcast["mcast_port"], mcast["source"])
except Exception as ex:
self.exc_queue.put(ex)
self.queue.task_done()
class Cache:
def __init__(self):
self.__programs = {}
self.__end_points = None
self.__check_dirs()
self.__clean()
@staticmethod
def __check_dirs():
cache_path = os.path.join(app_dir, "cache")
progs_path = os.path.join(cache_path, "programs")
if not os.path.exists(app_dir):
os.mkdir(app_dir)
if not os.path.exists(cache_path):
log.info(f"Creando caché en {cache_path}")
os.mkdir(cache_path)
if not os.path.exists(progs_path):
os.mkdir(progs_path)
@staticmethod
def __clean():
for file in glob.glob(f"{app_dir}{sep}cache{sep}programs{sep}*.json"):
try:
with open(file, encoding="utf8") as f:
_data = json.load(f)["data"]
_exp_date = int(_data["endTime"] / 1000)
if _exp_date < deadline:
os.remove(file)
except (IOError, KeyError, ValueError):
pass
@staticmethod
def __load(cfile):
try:
with open(f"{app_dir}{sep}cache{sep}{cfile}", "r", encoding="utf8") as f:
return json.load(f)["data"]
except (IOError, KeyError, ValueError):
pass
@staticmethod
def __save(cfile, data):
with open(f"{app_dir}{sep}cache{sep}{cfile}", "w", encoding="utf8") as f:
try:
json.dump({"data": data}, f, ensure_ascii=False, indent=4, sort_keys=True)
except AttributeError:
json.dump({"data": data}, f, ensure_ascii=False, sort_keys=True)
def load_cloud_epg(self):
return self.__load("cloud.json")
def load_config(self):
return self.__load("config.json")
def load_cookie(self):
return self.__load(cookie_file)
def load_end_points(self):
if not self.__end_points:
self.__end_points = self.__load(end_points_file)
return self.__end_points or end_points
async def load_epg(self):
data = self.__load("epg.json")
if not data:
async with aiohttp.ClientSession(headers={"User-Agent": UA_U7D}) as session:
for i in range(5):
log.info("Intentando obtener Caché de EPG actualizada...")
try:
async with session.get("https://openwrt.marcet.info/epg.json") as r:
if r.status == 200:
data = (await r.json())["data"]
log.info("Obtenida Caché de EPG actualizada")
break
if i < 4:
log.warning(f"No ha habido suerte. Reintentando en 15s... [{i+2}/5]")
await asyncio.sleep(15)
except Exception as ex:
data = None
if i < 4:
log.warning(
f"No ha habido suerte. Reintentando en 15s... [{i+2}/5] => {repr(ex)}"
)
await asyncio.sleep(15)
if not data:
log.warning(
"Caché de EPG no encontrada. "
"Tendrá que esperar unos días para poder acceder a todo el archivo de los útimos 7 días."
)
return data
def load_epg_extended_info(self, pid):
return self.__programs[pid] if pid in self.__programs else self.__load(f"programs{sep}{pid}.json")
def load_service_provider_data(self):
return self.__load("provider.json")
def save_config(self, data):
self.__save("config.json", data)
def save_cookie(self, data):
# log.debug(f"Set-Cookie: {data}")
self.__save(cookie_file, data)
def save_end_points(self, data):
log.info(f"Nuevos End Points: {sorted(data.keys())}")
self.__end_points = data
self.__save(end_points_file, data)
def save_epg(self, data):
self.__save("epg.json", data)
def save_epg_data(self, data):
self.__save("epg_metadata.json", data)
def save_epg_extended_info(self, data):
self.__programs[data["productID"]] = data
self.__save("programs%s%s.json" % (sep, data["productID"]), data)
def save_service_provider_data(self, data):
self.__save("provider.json", data)
class MovistarTV:
def __init__(self):
self.__cookie = cache.load_cookie()
self.__end_points_down = []
self.__web_service_down = False
self.__session = None
@staticmethod
def __get_end_points():
try:
return config["end_points"]
except TypeError:
return cache.load_end_points()
async def __get_genres(self, tv_wholesaler):
log.info("Descargando mapa de géneros")
return await self.__get_service_data(f"getEpgSubGenres&tvWholesaler={tv_wholesaler}")
async def __get_service_data(self, action):
if self.__web_service_down:
return
ep = self.get_end_point()
if not ep:
log.warning("Servicio Web de Movistar TV caído: decargando guía básica")
self.__web_service_down = True
return
__attempts = 10
while __attempts > 0:
try:
headers = {}
if self.__cookie:
for ck in self.__cookie.split("; "):
if "=" in ck:
headers["Cookie"] = self.__cookie
url = f"{ep}/appserver/mvtv.do?action={action}"
async with session.get(url, headers=headers) as response:
if response.status == 200:
content = (await response.json())["resultData"]
new_cookie = response.headers.get("set-cookie")
if new_cookie and not self.__cookie:
self.__cookie = new_cookie
cache.save_cookie(self.__cookie)
elif new_cookie and new_cookie != self.__cookie:
cache.save_cookie(new_cookie)
return content
except Exception as ex:
__attempts -= 1
log.debug(f"Timeout: {ep}, reintentos: {__attempts} => {repr(ex)}")
continue
@staticmethod
def __update_end_points(data):
cache.save_end_points(data)
return data
def get_end_point(self):
eps = self.__get_end_points()
for ep in sorted(eps):
if eps[ep] not in self.__end_points_down:
return eps[ep]
async def get_epg_extended_info(self, pid, channel_id):
try:
data = cache.load_epg_extended_info(pid)
except Exception as ex:
log.debug(f"{repr(ex)}")
if not data:
try:
data = await self.__get_service_data(
f"epgInfov2&productID={pid}&channelID={channel_id}&extra=1"
)
cache.save_epg_extended_info(data)
except Exception as ex:
log.debug(f"Información extendida no encontrada: {pid} {repr(ex)}")
return
return data
def get_first_end_point(self):
eps = self.__get_end_points()
for ep in sorted(eps):
return eps[ep]
def get_random_end_point(self):
eps = self.__get_end_points()
return eps[random.choice(eps.keys())] # nosec B311
async def get_service_config(self):
cfg = cache.load_config()
if cfg:
if VERBOSE:
log.info("tvPackages: %s" % cfg["tvPackages"])
log.info("Demarcation: %s" % cfg["demarcation"])
return cfg
log.info("Descargando configuración del cliente, parámetros de configuración y perfil del servicio")
client, params, platform = await asyncio.gather(
self.__get_service_data("getClientProfile"),
self.__get_service_data("getConfigurationParams"),
self.__get_service_data("getPlatformProfile"),
)
if not client or not params or not platform:
raise ValueError("IPTV de Movistar no detectado")
dvb_entry_point = platform["dvbConfig"]["dvbipiEntryPoint"].split(":")
uri = platform[list(filter(lambda f: re.search("base.*uri", f, re.IGNORECASE), platform.keys()))[0]]
if VERBOSE:
log.info("tvPackages: %s" % client["tvPackages"])
log.info("Demarcation: %s" % client["demarcation"])
conf = {
"tvPackages": client["tvPackages"],
"demarcation": client["demarcation"],
"tvWholesaler": client["tvWholesaler"],
"end_points": self.__update_end_points(platform["endPoints"]),
"mcast_grp": dvb_entry_point[0],
"mcast_port": int(dvb_entry_point[1]),
"tvChannelLogoPath": "%s%s" % (uri, params["tvChannelLogoPath"]),
"tvCoversPath": "%s%s%s290x429/" % (uri, params["tvCoversPath"], params["portraitSubPath"]),
"tvCoversLandscapePath": "%s%s%s%s"
% (uri, params["tvCoversPath"], params["landscapeSubPath"], params["bigSubpath"]),
"genres": await self.__get_genres(client["tvWholesaler"]),
}
cache.save_config(conf)
return conf
class MulticastIPTV:
def __init__(self):
self.__xml_data = {}
self.__epg = None
@staticmethod
def __decode_string(string):
_t = ("".join(chr(char ^ 0x15) for char in string)).encode("latin1").decode("utf8")
return _t.replace(""", "«", 1).replace(""", "»", 1)
@staticmethod
def __drop_encrypted_channels(epg):
clean_channels = {}
for channel in list(set(epg) & set(epg_channels)):
clean_channels[channel] = epg[channel]
return clean_channels
def __get_bin_epg(self):
queue, exc_queue = Queue(), Queue()
threads = tvg_threads
self.__epg = [{} for r in range(len(self.__xml_data["segments"]))]
log.info(f"Multithread: {threads} descargas simultáneas")
for n in range(threads):
process = MulticastEPGFetcher(queue, exc_queue)
process.start()
for key in sorted(self.__xml_data["segments"]):
queue.put(
{
"mcast_grp": self.__xml_data["segments"][key]["Address"],
"mcast_port": self.__xml_data["segments"][key]["Port"],
"source": key,
}
)
queue.join()
if exc_queue.qsize():
raise exc_queue.get()
@staticmethod
def __get_channels(xml_channels):
root = ElTr.fromstring(xml_channels.replace("\n", " "))
services = root[0][0].findall("{urn:dvb:ipisdns:2006}SingleService")
channel_list = {}
for i in services:
channel_id = "unknown"
try:
channel_id = i[1].attrib["ServiceName"]
channel_list[channel_id] = {
"id": channel_id,
"address": i[0][0].attrib["Address"],
"port": i[0][0].attrib["Port"],
"name": i[2][0].text.encode("latin1").decode("utf8"),
"shortname": i[2][1].text.encode("latin1").decode("utf8"),
"genre": i[2][3][0].text.encode("latin1").decode("utf8"),
"logo_uri": i[1].attrib["logoURI"]
if "logoURI" in i[1].attrib
else "MAY_1/imSer/4146.jpg",
}
if i[2][4].tag == "{urn:dvb:ipisdns:2006}ReplacementService":
channel_list[channel_id]["replacement"] = i[2][4][0].attrib["ServiceName"]
except (KeyError, IndexError) as ex:
log.debug(f"El canal {channel_id} no tiene la estructura correcta: {repr(ex)}")
if VERBOSE:
log.info("Canales: %i" % len(channel_list))
return channel_list
@staticmethod
def __get_demarcation_name():
for demarcation in demarcations:
if demarcations[demarcation] == config["demarcation"]:
return demarcation
return config["demarcation"]
def __get_epg_data(self, mcast_grp, mcast_port):
while True:
xml = self.__get_xml_files(mcast_grp, mcast_port)
_msg = "[" + " ".join(sorted(xml)) + "] / [2_0 5_0 6_0]"
if "2_0" in xml and "5_0" in xml and "6_0" in xml:
if VERBOSE:
log.info(f"Ficheros XML descargados: {_msg}")
break
else:
log.warning(f"Ficheros XML incompletos: {_msg}")
time.sleep(10)
if VERBOSE:
log.info("Descargando canales y paquetes")
try:
self.__xml_data["channels"] = self.__get_channels(xml["2_0"])
self.__xml_data["packages"] = self.__get_packages(xml["5_0"])
if VERBOSE:
log.info("Descargando índices")
self.__xml_data["segments"] = self.__get_segments(xml["6_0"])
except Exception as ex:
log.debug(f"{repr(ex)}")
log.warning("Error descargando datos de la EPG. Reintentando...")
return self.__get_epg_data(mcast_grp, mcast_port)
cache.save_epg_data(self.__xml_data)
@staticmethod
def __get_packages(xml):
root = ElTr.fromstring(xml.replace("\n", " "))
packages = root[0].findall("{urn:dvb:ipisdns:2006}Package")
package_list = {}
for package in packages:
package_name = "unknown"
try:
package_name = package[0].text
package_list[package_name] = {
"id": package.attrib["Id"],
"name": package_name,
"services": {},
}
for service in package:
if not service.tag == "{urn:dvb:ipisdns:2006}PackageName":
service_id = service[0].attrib["ServiceName"]
package_list[package_name]["services"][service_id] = service[1].text
except (AttributeError, IndexError, KeyError):
log.debug(f"El paquete {package_name} no tiene la estructura correcta")
if VERBOSE:
log.info(f"Paquetes: {len(package_list)}")
return package_list
def __get_sane_epg(self, epg):
sane_epg = {}
for channel_key in epg:
_channels = self.__xml_data["channels"]
for channel_id in _channels:
if (
"replacement" in _channels[channel_id]
and _channels[channel_id]["replacement"] == channel_key
):
sane_epg[channel_id] = epg[channel_key]
break
if channel_id not in sane_epg:
sane_epg[channel_key] = epg[channel_key]
return sane_epg
@staticmethod
def __get_segments(xml):
root = ElTr.fromstring(xml.replace("\n", " "))
payloads = root[0][1][1].findall("{urn:dvb:ipisdns:2006}DVBBINSTP")
segment_list = {}
for segments in payloads:
source = "unknown"
try:
source = segments.attrib["Source"]
segment_list[source] = {
"Source": source,
"Port": segments.attrib["Port"],
"Address": segments.attrib["Address"],
"Segments": {},
}
for segment in segments[0]:
segment_id = segment.attrib["ID"]
segment_list[source]["Segments"][segment_id] = segment.attrib["Version"]
except KeyError:
log.debug(f"El segmento {source} no tiene la estructura correcta")
if VERBOSE:
log.info("Días de EPG: %i" % len(segment_list))
return segment_list
def __get_service_provider_ip(self):
if VERBOSE:
log.info("Buscando el Proveedor de Servicios de %s" % self.__get_demarcation_name())
data = cache.load_service_provider_data()
if not data:
xml = self.__get_xml_files(config["mcast_grp"], config["mcast_port"])["1_0"]
result = re.findall(
"DEM_" + str(config["demarcation"]) + r'\..*?Address="(.*?)".*?\s*Port="(.*?)".*?',
xml,
re.DOTALL,
)[0]
data = {"mcast_grp": result[0], "mcast_port": result[1]}
cache.save_service_provider_data(data)
if VERBOSE:
log.info("Proveedor de Servicios de %s: %s" % (self.__get_demarcation_name(), data["mcast_grp"]))
return data
def __get_xml_files(self, mc_grp, mc_port):
loop = True
max_files = 1000
_files = {}
failed = 0
first_file = ""
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(3)
s.bind((mc_grp if not WIN32 else "", int(mc_port)))
s.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(mc_grp) + socket.inet_aton(_iptv),
)
# Wait for an end chunk to start by the beginning
while True:
try:
chunk = self.__parse_chunk(s.recv(1500))
if chunk["end"]:
first_file = str(chunk["filetype"]) + "_" + str(chunk["fileid"])
break
except TimeoutError:
if threading.current_thread() == threading.main_thread():
msg = "Multicast IPTV de Movistar no detectado"
else:
msg = "Imposible descargar XML"
log.error(msg)
failed += 1
if failed == 3:
raise ValueError(msg)
# Loop until firstfile
while loop:
try:
xmldata = ""
chunk = self.__parse_chunk(s.recv(1500))
# Discard headers
body = chunk["data"]
while not (chunk["end"]):
xmldata += body
chunk = self.__parse_chunk(s.recv(1500))
body = chunk["data"]
# Discard last 4bytes binary footer?
xmldata += body[:-4]
_files[str(chunk["filetype"]) + "_" + str(chunk["fileid"])] = xmldata
# log.debug("XML: %s_%s" % (chunk["filetype"], chunk["fileid"]))
max_files -= 1
if str(chunk["filetype"]) + "_" + str(chunk["fileid"]) == first_file or max_files == 0:
if VERBOSE:
log.info(f"{mc_grp}:{mc_port} -> XML descargado")
loop = False
except Exception as ex:
log.error(f"Error al descargar los archivos XML: {repr(ex)}")
return _files
def __merge_dicts(self, dict1, dict2, path=[]):
for key in dict2:
if key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
self.__merge_dicts(dict1[key], dict2[key], path + [str(key)])
elif dict1[key] == dict2[key]:
pass
else:
raise ValueError("Conflicto en %s" % ".".join(path + [str(key)]))
else:
dict1[key] = dict2[key]
return dict1
def __parse_bin_epg(self):
merged_epg = {}
for epg_day in self.__epg:
programs = {}
for ch_id in epg_day:
if epg_day[ch_id] and "replacement" not in epg_day[ch_id]:
head = self.__parse_bin_epg_header(epg_day[ch_id])
programs[str(head["service_id"])] = self.__parse_bin_epg_body(head["data"])
self.__merge_dicts(merged_epg, programs)
log.info(f"Canales con EPG: {len(merged_epg)}")
cache.save_epg(merged_epg)
return merged_epg
def __parse_bin_epg_body(self, data):
epg_dt = data[:-4]
programs = {}
while epg_dt:
start = struct.unpack(">I", epg_dt[4:8])[0]
duration = struct.unpack(">H", epg_dt[8:10])[0]
title_end = struct.unpack("B", epg_dt[31:32])[0] + 32
episode = struct.unpack("B", epg_dt[title_end + 8 : title_end + 9])[0]
season = struct.unpack("B", epg_dt[title_end + 11 : title_end + 12])[0]
full_title = self.__decode_string(epg_dt[32:title_end])
serie_id = struct.unpack(">H", epg_dt[title_end + 5 : title_end + 7])[0]
meta_data = get_title_meta(full_title, serie_id)
programs[start] = {
"pid": struct.unpack(">I", epg_dt[:4])[0],
"start": start,
"duration": duration,
"end": start + duration,
"genre": "{:02X}".format(struct.unpack("B", epg_dt[20:21])[0]),
"age_rating": struct.unpack("B", epg_dt[24:25])[0],
"full_title": meta_data["full_title"],
"serie_id": serie_id,
"episode": meta_data["episode"] or episode,
"year": str(struct.unpack(">H", epg_dt[title_end + 9 : title_end + 11])[0]),
"serie": meta_data["serie"],
"season": meta_data["season"] or season,
"is_serie": meta_data["is_serie"],
}
if meta_data["episode_title"]:
programs[start]["episode_title"] = meta_data["episode_title"]
pr_title_end = struct.unpack("B", epg_dt[title_end + 12 : title_end + 13])[0] + title_end + 13
cut = pr_title_end or title_end
epg_dt = epg_dt[struct.unpack("B", epg_dt[cut + 3 : cut + 4])[0] + cut + 4 :]
return programs
@staticmethod
def __parse_bin_epg_header(data):
data = data.encode("latin1")
body = struct.unpack("B", data[6:7])[0] + 7
return {
"size": struct.unpack(">H", data[1:3])[0],
"service_id": struct.unpack(">H", data[3:5])[0],
"service_version": struct.unpack("B", data[5:6])[0],
"service_url": data[7:body],
"data": data[body:],
}
@staticmethod
def __parse_chunk(data):
try:
chunk = {
"end": struct.unpack("B", data[:1])[0],
"size": struct.unpack(">HB", data[1:4])[0],
"filetype": struct.unpack("B", data[4:5])[0],
"fileid": struct.unpack(">H", data[5:7])[0] & 0x0FFF,
"chunk_number": struct.unpack(">H", data[8:10])[0] >> 4,
"chunk_total": struct.unpack("B", data[10:11])[0],
"data": data[12:].decode("latin1"),
}
return chunk
except Exception as ex:
raise ValueError(f"get_chunk: error al analizar los datos {repr(ex)}")
def check_epg(self, epg):
has_errors = False
for channel in epg:
prev_end = 0
for timestamp in sorted(epg[channel]):
if prev_end > timestamp:
log.debug(f"[{channel}] {prev_end=} > {timestamp}")
has_errors = True
prev_end = epg[channel][timestamp]["end"]
return has_errors
def fix_epg(self, new_epg, cached_epg=None, broken=0, fixed=0, times=0):
epg_name = "Cached" if cached_epg else "Nuevo"
fixed_diff = fixed_over = 0
epg = cached_epg if cached_epg else new_epg
for channel in epg:
sorted_epg = sorted(epg[channel])
if cached_epg:
stales = set()
for i in range(len(sorted_epg) - 1):
timestamp = sorted_epg[i]
_start = epg[channel][timestamp]["start"]
_end = epg[channel][timestamp]["end"]
_duration = epg[channel][timestamp]["duration"]
if _duration != _end - _start:
epg[channel][timestamp]["duration"] = _end - _start
log.warning(
f"[{epg_name}] [{channel}] DIFF "
f"{timestamp} duration={_duration} -> {_end - _start}"
)
fixed_diff += 1
_next = epg[channel][sorted_epg[i + 1]]["start"]
if _end > _next:
if cached_epg:
if _next in new_epg[channel] and _start not in new_epg[channel]:
stales.add(_start)
# log.debug(f"[{channel}] {_start=} {_end=} {_next=} stale 1")
elif _start in new_epg[channel] and _next not in new_epg[channel]:
stales.add(_next)
# log.debug(f"[{channel}] {_start=} {_end=} {_next=} stale 2")
else:
log.debug(
f"[{epg_name}] [{channel}] COLLAPSE {_start}->{_end} & {_next} in EPG!!!"
)
if times > 5:
log.error(
f"[{epg_name}] [{channel}] UGLILY COERCED {_start}->{_end} TO {_next}"
)
epg[channel][timestamp]["end"] = _next
epg[channel][timestamp]["duration"] = _next - _start
else:
if _end not in epg[channel]:
log.debug(f"[{epg_name}] [{channel}] OVER {timestamp} {_end=} -> {_next=}")
epg[channel][timestamp]["end"] = _next
epg[channel][timestamp]["duration"] = _next - _start
fixed_over += 1
else:
log.error(
f"[{epg_name}] [{channel}] COLLAPSE {_start}->{_end} & {_next} in EPG!!!"
)
if cached_epg:
for timestamp in stales:
del epg[channel][timestamp]
broken += len(stales)
if cached_epg:
for channel in epg:
prev_end = prev_timestamp = 0
sorted_epg = sorted(epg[channel])
for timestamp in sorted_epg:
if prev_end > timestamp:
if (
epg[channel][prev_timestamp]["duration"] > 3600
and abs(timestamp - prev_end) < 181
):
epg[channel][prev_timestamp]["duration"] = timestamp - prev_timestamp
epg[channel][prev_timestamp]["end"] = timestamp
log.debug(
f"[{epg_name}] [{channel}] OVER "
f"{prev_timestamp} end={prev_end} -> next={timestamp}"
)
fixed_over += 1
prev_end = epg[channel][timestamp]["end"]
prev_timestamp = epg[channel][timestamp]["start"]
if self.check_epg(epg):
return self.fix_epg(new_epg, epg, broken, fixed + fixed_diff + fixed_over, times + 1)
else:
if DEBUG:
self.check_epg(epg)
if fixed_diff or fixed_over:
log.warning("El nuevo EPG contenía errores")
if fixed_diff:
_s = "programas no duraban" if fixed_diff > 1 else "programa no duraba"
log.warning(f"{fixed_diff} {_s} el tiempo hasta al siguiente programa")
if fixed_over:
_s = "programas acababan" if fixed_over > 1 else "programa acababa"
log.warning(f"{fixed_over} {_s} después de que el siguiente empezara")
else:
log.info("Nuevo EPG sin errores")
return (epg, broken, fixed + fixed_diff + fixed_over)
def get_cloud_epg(self):
return self.__drop_encrypted_channels(cache.load_cloud_epg())
def get_day(self, mcast_grp, mcast_port, source):
day = int(source.split("_")[1]) - 1
log.info("Descargando XML " + source.split(".")[0] + f" -> {mcast_grp}:{mcast_port}")
self.__epg[day] = self.__get_xml_files(mcast_grp, mcast_port)
async def get_epg(self):
cached_epg = await cache.load_epg()
if cached_epg:
cached_epg = (
self.__drop_encrypted_channels(self.__get_sane_epg(cached_epg))
if "1" in cached_epg
else self.__drop_encrypted_channels(cached_epg)
)
self.__get_bin_epg()
try:
new_epg = self.__drop_encrypted_channels(self.__get_sane_epg(self.__parse_bin_epg()))
log.info(f"Conservando {len(new_epg)} canales en abierto")
except Exception as ex:
log.debug(f"{repr(ex)}")
log.warning("Error descargando la EPG. Reintentando...")
return await self.get_epg()
clean_new_epg = {}
for channel in new_epg:
clean_new_epg[channel] = {}
for timestamp in sorted(new_epg[channel]):
clean_new_epg[channel][int(timestamp)] = new_epg[channel][timestamp]
new_epg = clean_new_epg
log.info("Comprobando si el nuevo EPG necesita arreglos...")
new_epg, broken, fixed = self.fix_epg(new_epg)
if not cached_epg:
cache.save_epg(new_epg)
log.info(f"Eventos: Arreglados = {fixed}")
return (new_epg, False)
expired = 0
log.debug(f"Fecha de caducidad: [{time.ctime(deadline)}] [{deadline}]")
for channel in new_epg:
if channel not in cached_epg:
cached_epg[channel] = {}
else:
clean_channel_epg = {}
for timestamp in sorted(cached_epg[channel]):
if cached_epg[channel][timestamp]["end"] < deadline:
expired += 1
continue