Merge pull request #474 from lopezvg/master

Cacheando los enlaces de las series y películas en la Videoteca
This commit is contained in:
Alfa
2018-10-31 14:09:41 -05:00
committed by GitHub
6 changed files with 468 additions and 220 deletions

View File

@@ -48,6 +48,20 @@
"VOSE"
]
},
{
"id": "emergency_urls",
"type": "list",
"label": "Se quieren guardar Enlaces de Emergencia por si se cae la Web?",
"default": 1,
"enabled": true,
"visible": true,
"lvalues": [
"No",
"Guardar",
"Borrar",
"Actualizar"
]
},
{
"id": "clonenewpct1_channel_default",
"type": "list",
@@ -77,7 +91,7 @@
"id": "intervenidos_channels_list",
"type": "text",
"label": "Lista de canales y clones de NewPct1 intervenidos y orden de sustitución de URLs",
"default": "('0', 'canal_org', 'canal_des', 'url_org', 'url_des', 'patron1', 'patron2', 'patron3', 'patron4', 'patron5', 'content_inc', 'content_exc', 'ow_force'), ('0', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)([^0-9]+-)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-\\d+-(Temporada-).html', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-(\\d+)-', '', 'tvshow, season', '', 'force'), ('0', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-([^.]+).html', '', '', '', 'movie', '', 'force'), ('1', 'mejortorrent', 'mejortorrent', 'http://www.mejortorrent.com/', 'http://www.mejortorrent.org/', '', '', '', '', '', '*', '', 'force'), ('1', 'plusdede', 'megadede', 'https://www.plusdede.com', 'https://www.megadede.com', '', '', '', '', '', '*', '', 'auto')",
"default": "('0', 'canal_org', 'canal_des', 'url_org', 'url_des', 'patron1', 'patron2', 'patron3', 'patron4', 'patron5', 'content_inc', 'content_exc', 'ow_force'), ('0', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)([^0-9]+-)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-\\d+-(Temporada-).html', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-(\\d+)-', '', 'tvshow, season', '', 'force'), ('0', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-([^.]+).html', '', '', '', 'movie', '', 'force'), ('0', 'mejortorrent', 'mejortorrent', 'http://www.mejortorrent.com/', 'http://www.mejortorrent.org/', '', '', '', '', '', '*', '', 'force'), ('0', 'plusdede', 'megadede', 'https://www.plusdede.com', 'https://www.megadede.com', '', '', '', '', '', '*', '', 'auto')",
"enabled": true,
"visible": false
},

View File

