Skip to content

Commit

Permalink
u7d, epg & tvg: abort cleanly in all cases when no IPTV or no
Browse files Browse the repository at this point in the history
Multicast IPTV is detected on start

Signed-off-by: Javier Marcet <[email protected]>
  • Loading branch information
jmarcet committed Jun 15, 2022
1 parent ebcd864 commit d6b64f8
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 57 deletions.
37 changes: 19 additions & 18 deletions movistar_epg.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,20 +136,18 @@ async def before_server_start(app, loop):

@app.listener("after_server_start")
async def after_server_start(app, loop):
if _last_epg:
if 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")
else:
app.add_task(cancel_app())
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")
Expand All @@ -169,7 +167,6 @@ async def alive():

async def cancel_app():
await asyncio.sleep(1)
log.fatal("Multicast IPTV de Movistar no detectado")
if not WIN32:
os.kill(U7D_PARENT, signal.SIGTERM)
else:
Expand Down Expand Up @@ -391,7 +388,7 @@ def _prune_duplicates():

@app.get("/channels/")
async def handle_channels(request):
return response.json(_CHANNELS)
return response.json(_CHANNELS) if _CHANNELS else response.empty(404)


@app.get("/program_id/<channel_id:int>/<url>")
Expand Down Expand Up @@ -625,6 +622,8 @@ async def reload_epg():
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)
Expand Down Expand Up @@ -941,7 +940,7 @@ def _fill_cloud_event():
log.info(f"Cloud Recordings Updated => {U7D_URL}/MovistarTVCloud.m3u - {U7D_URL}/cloud.xml")


async def update_epg():
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]
Expand All @@ -955,6 +954,8 @@ async def update_epg():
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())
Expand All @@ -967,7 +968,7 @@ 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()
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())
Expand Down
61 changes: 23 additions & 38 deletions movistar_tvg.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@
"4990",
]

default_service_provider = {"mcast_grp": "239.0.2.150", "mcast_port": "3937"}

demarcations = {
"Andalucia": 15,
"Aragon": 34,
Expand Down Expand Up @@ -411,14 +409,6 @@ def __init__(self):
self.__web_service_down = False
self.__session = None

async def __get_client_profile(self):
log.info("Descargando configuración del cliente")
return await self.__get_service_data("getClientProfile")

async def __get_config_params(self):
log.info("Descargando parámetros de configuración")
return await self.__get_service_data("getConfigurationParams")

@staticmethod
def __get_end_points():
try:
Expand All @@ -430,10 +420,6 @@ 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_platform_profile(self):
log.info("Descargando perfil del servicio")
return await self.__get_service_data("getPlatformProfile")

async def __get_service_data(self, action):
if self.__web_service_down:
return
Expand Down Expand Up @@ -509,9 +495,14 @@ async def get_service_config(self):
log.info("tvPackages: %s" % cfg["tvPackages"])
log.info("Demarcation: %s" % cfg["demarcation"])
return cfg
client = await self.__get_client_profile()
platform = await self.__get_platform_profile()
params = await self.__get_config_params()
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 platform or not params:
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:
Expand Down Expand Up @@ -695,27 +686,21 @@ def __get_segments(xml):
return segment_list

def __get_service_provider_ip(self):
try:
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
except Exception as ex:
log.warning(f"Usando el Proveedor de Servicios por defecto: 239.0.2.150 {repr(ex)}")
return default_service_provider
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
Expand Down
1 change: 0 additions & 1 deletion movistar_u7d.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ async def before_server_start(app, loop):
)
break
else:
log.error("Failed to get channel list from EPG service")
await asyncio.sleep(5)
except (ClientOSError, ServerDisconnectedError):
log.debug("Waiting for EPG service...")
Expand Down

0 comments on commit d6b64f8

Please sign in to comment.