@@ -544,15 +544,15 @@ def listado(item):
if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie":
#Eliminamos Temporada de Series, solo nos interesa la serie completa
title = re.sub(r'-? [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r'-? [t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+', '', title)
title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r'-?\s*[t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+.*?\d+', '', title)
title = re.sub(r'\s*[t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r'\s*[t|T]emp.*?\d+', '', title)
title = re.sub(r'\s*[c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r'\s*[c|C]ap.*?\d+', '', title)
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title)
@@ -1026,15 +1026,15 @@ def listado_busqueda(item):
#Extraemos info adicional del título y la guardamos para después de TMDB
if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie":
#Eliminamos Temporada de Series, solo nos interesa la serie completa
title = re.sub(r'-? [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r'-? [t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+', '', title)
title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r'-?\s*[t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+ \d+', '', title)
title = re.sub(r'-?\s*[t|T]emp\w+.*?\d+', '', title)
title = re.sub(r'\s*[t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r'\s*[t|T]emp.*?\d+', '', title)
title = re.sub(r'\s*[c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r'\s*[c|C]ap.*?\d+', '', title)
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title)
@@ -1250,7 +1250,7 @@ def findvideos(item):
item.channel_host = host
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
verify_fo = True #Verificamos si el clone a usar está activo
verify_fo = True #Verificamos si el clone a usar está activo
item, data = generictools.fail_over_newpct1(item, verify_fo)
# Cualquiera de las tres opciones son válidas
@@ -1259,113 +1259,115 @@ def findvideos(item):
item.url = item.url.replace(".com/", ".com/descarga-torrent/")
#Función para limitar la verificación de enlaces de Servidores para Ver online y Descargas
try:
#Inicializamos las variables por si hay un error en medio del proceso
channel_exclude = []
ver_enlaces = []
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
if not item.videolibray_emergency_urls: #Si es un proceso nomal...
try:
#Inicializamos las variables por si hay un error en medio del proceso
channel_exclude = []
ver_enlaces = []
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
#Leemos las opciones de permitir Servidores para Ver Online y Descargas
#Cargamos en .json del canal para ver las listas de valores en settings
channel_exclude = channeltools.get_channel_json(item.channel)
for settings in channel_exclude['settings']: #Se recorren todos los settings
if settings['id'] == "clonenewpct1_excluir1_enlaces_veronline": #lista de enlaces a excluir
max_excl = int(settings['max_excl']) #Máximo número de servidores excluidos
channel_exclude = settings['lvalues'] #Cargamos la lista de servidores
if settings['id'] == "clonenewpct1_ver_enlaces_descargas": #Número de enlances a ver o verificar
ver_enlaces = settings['lvalues'] #Cargamos la lista de num. de enlaces
#Leemos las opciones de permitir Servidores para Ver Online y Descargas
#Cargamos en .json del canal para ver las listas de valores en settings
channel_exclude = channeltools.get_channel_json(item.channel)
for settings in channel_exclude['settings']: #Se recorren todos los settings
if settings['id'] == "clonenewpct1_excluir1_enlaces_veronline": #lista de enlaces a excluir
max_excl = int(settings['max_excl']) #Máximo número de servidores excluidos
channel_exclude = settings['lvalues'] #Cargamos la lista de servidores
if settings['id'] == "clonenewpct1_ver_enlaces_descargas": #Número de enlances a ver o verificar
ver_enlaces = settings['lvalues'] #Cargamos la lista de num. de enlaces
#Primer loop para enlaces de Ver Online.
#Carga la variable de ver
ver_enlaces_veronline = int(config.get_setting("clonenewpct1_ver_enlaces_veronline", item.channel))
if ver_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_veronline = -1
if ver_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_veronline = int(ver_enlaces[ver_enlaces_veronline])
#Carga la variable de verificar
verificar_enlaces_veronline = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline", item.channel))
if verificar_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_veronline = -1
if verificar_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_veronline = int(ver_enlaces[verificar_enlaces_veronline])
#Primer loop para enlaces de Ver Online.
#Carga la variable de ver
ver_enlaces_veronline = int(config.get_setting("clonenewpct1_ver_enlaces_veronline", item.channel))
if ver_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_veronline = -1
if ver_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_veronline = int(ver_enlaces[ver_enlaces_veronline])
#Carga la variable de verificar
verificar_enlaces_veronline = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline", item.channel))
if verificar_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_veronline = -1
if verificar_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_veronline = int(ver_enlaces[verificar_enlaces_veronline])
#Carga la variable de contar sólo los servidores verificados
verificar_enlaces_veronline_validos = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline_validos", item.channel))
#Carga la variable de contar sólo los servidores verificados
verificar_enlaces_veronline_validos = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline_validos", item.channel))
#Carga la variable de lista de servidores excluidos
x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_veronline" % x, item.channel))
valor = int(valor)
if valor > 0: #Evitamos "No"
excluir_enlaces_veronline += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1
#Carga la variable de lista de servidores excluidos
x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_veronline" % x, item.channel))
valor = int(valor)
if valor > 0: #Evitamos "No"
excluir_enlaces_veronline += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1
#Segundo loop para enlaces de Descargar.
#Carga la variable de ver
ver_enlaces_descargas = int(config.get_setting("clonenewpct1_ver_enlaces_descargas", item.channel))
if ver_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_descargas = -1
if ver_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_descargas = int(ver_enlaces[ver_enlaces_descargas])
#Carga la variable de verificar
verificar_enlaces_descargas = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas", item.channel))
if verificar_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_descargas = -1
if verificar_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_descargas = int(ver_enlaces[verificar_enlaces_descargas])
#Segundo loop para enlaces de Descargar.
#Carga la variable de ver
ver_enlaces_descargas = int(config.get_setting("clonenewpct1_ver_enlaces_descargas", item.channel))
if ver_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_descargas = -1
if ver_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_descargas = int(ver_enlaces[ver_enlaces_descargas])
#Carga la variable de verificar
verificar_enlaces_descargas = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas", item.channel))
if verificar_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_descargas = -1
if verificar_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_descargas = int(ver_enlaces[verificar_enlaces_descargas])
#Carga la variable de contar sólo los servidores verificados
verificar_enlaces_descargas_validos = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas_validos", item.channel))
#Carga la variable de contar sólo los servidores verificados
verificar_enlaces_descargas_validos = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas_validos", item.channel))
#Carga la variable de lista de servidores excluidos
x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_descargas" % x, item.channel))
valor = int(valor)
if valor > 0: #Evitamos "No"
excluir_enlaces_descargas += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1
#Carga la variable de lista de servidores excluidos
x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_descargas" % x, item.channel))
valor = int(valor)
if valor > 0: #Evitamos "No"
excluir_enlaces_descargas += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1
except Exception, ex: #En caso de error, lo mostramos y reseteamos todas las variables
logger.error("Error en la lectura de parámentros del .json del canal: " + item.channel + " \n%s" % ex)
#Mostrar los errores
logger.error(ver_enlaces_veronline)
logger.error(verificar_enlaces_veronline)
logger.error(verificar_enlaces_veronline_validos)
logger.error(excluir_enlaces_veronline)
logger.error(ver_enlaces_descargas)
logger.error(verificar_enlaces_descargas)
logger.error(verificar_enlaces_descargas_validos)
logger.error(excluir_enlaces_descargas)
#Resetear las variables a sus valores por defecto
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
except Exception, ex: #En caso de error, lo mostramos y reseteamos todas las variables
logger.error("Error en la lectura de parámentros del .json del canal: " + item.channel + " \n%s" % ex)
#Mostrar los errores
logger.error(ver_enlaces_veronline)
logger.error(verificar_enlaces_veronline)
logger.error(verificar_enlaces_veronline_validos)
logger.error(excluir_enlaces_veronline)
logger.error(ver_enlaces_descargas)
logger.error(verificar_enlaces_descargas)
logger.error(verificar_enlaces_descargas_validos)
logger.error(excluir_enlaces_descargas)
#Resetear las variables a sus valores por defecto
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
# Descarga la página
data = ''
data_servidores = ''
try:
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data)
data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures")
url_servidores = item.url
category_servidores = item.category
data_servidores = data #salvamos data para verificar servidores, si es necesario
except:
data_servidores = data #salvamos data para verificar servidores, si es necesario
except: #La web no responde. Probemos las urls de emergencia
pass
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
@@ -1375,15 +1377,20 @@ def findvideos(item):
if not data or not scrapertools.find_single_match(data, patron):
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error
return itemlist #Salimos
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el vídeo
item, data = generictools.fail_over_newpct1(item, patron)
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error
if item.emergency_urls: #Hay urls de emergencia?
item.url = item.emergency_urls[0] #Guardamos la url del .Torrent
enlaces_ver = item.emergency_urls[1] #Guardamos los datos iniciales de los Servidores Directos
item.armagedon = True #Marcamos la situación como catastrófica
else:
return itemlist #Salimos
else:
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el vídeo
item, data = generictools.fail_over_newpct1(item, patron)
if not data: #Si no ha logrado encontrar nada, verificamos si hay servidores
if not data: #Si no ha logrado encontrar nada, verificamos si hay servidores
cnt_servidores = 0
item.category = category_servidores #restauramos valores originales
item.url = url_servidores
@@ -1395,8 +1402,8 @@ def findvideos(item):
enlaces_ver = re.compile(patron, re.DOTALL).findall(data_servidores)
enlaces_descargar = enlaces_ver
for logo, servidor, idioma, calidad, enlace, title in enlaces_ver: #buscamos enlaces de servidores de ver-online
if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque
for logo, servidor, idioma, calidad, enlace, title in enlaces_ver: #buscamos enlaces de servidores de ver-online
if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque
break
if "ver" in title.lower():
cnt_servidores += 1
@@ -1407,14 +1414,20 @@ def findvideos(item):
#Miramos si ha servidores
if not data_servidores: #Si no ha logrado encontrar nada nos vamos
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: FINDVIDEOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
if item.emergency_urls: #Hay urls de emergencia?
item.url = str(item.emergency_urls[0]).replace ("'", "").replace ("[", "").replace ("]", "") #Guardamos la url del .Torrent
enlaces_ver = item.emergency_urls[1] #Guardamos los datos iniciales de los Servidores Directos
item.armagedon = True #Marcamos la situación como catastrófica
else:
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: FINDVIDEOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
data = data_servidores #restauramos los datos
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures")
#buscamos el tamaño del .torrent
size = scrapertools.find_single_match(data, '<div class="entry-left".*?><a href=".*?span class=.*?>Size:<\/strong>?\s(\d+?\.?\d*?\s\w[b|B])<\/span>')
if not size: #Para planetatorrent
size = scrapertools.find_single_match(data, '<div class="fichas-box"><div class="entry-right"><div style="[^"]+"><span class="[^"]+"><strong>Size:<\/strong>?\s(\d+?\.?\d*?\s\w[b|B])<\/span>')
@@ -1435,57 +1448,72 @@ def findvideos(item):
#Generamos una copia de Item para trabajar sobre ella
item_local = item.clone()
# obtenemos la url torrent
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not scrapertools.find_single_match(data, patron):
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
item_local.url = scrapertools.find_single_match(data, patron)
if not item_local.url: #error
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
item_local.url = item_local.url.replace(" ", "%20") #sustituimos espacios por %20, por si acaso
#logger.debug("Patron: " + patron + " url: " + item_local.url)
#logger.debug(data)
#Ahora pintamos el link del Torrent, si lo hay
if item_local.url: # Hay Torrent ?
if size:
quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título
else:
quality = item_local.quality
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent
#Preparamos título y calidad, quitamos etiquetas vacías
item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)
item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
item_local.title = item_local.title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', quality)
quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', quality)
item_local.quality = quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Servidor
itemlist_t.append(item_local.clone()) #Pintar pantalla, si no se filtran idiomas
# Requerido para FilterTools
if config.get_setting('filter_languages', channel_py) > 0: #Si hay idioma seleccionado, se filtra
itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language) #Pintar pantalla, si no está vacío
# obtenemos la url torrent o usamos la de emergencia
if not item.armagedon: #Si es un proceso normal, seguimos
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not scrapertools.find_single_match(data, patron):
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
item_local.url = scrapertools.find_single_match(data, patron)
if not item_local.url: #error
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
if item.emergency_urls: #Hay urls de emergencia?
item.url = item.emergency_urls[0] #Guardamos la url del .Torrent
item.armagedon = True #Marcamos la situación como catastrófica
item_local.url = item_local.url.replace(" ", "%20") #sustituimos espacios por %20, por si acaso
#logger.debug("Patron: " + patron + " url: " + item_local.url)
#logger.debug(data)
logger.debug("TORRENT: " + item_local.url + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
#logger.debug(item_local)
#Si es un lookup para cargar las urls de emergencia en la Videoteca...
if item.videolibray_emergency_urls:
item.emergency_urls = []
url = item_local.url
if url == 'javascript:;': #No hay torrent...
url = '' #... ignorar
item.emergency_urls.append([url])
#... si no, ejecutamos el proceso normal
else:
#Ahora pintamos el link del Torrent, si lo hay
if item_local.url: # Hay Torrent ?
if size:
quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título
else:
quality = item_local.quality
if item.armagedon: #Si es catastrófico, lo marcamos
quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % quality
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent
#Preparamos título y calidad, quitamos etiquetas vacías
item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)
item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
item_local.title = item_local.title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', quality)
quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', quality)
item_local.quality = quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Servidor
itemlist_t.append(item_local.clone()) #Pintar pantalla, si no se filtran idiomas
# Requerido para FilterTools
if config.get_setting('filter_languages', channel_py) > 0: #Si hay idioma seleccionado, se filtra
itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language) #Pintar pantalla, si no está vacío
logger.debug("TORRENT: " + item_local.url + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
#logger.debug(item_local)
if len(itemlist_f) > 0: #Si hay entradas filtradas...
itemlist.extend(itemlist_f) #Pintamos pantalla filtrada
else:
if config.get_setting('filter_languages', channel_py) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
thumb_separador = get_thumb("next.png") #... pintamos todo con aviso
itemlist.append(Item(channel=item.channel, url=host, title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", thumbnail=thumb_separador))
itemlist.extend(itemlist_t) #Pintar pantalla con todo si no hay filtrado
if len(itemlist_f) > 0: #Si hay entradas filtradas...
itemlist.extend(itemlist_f) #Pintamos pantalla filtrada
else:
if config.get_setting('filter_languages', channel_py) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
thumb_separador = get_thumb("next.png") #... pintamos todo con aviso
itemlist.append(Item(channel=item.channel, url=host, title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", thumbnail=thumb_separador))
itemlist.extend(itemlist_t) #Pintar pantalla con todo si no hay filtrado
itemlist_t = [] #Itemlist total de enlaces
itemlist_f = [] #Itemlist de enlaces filtrados
itemlist_t = [] #Itemlist total de enlaces
itemlist_f = [] #Itemlist de enlaces filtrados
# VER vídeos, descargar vídeos un link, o múltiples links
data = scrapertools.find_single_match(data, '<div id="tab1" class="tab_content"(.*?<\/ul>(?:<div.*?>)?<\/div><\/div><\/div>)') #Seleccionar el bloque para evitar duplicados
@@ -1498,10 +1526,27 @@ def findvideos(item):
patron += '<\/div[^<]+<div class="box4">([^<]+)?<\/div[^<]+<div class="box5"><a href=(.*?)? rel.*?'
patron += '<\/div[^<]+<div class="box6">([^<]+)?<'
enlaces_ver = re.compile(patron, re.DOTALL).findall(data)
if not item.armagedon: #Si es un proceso normal, seguimos
enlaces_ver = re.compile(patron, re.DOTALL).findall(data)
if not enlaces_ver and item.emergency_urls[1]: #Si no hay enlaces, hay urls de emergencia?
enlaces_ver = item.emergency_urls[1] #Guardamos los datos iniciales de los Servidores Directos
item.armagedon = True #Activamos el modo catástrofe
enlaces_descargar = enlaces_ver
#logger.debug(enlaces_ver)
#Si es un lookup para cargar las urls de emergencia en la Videoteca, lo hacemos y nos vamos si más
if item.videolibray_emergency_urls:
emergency_urls_directos = []
i = 0
for logo, servidor, idioma, calidad, enlace, title in enlaces_ver:
if "ver" in title.lower():
emergency_urls_directos.append(enlaces_ver[i])
i += 1
item.emergency_urls.append(emergency_urls_directos)
return item
#Recorre todos los links de VER, si está permitido
cnt_enl_ver = 1
cnt_enl_verif = 1
@@ -1548,14 +1593,16 @@ def findvideos(item):
else:
break #Si se ha agotado el contador de verificación, se sale de Ver Online
if item.armagedon: #Si es catastrófico, lo marcamos
item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
#Si el link no está activo se ignora
if "??" in item_local.alive: #dudoso
if "??" in item_local.alive: #dudoso
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), item_local.quality, str(item_local.language))
elif "no" in item_local.alive.lower(): #No está activo. Lo preparo, pero no lo pinto
elif "no" in item_local.alive.lower(): #No está activo. Lo preparo, pero no lo pinto
item_local.title = '[COLOR red][%s][/COLOR] [COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.alive, servidor.capitalize(), item_local.quality, str(item_local.language))
logger.debug(item_local.alive + ": ALIVE / " + title + " / " + servidor + " / " + enlace)
raise
else: #Sí está activo
else: #Sí está activo
item_local.title = '[COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), item_local.quality, str(item_local.language))
#Preparamos el resto de variables de Item para ver los vídeos en directo
@@ -1827,6 +1874,7 @@ def episodios(item):
list_pages = [item.url]
season = max_temp
first = True
#Comprobamos si realmente sabemos el num. máximo de temporadas
if item.library_playcounts or (item.infoLabels['number_of_seasons'] and item.tmdb_stat):
num_temporadas_flag = True
@@ -1971,12 +2019,16 @@ def episodios(item):
item_local.contentEpisodeNumber = match['episode']
if match["episode2"]: #Hay episodio dos? es una entrada múltiple?
item_local.title = "%sx%s al %s -" % (str(match["season"]), str(match["episode"]).zfill(2), str(match["episode2"]).zfill(2)) #Creamos un título con el rango de episodios
item_local.title = "%sx%s al %s -" % (str(match["season"]), str(match["episode"]).zfill(2), str(match["episode2"]).zfill(2)) #Creamos un título con el rango de episodios
else: #Si es un solo episodio, se formatea ya
item_local.title = "%sx%s -" % (match["season"], str(match["episode"]).zfill(2))
if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca
if item_local.contentSeason < max_temp:
if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca
if first: #Si es el primer episodio, comprobamos que ...
first = False
if item_local.contentSeason < max_temp: #... la temporada sea la última ...
modo_ultima_temp_alt = False #... si no, por seguridad leeremos toda la serie
if item_local.contentSeason < max_temp and modo_ultima_temp_alt:
list_pages = [] #Sale del bucle de leer páginas
break #Sale del bucle actual del FOR de episodios por página
#if ('%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))) in item.library_playcounts:

View File

@@ -452,7 +452,7 @@ def findvideos(item):
data_subtitle = scrapertools.find_single_match(data_subtitle, patron)
patron = '<tr class="fichserietabla_b">.*?<a href="([^"]+)"'
subtitles = re.compile(patron, re.DOTALL).findall(data_subtitle) #Creamos una lista con todos los sub-títulos
if subtitles and len(subtitles) > 1: #Solo se guarda si hay más de un idioma. Si no, automático
if subtitles:
item.subtitle = []
for subtitle in subtitles:
subtitle = subtitle.replace('&#038;', '&').replace('.io/', sufix).replace('.com/', sufix)

View File

@@ -12,6 +12,7 @@ from core import scrapertools
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools
from lib import generictools
FOLDER_MOVIES = config.get_setting("folder_movies")
FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
@@ -182,6 +183,19 @@ def save_movie(item):
else:
insertados += 1
# Si se ha marcado la opción de url de emergencia, se añade ésta a la película después de haber ejecutado Findvideos del canal
try:
channel = generictools.verify_channel(item.channel)
if config.get_setting("emergency_urls", channel) in [1, 3]:
item = emergency_urls(item)
if item_nfo.emergency_urls and not isinstance(item_nfo.emergency_urls, dict):
del item_nfo.emergency_urls
if not item_nfo.emergency_urls:
item_nfo.emergency_urls = dict()
item_nfo.emergency_urls.update({item.channel: True})
except:
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % item.contentTitle)
if filetools.write(json_path, item.tojson()):
p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
item_nfo.library_urls[item.channel] = item.url
@@ -309,6 +323,7 @@ def save_tvshow(item, episodelist):
if item.channel != "downloads":
item_tvshow.active = 1 # para que se actualice a diario cuando se llame a videolibrary_service
filetools.write(tvshow_path, head_nfo + item_tvshow.tojson())
if not episodelist:
@@ -377,6 +392,10 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
p_dialog = platformtools.dialog_progress(config.get_localized_string(20000), config.get_localized_string(60064))
p_dialog.update(0, config.get_localized_string(60065))
channel_alt = generictools.verify_channel(serie.channel) #Preparamos para añadir las urls de emergencia
emergency_urls_stat = config.get_setting("emergency_urls", channel_alt) #El canal quiere urls de emergencia?
emergency_urls_succ = False
channel = __import__('channels.%s' % channel_alt, fromlist=["channels.%s" % channel_alt])
new_episodelist = []
# Obtenemos el numero de temporada y episodio y descartamos los q no lo sean
tags = []
@@ -385,13 +404,39 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
for e in episodelist:
if tags != [] and tags != None and any(tag in e.title.lower() for tag in tags):
continue
try:
season_episode = scrapertools.get_season_and_episode(e.title)
# Si se ha marcado la opción de url de emergencia, se añade ésta a cada episodio después de haber ejecutado Findvideos del canal
if e.emergency_urls and isinstance(e.emergency_urls, dict): del e.emergency_urls #Borramos trazas anterioires
if emergency_urls_stat == 1 and not e.emergency_urls and e.contentType == 'episode': #Guardamos urls de emergencia?
json_path = filetools.join(path, ("%s [%s].json" % (season_episode, e.channel)).lower()) #Path del .json del episodio
if json_path in ficheros: #Si existe el .json sacamos de ahí las urls
if overwrite: #pero solo si se se sobrescriben los .json
json_epi = Item().fromjson(filetools.read(json_path)) #Leemos el .json
if json_epi.emergency_urls: #si existen las urls de emergencia...
e.emergency_urls = json_epi.emergency_urls #... las copiamos
else: #y si no...
e = emergency_urls(e, channel) #... las generamos
else:
e = emergency_urls(e, channel) #Si el episodio no existe, generamos las urls
if e.emergency_urls: #Si ya tenemos urls...
emergency_urls_succ = True #... es un éxito y vamos a marcar el .nfo
elif emergency_urls_stat == 2 and e.contentType == 'episode': #Borramos urls de emergencia?
if e.emergency_urls: del e.emergency_urls
emergency_urls_succ = True #... es un éxito y vamos a marcar el .nfo
elif emergency_urls_stat == 3 and e.contentType == 'episode': #Actualizamos urls de emergencia?
e = emergency_urls(e, channel) #generamos las urls
if e.emergency_urls: #Si ya tenemos urls...
emergency_urls_succ = True #... es un éxito y vamos a marcar el .nfo
e.infoLabels = serie.infoLabels
e.contentSeason, e.contentEpisodeNumber = season_episode.split("x")
new_episodelist.append(e)
except:
if e.contentType == 'episode':
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle)
continue
# No hay lista de episodios, no hay nada que guardar
@@ -495,7 +540,19 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
import datetime
head_nfo, tvshow_item = read_nfo(tvshow_path)
tvshow_item.library_playcounts.update(news_in_playcounts)
#Si la operación de insertar/borrar urls de emergencia en los .jsons de los episodios ha tenido éxito, se marca el .nfo
if emergency_urls_succ:
if tvshow_item.emergency_urls and not isinstance(tvshow_item.emergency_urls, dict):
del tvshow_item.emergency_urls
if emergency_urls_stat in [1, 3]: #Operación de guardar/actualizar enlaces
if not tvshow_item.emergency_urls:
tvshow_item.emergency_urls = dict()
tvshow_item.emergency_urls.update({serie.channel: True})
elif emergency_urls_stat == 2: #Operación de Borrar enlaces
if tvshow_item.emergency_urls and tvshow_item.emergency_urls.get(serie.channel, False):
tvshow_item.emergency_urls.pop(serie.channel, None) #borramos la entrada del .nfo
if tvshow_item.active == 30:
tvshow_item.active = 1
update_last = datetime.date.today()
@@ -506,6 +563,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
filetools.write(tvshow_path, head_nfo + tvshow_item.tojson())
except:
logger.error("Error al actualizar tvshow.nfo")
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % tvshow_item.contentSerieName)
fallidos = -1
else:
# ... si ha sido correcto actualizamos la videoteca de Kodi
@@ -546,11 +604,10 @@ def add_movie(item):
#Si lo hace en "Completar Información", cambia parcialmente al nuevo título, pero no busca en TMDB. Hay que hacerlo
#Si se cancela la segunda pantalla, la variable "scraper_return" estará en False. El usuario no quiere seguir
from lib import generictools
item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
#if item.tmdb_stat:
# del item.tmdb_stat #Limpiamos el status para que no se grabe en la Videoteca
new_item = item.clone(action="findvideos")
insertados, sobreescritos, fallidos = save_movie(new_item)
@@ -614,7 +671,6 @@ def add_tvshow(item, channel=None):
#Si lo hace en "Completar Información", cambia parcialmente al nuevo título, pero no busca en TMDB. Hay que hacerlo
#Si se cancela la segunda pantalla, la variable "scraper_return" estará en False. El usuario no quiere seguir
from lib import generictools
item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
#if item.tmdb_stat:
# del item.tmdb_stat #Limpiamos el status para que no se grabe en la Videoteca
@@ -653,3 +709,24 @@ def add_tvshow(item, channel=None):
xbmc_videolibrary.sync_trakt_kodi()
# Se lanza la sincronización para la videoteca del addon
xbmc_videolibrary.sync_trakt_addon(path)
def emergency_urls(item, channel=None):
"""
Llamamos a Findvideos del canal con la variable "item.videolibray_emergency_urls = True" para obtener la variable
"item.matches" con la lista de listas de tuplas de los enlaces torrent y de servidores directos para ese episodio o película
"""
try:
if channel == None:
channel = generictools.verify_channel(item.channel)
channel = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel])
if hasattr(channel, 'findvideos'):
item.videolibray_emergency_urls = True
item_res = getattr(channel, 'findvideos')(item)
del item_res.videolibray_emergency_urls
except:
item_res = item.clone()
#logger.debug(item_res.emergency_urls)
return item_res

View File

@@ -294,6 +294,8 @@ def post_tmdb_listado(item, itemlist):
del item_local.url_alt
if item_local.extra2:
del item_local.extra2
if item_local.library_filter_show:
del item_local.library_filter_show
#Ajustamos el nombre de la categoría
if item_local.channel == channel_py:
@@ -508,6 +510,11 @@ def post_tmdb_seasons(item, itemlist):
itemlist_temporadas = []
itemlist_fo = []
if config.get_setting("no_pile_on_seasons", 'videolibrary') == 2: #Si no se quiere mostrar por temporadas, nos vamos...
if item.season_colapse: #Quitamos el indicador de listado por Temporadas
del item.season_colapse
return (item, itemlist)
#Restauramos valores si ha habido fail-over
channel_alt = ''
if item.channel == channel_py:
@@ -555,7 +562,8 @@ def post_tmdb_seasons(item, itemlist):
title = title.replace('[', '-').replace(']', '-').replace('.', ',').strip()
title = title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
itemlist_temporadas.append(item_season.clone(title=title, from_title_season_colapse=item.title))
if config.get_setting("show_all_seasons", 'videolibrary'):
itemlist_temporadas.append(item_season.clone(title=title, from_title_season_colapse=item.title))
#Repasamos todos los episodios para detectar las diferentes temporadas
for item_local in itemlist:
@@ -566,8 +574,8 @@ def post_tmdb_seasons(item, itemlist):
item_season.title = 'Temporada %s' % item_season.contentSeason
itemlist_temporadas.append(item_season.clone(from_title_season_colapse=item.title))
#Si hay más de una temporada se sigue, si no se devuelve el Itemlist original
if len(itemlist_temporadas) > 2:
#Si hay más de una temporada se sigue, o se ha forzado a listar por temporadas, si no se devuelve el Itemlist original
if len(itemlist_temporadas) > 2 or config.get_setting("no_pile_on_seasons", 'videolibrary') == 0:
for item_local in itemlist_temporadas:
if "** Todas las Temporadas" in item_local.title: #Si es el título de TODAS las Temporadas, lo ignoramos
continue
@@ -708,6 +716,8 @@ def post_tmdb_episodios(item, itemlist):
del item.from_action
if item.from_channel:
del item.from_channel
if item.library_filter_show:
del item.library_filter_show
for item_local in itemlist: #Recorremos el Itemlist generado por el canal
if item_local.add_videolibrary:
@@ -742,6 +752,10 @@ def post_tmdb_episodios(item, itemlist):
del item_local.from_action
if item_local.from_channel:
del item_local.from_channel
if item_local.emergency_urls and isinstance(item_local.emergency_urls, dict):
del item_local.emergency_urls
if item_local.library_filter_show:
del item_local.library_filter_show
#logger.debug(item_local)
#Ajustamos el nombre de la categoría si es un clone de NewPct1
@@ -977,9 +991,6 @@ def post_tmdb_findvideos(item, itemlist):
"""
#logger.debug(item)
#Creción de título general del vídeo a visualizar en Findvideos
itemlist = []
# Saber si estamos en una ventana emergente lanzada desde una viñeta del menú principal,
# con la función "play_from_library"
item.unify = False
@@ -993,6 +1004,9 @@ def post_tmdb_findvideos(item, itemlist):
if item.contentSeason_save: #Restauramos el num. de Temporada
item.contentSeason = item.contentSeason_save
del item.contentSeason_save
if item.library_filter_show:
del item.library_filter_show
#Salvamos la información de max num. de episodios por temporada para despues de TMDB
num_episodios = item.contentEpisodeNumber
@@ -1022,6 +1036,9 @@ def post_tmdb_findvideos(item, itemlist):
if item.channel == channel_py:
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
if item.armagedon: #Es una situación catastrófica?
itemlist.append(item.clone(action='', title=item.category + ': [COLOR hotpink]VIDEOTECA: Usando enlaces de emergencia[/COLOR]'))
#Quitamos el la categoría o nombre del título, si lo tiene
if item.contentTitle:
item.contentTitle = re.sub(r' -%s-' % item.category, '', item.contentTitle)
@@ -1154,10 +1171,10 @@ def post_tmdb_findvideos(item, itemlist):
#agregamos la opción de Añadir a Videoteca para péliculas (no series)
if (item.contentType == 'movie' or item.contentType == 'season') and item.contentChannel != "videolibrary":
#Permitimos la actualización de los títulos, bien para uso inmediato, o para añadir a la videoteca
itemlist.append(item.clone(title="** [COLOR yelow]Actualizar Títulos - vista previa videoteca[/COLOR] **", action="actualizar_titulos", extra="películas", tmdb_stat=False, from_action=item.action, from_title_tmdb=item.title, from_update=True))
itemlist.append(item.clone(title="** [COLOR yelow]Actualizar Títulos - vista previa videoteca[/COLOR] **", action="actualizar_titulos", extra="peliculas", tmdb_stat=False, from_action=item.action, from_title_tmdb=item.title, from_update=True))
if item.contentType == 'movie' and item.contentChannel != "videolibrary":
itemlist.append(item.clone(title="**-[COLOR yellow] Añadir a la videoteca [/COLOR]-**", action="add_pelicula_to_library", extra="películas", from_action=item.action, from_title_tmdb=item.title))
itemlist.append(item.clone(title="**-[COLOR yellow] Añadir a la videoteca [/COLOR]-**", action="add_pelicula_to_library", extra="peliculas", from_action=item.action, from_title_tmdb=item.title))
#Añadimos la opción de ver trailers
if item.contentChannel != "videolibrary":
@@ -1280,14 +1297,14 @@ def get_torrent_size(url):
size = convert_size(sizet)
except:
logger.error('ERROR al buscar el tamaño de un .Torrent: ' + url)
logger.error('ERROR al buscar el tamaño de un .Torrent: ' + str(url))
try:
os.remove(torrents_path + "/generictools.torrent") #borramos el .torrent
except:
pass
#logger.debug(url + ' / ' + size)
#logger.debug(str(url) + ' / ' + str(size))
return size
@@ -1552,6 +1569,20 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
return (item, data)
def verify_channel(channel):
#Lista con los datos de los canales alternativos
#Cargamos en .json del canal para ver las listas de valores en settings
clones = channeltools.get_channel_json(channel_py)
for settings in clones['settings']: #Se recorren todos los settings
if settings['id'] == "clonenewpct1_channels_list": #Encontramos en setting
clones = settings['default'] #Carga lista de clones
channel_alt = "'%s'" % channel
if channel_alt in clones: #Si es un clon se pone como canal newpct1, si no se deja
channel = channel_py
return channel
def web_intervenida(item, data, desactivar=True):
logger.info()
@@ -1663,24 +1694,27 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
- patron4: expresión Regex aplicable a la url (opcional)
- patron5: expresión Regex aplicable a la url (opcional)
- content_inc: contenido al que aplica esta entrada, o * (item.contentType o item.extra)
- content_exc: contenido que se excluye de esta entrada (item.contentType) (opcional)
- content_exc: contenido que se excluye de esta entrada (item.contentType) (opcional). opción para 'emerg'
- ow_force: indicador para la acción de "videolibrary_service.py". Puede crear la variable item.ow_force:
- force: indica al canal que analize toda la serie y que videolibrary_service la reescriba
- auto: indica a videolibrary_service que la reescriba
- no: no acción para videolibrary_service, solo redirige en visionado de videolibrary
- del: borra las estrucuturas de un determinado canal en videolibrary_service, quizás creadas por errores de un canal
- emerg: funcionalidad muy similar a la de "del". se general dinámicamente cada vez que entra un canal con el estado activado en el .json de "emergency_urls". Permite cargar las urls de emergencia en todos los elementos existentes de la Videoteca para canal afectado
ejemplos:
('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)([^0-9]+-)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-\\d+-(Temporada-).html', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-(\\d+)-', '', 'tvshow, season', '', 'force'),
('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-([^.]+).html', '', '', '', 'movie', '', 'force')",
('1', 'torrentrapid', 'torrentlocura', 'http://torrentrapid.com/', 'http://torrentlocura.com/', '', '', '', '', '', '*', '', 'no'),
('1', 'newpct1', '', '', '', '', '', '', '', '', '*', '', 'del'),
('1', 'torrentrapid', 'torrentrapid', '', '', '', '', '', '', '', '*', '1 ó 2', 'emerg'),
La llamada recibe el parámetro Item, el .nfo y los devuleve actualizados, así como opcionalmente el parámetro "overwrite· que puede forzar la reescritura de todos los archivos de la serie, y el parámetro "path" si viene de videolibrary_service. Por último, recibe opcionalmente el parámetro "lookup" si se quiere solo averigurar si habrá migración para ese título, pero sin realizarla.
"""
#logger.debug(item)
#if it != None: logger.debug(it)
if not it:
it = Item()
#logger.debug(item)
ow_force_param = True
channel_enabled = False
update_stat = 0
@@ -1721,28 +1755,59 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if channel_alt != 'videolibrary':
item.category = channel_alt.capitalize()
category = "'%s'" % channel_alt
channel_py_alt = ''
channel_py_alt = 'xyz123'
if channel in fail_over_list : #Si es un clone de Newpct1, se actualiza el canal y la categoría
item.channel = channel_py
channel_py_alt = "'%s'" % channel_py
if item.channel_host: #y se borran resto de pasadas anteriores
del item.channel_host
#Ahora tratamos las webs intervenidas, tranformamos la url, el nfo y borramos los archivos obsoletos de la serie
if channel not in intervencion and channel_py_alt not in intervencion and category not in intervencion and channel_alt != 'videolibrary': #lookup
return (item, it, overwrite) #... el canal/clone está listado
#Analizamos si hay series o películas que migrar, debido a que se ha activado en el .json del canal la opción "guardar"
#"emergency_urls = 1", y hay que calcularla para todos los episodios y película existentes en la Videoteca.
#Si "emergency_urls" está activada para uno o más canales, se verifica en el .nfo del vídeo si ya se ha realizado
#la carga de las urls de emergencia. Sí se ha hecho, se ignora el proceso de conversión. Si no, se convierte por el
#canal en curso cuando hay item.url, o para todos los canales en item.library_urls si no hay un canal específico en curso.
#El mecanismo consiste en generar una regla temporal de migración para cada canal activado. Esta regla actua borrando
#todos los .json de la serie/película. En el caso de la serie, el proceso de actualización de la videoteca los regenerará
#automáticamente. En el caso de peliculas, se general aquí el json actualizado y se marca el .nfo como actualizado.
#Cuando en el .json se activa "Borrar", "emergency_urls = 2", se borran todos los enlaces existentes
#Cuando en el .json se activa "Actualizar", "emergency_urls = 3", se actualizan todos los enlaces existentes
if it.emergency_urls:
item.emergency_urls = it.emergency_urls #Refrescar desde el .nfo
if item.url: #Viene de actualización de videoteca de series
#Analizamos si el canal ya tiene las urls de emergencia: guardar o borrar
if (config.get_setting("emergency_urls", item.channel) == 1 and (not item.emergency_urls or (item.emergency_urls and not item.emergency_urls.get(channel_alt, False)))) or (config.get_setting("emergency_urls", item.channel) == 2 and item.emergency_urls.get(channel_alt, False)) or config.get_setting("emergency_urls", item.channel) == 3:
intervencion += ", ('1', '%s', '%s', '', '', '', '', '', '', '', '*', '%s', 'emerg')" % (channel_alt, channel_alt, config.get_setting("emergency_urls", item.channel))
elif it.library_urls: #Viene de "listar peliculas´"
for canal_vid, url_vid in it.library_urls.items(): #Se recorre "item.library_urls" para buscar canales candidatos
canal_vid_alt = "'%s'" % canal_vid
if canal_vid_alt in fail_over_list: #Se busca si es un clone de newpct1
channel_bis = channel_py
else:
channel_bis = canal_vid
#Analizamos si el canal ya tiene las urls de emergencia: guardar o borrar
if (config.get_setting("emergency_urls", channel_bis) == 1 and (not it.emergency_urls or (it.emergency_urls and not it.emergency_urls.get(canal_vid, False)))) or (config.get_setting("emergency_urls", channel_bis) == 2 and it.emergency_urls.get(canal_vid, False)) or config.get_setting("emergency_urls", channel_bis) == 3:
intervencion += ", ('1', '%s', '%s', '', '', '', '', '', '', '', '*', '%s', 'emerg')" % (canal_vid, canal_vid, config.get_setting("emergency_urls", channel_bis))
#Ahora tratamos las webs intervenidas, tranformamos la url, el nfo y borramos los archivos obsoletos de la serie
if channel not in intervencion and channel_py_alt not in intervencion and category not in intervencion and channel_alt != 'videolibrary': #lookup
return (item, it, overwrite) #... el canal/clone está listado
import ast
intervencion_list = ast.literal_eval(intervencion) #Convertir a Array el string
#logger.debug(intervencion_list)
if lookup == True:
overwrite = False #Solo avisamos si hay cambios
for activo, canal_org, canal_des, url_org, url_des, patron1, patron2, patron3, patron4, patron5, content_inc, content_exc, ow_force in intervencion_list:
opt = ''
#Es esta nuestra entrada?
if activo == '1' and (canal_org == channel_alt or canal_org == item.channel or channel_alt == 'videolibrary' or ow_force == 'del'):
if activo == '1' and (canal_org == channel_alt or canal_org == item.channel or channel_alt == 'videolibrary' or ow_force == 'del' or ow_force == 'emerg'):
if ow_force == 'del': #Si es un borrado de estructuras erroneas, hacemos un proceso aparte
if ow_force == 'del' or ow_force == 'emerg': #Si es un borrado de estructuras erroneas, hacemos un proceso aparte
canal_des_def = canal_des #Si hay canal de sustitución para item.library_urls, lo usamos
if not canal_des_def and canal_org in item.library_urls and len(item.library_urls) == 1: #Si no, lo extraemos de la url
canal_des_def = scrapertools.find_single_match(item.library_urls[canal_org], 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').lower() #salvamos la url actual de la estructura a borrar
@@ -1762,7 +1827,7 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
url_total_status = True #marcamos esta url como válida
overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas
if len(item.library_urls) > 1:
if len(item.library_urls) > 1 and ow_force == 'del':
item.library_urls.pop(canal_org, None) #borramos la url del canal a borrar
overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas
@@ -1783,7 +1848,8 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if lookup == False: #si es migración completa...
delete_stat += 1 #Ya hemos actualizado algo, o habrá que hacerlo...
canal_org_des_list += [(canal_org, canal_des, url_total, ow_force)] #salvamos el resultado para su proceso
if ow_force == 'emerg': opt = content_exc #Salvamos la opción de Guardar o Borrar enlaces
canal_org_des_list += [(canal_org, canal_des, url_total, opt, ow_force)] #salvamos el resultado para su proceso
else:
if channel_alt == 'videolibrary': #Viene de videolibrary.list_movies: IMPRESCINDIBLE
@@ -1837,15 +1903,15 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if url:
url_total = url #Guardamos la suma de los resultados intermedios
update_stat += 1 #Ya hemos actualizado algo
canal_org_des_list += [(canal_org, canal_des, url_total, ow_force)] #salvamos el resultado para su proceso
canal_org_des_list += [(canal_org, canal_des, url_total, opt, ow_force)] #salvamos el resultado para su proceso
if update_stat > 0 or delete_stat > 0: #Ha habido alguna actualización o borrado? Entonces salvamos
if (update_stat > 0 and path != False) or item.ow_force == '1':
logger.error('** Lista de Actualizaciones a realizar: ' + str(canal_org_des_list))
for canal_org_def, canal_des_def, url_total, ow_force_def in canal_org_des_list: #pasamos por todas las "parejas" cambiadas
if ow_force_def != 'del':
for canal_org_def, canal_des_def, url_total, opt_def, ow_force_def in canal_org_des_list: #pasamos por todas las "parejas" cambiadas
if ow_force_def != 'del' and ow_force_def != 'emerg':
url_total_def = url_total
if item.channel == channel_py or channel in fail_over_list: #Si es Newpct1...
if (item.channel == channel_py or channel in fail_over_list): #Si es Newpct1...
if item.contentType == "tvshow":
url_total_def = re.sub(r'\/\d+\/?$', '', url_total) #parece que con el título encuentra la serie, normalmente...
if item.url:
@@ -1871,30 +1937,57 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
# Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno
canal_erase_list = []
from core import videolibrarytools
raiz, carpetas_series, ficheros = filetools.walk(path).next()
ficheros = [filetools.join(path, f) for f in ficheros] #Almacenamos la lista de archivos de la carpeta
#logger.error(ficheros)
for archivo in ficheros:
for canal_org_def, canal_des_def, url_total, ow_force_def in canal_org_des_list: #pasamos por todas las "parejas" a borrar
for canal_org_def, canal_des_def, url_total, opt_def, ow_force_def in canal_org_des_list: #pasamos por las "parejas" a borrar
canal_erase = '[%s]' % canal_org_def
canal_erase_alt = "'%s'" % canal_org_def
canal_new = '[%s]' % canal_des_def
if canal_erase in archivo: #Borramos los .json que sean de los canal afectados
if canal_des_def:
archivo_alt = "'%s'" % scrapertools.find_single_match(archivo, '\[(\w+)\].json')
if archivo_alt == "''": archivo_alt = "'xyz123'"
#logger.error(canal_erase + canal_new + archivo + archivo_alt)
#Borramos los .json que sean de los canal afectados, incluidos todos los de los clones de newpct1 si éste es el canal
if canal_erase in archivo or (ow_force_def == 'emerg' and canal_erase_alt in fail_over_list and archivo_alt in fail_over_list):
if canal_des_def and it.contentType == 'movie': #Si es película ...
item_json = Item().fromjson(filetools.read(archivo)) #leemos el .json ante de borrarlo para salvar...
title = item_json.title #... el título con su formato
language = item_json.language #... los idiomas, que no están en el .nfo
wanted = item_json.wanted #... y wanted con el título original
json_path = archivo.replace(canal_erase, canal_new) #Salvamos el path del .json para luego crearlo
json_path_list += [(canal_org_def, canal_des_def, url_total, json_path, title, language, wanted)]
emer_urls = ''
if ow_force_def == 'emerg' and opt_def in ['1', '3']: #Si era una op. para añadir/actualizar urls de emergencia ...
item_json = videolibrarytools.emergency_urls(item_json) #... ejecutamos "findvideos" del canal para obtenerlas
if item_json.emergency_urls: #... si las hay ...
emer_urls = item_json.emergency_urls #... lo preparamos para el .json
if it.emergency_urls and not isinstance(it.emergency_urls, dict):
del it.emergency_urls
if not it.emergency_urls: #... lo actualizamos en el .nfo
it.emergency_urls = dict() #... iniciamos la variable si no existe
it.emergency_urls.update({canal_des_def: True}) #... se marca como activo
else:
continue #Si no hay url, pasamos al siguiente, sin borrar el .json
if ow_force_def == 'emerg' and opt_def == '2': #Si era una operación para borrar urls de emergencia ...
emer_urls = '2' #borramos enlaces
if it.emergency_urls and not isinstance(it.emergency_urls, dict):
del it.emergency_urls
if it.emergency_urls and it.emergency_urls.get(item_json.channel, False):
it.emergency_urls.pop(item_json.channel, None) #borramos la entrada del .nfo
json_path_list += [(canal_org_def, canal_des_def, url_total, json_path, title, language, wanted, emer_urls)]
filetools.remove(archivo) #Borramos el .json
logger.error('** BORRAMOS: ' + str(archivo))
if ow_force_def == 'del': #Si la función es 'del' ...
if ow_force_def == 'del' or ow_force_def == 'emerg': #Si la función es 'del' or 'emerg' ...
overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas
#Si se ha cambiado algo, se actualizan los .nfo
if item.contentType == "movie" and ".nfo" in archivo:
if item.contentType == "movie" and ".nfo" in archivo: #Para películas
if it.ow_force: del it.ow_force
filetools.write(archivo, head_nfo + it.tojson()) #escribo el .nfo de la peli por si aborta update
filetools.write(archivo, head_nfo + it.tojson()) #escribo el .nfo de la peli
if item.contentType != "movie" and "tvshow.nfo" in archivo:
filetools.write(archivo, head_nfo + it.tojson()) #escribo el tvshow.nfo por si aborta update
@@ -1908,15 +2001,17 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
del item_movie.library_urls
del item_movie.nfo
del item_movie.path
del item_movie.strm_path
del item_movie.text_color
if item_movie.strm_path: del item_movie.strm_path
if item_movie.text_color: del item_movie.text_color
if not item_movie.context: item_movie.context = "['buscar_trailer']"
if not item_movie.extra: item_movie.extra = "peliculas"
if json_path_list:
logger.error('** .json LIST: ' + str(json_path_list))
for canal_org_def, canal_des_def, url_total, json_path, title, language, wanted in json_path_list: #pasamos por todas canales
for canal_org_def, canal_des_def, url_total, json_path, title, language, wanted, emer_urls in json_path_list: #pasamos por todos canales
logger.error('** ESCRIBIMOS: ' + json_path)
item_movie.emergency_urls = False
del item_movie.emergency_urls
item_movie.channel = canal_des_def #mombre del canal migrado
if not item_movie.category: item_movie.category = canal_des_def.capitalize() #categoría
item_movie.url = url_total #url migrada
@@ -1924,10 +2019,17 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if language: item_movie.language = language #restaurmos los idiomas
if wanted: item_movie.wanted = wanted #restaurmos wanted
item_movie.added_replacing = canal_org_def #guardamos la traza del canal reemplazado
if emer_urls == '2': #si estamos borrando urls de emergencia ...
if item_movie.emergency_urls:
del item_movie.emergency_urls #... las borramos
elif emer_urls: #si estamos añadiendo urls de emergencia ...
item_movie.emergency_urls = emer_urls #... las copiamos al .json
filetools.write(json_path, item_movie.tojson()) #Salvamos el nuevo .json de la película
if (update_stat > 0 and path != False and ow_force_def in ['force', 'auto']) or item.ow_force == '1' or len(json_path_list) > 0:
logger.error('ITEM cambiado')
if it.emergency_urls:
logger.error(it.emergency_urls)
logger.error(item)
return (item, it, overwrite)

View File

@@ -25,6 +25,9 @@ def update(path, p_dialog, i, t, serie, overwrite):
###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
try:
head_nfo, it = videolibrarytools.read_nfo(path + '/tvshow.nfo') #Refresca el .nfo para recoger actualizaciones
if it.emergency_urls:
serie.emergency_urls = it.emergency_urls
serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite)
except:
pass