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
+15 -1
View File
@@ -48,6 +48,20 @@
"VOSE" "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", "id": "clonenewpct1_channel_default",
"type": "list", "type": "list",
@@ -77,7 +91,7 @@
"id": "intervenidos_channels_list", "id": "intervenidos_channels_list",
"type": "text", "type": "text",
"label": "Lista de canales y clones de NewPct1 intervenidos y orden de sustitución de URLs", "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, "enabled": true,
"visible": false "visible": false
}, },
+74 -22
View File
@@ -544,15 +544,15 @@ def listado(item):
if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie": 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 #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'-?\s*[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'-?\s*[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'-?\s*[t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+', '', title) title = re.sub(r'-?\s*[t|T]emp\w+ \d+', '', title)
title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title) title = re.sub(r'-?\s*[t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title) title = re.sub(r'\s*[t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title) title = re.sub(r'\s*[t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title) title = re.sub(r'\s*[c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\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 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_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) 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 #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": 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 #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'-?\s*[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'-?\s*[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'-?\s*[t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r'-? [t|T]emp\w+ \d+', '', title) title = re.sub(r'-?\s*[t|T]emp\w+ \d+', '', title)
title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title) title = re.sub(r'-?\s*[t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title) title = re.sub(r'\s*[t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title) title = re.sub(r'\s*[t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title) title = re.sub(r'\s*[c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\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 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_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) title = re.sub(r'\[[a|A]udio.*?\]', '', title)
@@ -1259,6 +1259,7 @@ def findvideos(item):
item.url = item.url.replace(".com/", ".com/descarga-torrent/") 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 #Función para limitar la verificación de enlaces de Servidores para Ver online y Descargas
if not item.videolibray_emergency_urls: #Si es un proceso nomal...
try: try:
#Inicializamos las variables por si hay un error en medio del proceso #Inicializamos las variables por si hay un error en medio del proceso
channel_exclude = [] channel_exclude = []
@@ -1359,13 +1360,14 @@ def findvideos(item):
# Descarga la página # Descarga la página
data = '' data = ''
data_servidores = ''
try: try:
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data) data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data)
data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures") data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures")
url_servidores = item.url url_servidores = item.url
category_servidores = item.category category_servidores = item.category
data_servidores = data #salvamos data para verificar servidores, si es necesario data_servidores = data #salvamos data para verificar servidores, si es necesario
except: except: #La web no responde. Probemos las urls de emergencia
pass pass
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
@@ -1376,8 +1378,13 @@ def findvideos(item):
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente 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 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 return itemlist #Salimos
else:
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data) 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 #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
@@ -1407,6 +1414,11 @@ def findvideos(item):
#Miramos si ha servidores #Miramos si ha servidores
if not data_servidores: #Si no ha logrado encontrar nada nos vamos 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="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
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')) 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
@@ -1415,6 +1427,7 @@ def findvideos(item):
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8") data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures") 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>') 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 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>') 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,23 +1448,38 @@ def findvideos(item):
#Generamos una copia de Item para trabajar sobre ella #Generamos una copia de Item para trabajar sobre ella
item_local = item.clone() item_local = item.clone()
# obtenemos la url torrent # 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 patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not scrapertools.find_single_match(data, patron): if not scrapertools.find_single_match(data, patron):
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent) patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
item_local.url = scrapertools.find_single_match(data, patron) item_local.url = scrapertools.find_single_match(data, patron)
if not item_local.url: #error 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) 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 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("Patron: " + patron + " url: " + item_local.url)
#logger.debug(data) #logger.debug(data)
#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 #Ahora pintamos el link del Torrent, si lo hay
if item_local.url: # Hay Torrent ? if item_local.url: # Hay Torrent ?
if size: if size:
quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título
else: else:
quality = item_local.quality 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 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 #Preparamos título y calidad, quitamos etiquetas vacías
@@ -1498,10 +1526,27 @@ def findvideos(item):
patron += '<\/div[^<]+<div class="box4">([^<]+)?<\/div[^<]+<div class="box5"><a href=(.*?)? rel.*?' patron += '<\/div[^<]+<div class="box4">([^<]+)?<\/div[^<]+<div class="box5"><a href=(.*?)? rel.*?'
patron += '<\/div[^<]+<div class="box6">([^<]+)?<' patron += '<\/div[^<]+<div class="box6">([^<]+)?<'
if not item.armagedon: #Si es un proceso normal, seguimos
enlaces_ver = re.compile(patron, re.DOTALL).findall(data) 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 enlaces_descargar = enlaces_ver
#logger.debug(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 #Recorre todos los links de VER, si está permitido
cnt_enl_ver = 1 cnt_enl_ver = 1
cnt_enl_verif = 1 cnt_enl_verif = 1
@@ -1548,6 +1593,8 @@ def findvideos(item):
else: else:
break #Si se ha agotado el contador de verificación, se sale de Ver Online 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 #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)) 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))
@@ -1827,6 +1874,7 @@ def episodios(item):
list_pages = [item.url] list_pages = [item.url]
season = max_temp season = max_temp
first = True
#Comprobamos si realmente sabemos el num. máximo de temporadas #Comprobamos si realmente sabemos el num. máximo de temporadas
if item.library_playcounts or (item.infoLabels['number_of_seasons'] and item.tmdb_stat): if item.library_playcounts or (item.infoLabels['number_of_seasons'] and item.tmdb_stat):
num_temporadas_flag = True num_temporadas_flag = True
@@ -1976,7 +2024,11 @@ def episodios(item):
item_local.title = "%sx%s -" % (match["season"], str(match["episode"]).zfill(2)) 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 modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca
if item_local.contentSeason < max_temp: 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 list_pages = [] #Sale del bucle de leer páginas
break #Sale del bucle actual del FOR de episodios por página 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: #if ('%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))) in item.library_playcounts:
+1 -1
View File
@@ -452,7 +452,7 @@ def findvideos(item):
data_subtitle = scrapertools.find_single_match(data_subtitle, patron) data_subtitle = scrapertools.find_single_match(data_subtitle, patron)
patron = '<tr class="fichserietabla_b">.*?<a href="([^"]+)"' 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 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 = [] item.subtitle = []
for subtitle in subtitles: for subtitle in subtitles:
subtitle = subtitle.replace('&#038;', '&').replace('.io/', sufix).replace('.com/', sufix) subtitle = subtitle.replace('&#038;', '&').replace('.io/', sufix).replace('.com/', sufix)
+79 -2
View File
@@ -12,6 +12,7 @@ from core import scrapertools
from core.item import Item from core.item import Item
from platformcode import config, logger from platformcode import config, logger
from platformcode import platformtools from platformcode import platformtools
from lib import generictools
FOLDER_MOVIES = config.get_setting("folder_movies") FOLDER_MOVIES = config.get_setting("folder_movies")
FOLDER_TVSHOWS = config.get_setting("folder_tvshows") FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
@@ -182,6 +183,19 @@ def save_movie(item):
else: else:
insertados += 1 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()): if filetools.write(json_path, item.tojson()):
p_dialog.update(100, 'Añadiendo película...', item.contentTitle) p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
item_nfo.library_urls[item.channel] = item.url item_nfo.library_urls[item.channel] = item.url
@@ -309,6 +323,7 @@ def save_tvshow(item, episodelist):
if item.channel != "downloads": if item.channel != "downloads":
item_tvshow.active = 1 # para que se actualice a diario cuando se llame a videolibrary_service 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()) filetools.write(tvshow_path, head_nfo + item_tvshow.tojson())
if not episodelist: 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 = platformtools.dialog_progress(config.get_localized_string(20000), config.get_localized_string(60064))
p_dialog.update(0, config.get_localized_string(60065)) 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 = [] new_episodelist = []
# Obtenemos el numero de temporada y episodio y descartamos los q no lo sean # Obtenemos el numero de temporada y episodio y descartamos los q no lo sean
tags = [] tags = []
@@ -385,13 +404,39 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
for e in episodelist: for e in episodelist:
if tags != [] and tags != None and any(tag in e.title.lower() for tag in tags): if tags != [] and tags != None and any(tag in e.title.lower() for tag in tags):
continue continue
try: try:
season_episode = scrapertools.get_season_and_episode(e.title) 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.infoLabels = serie.infoLabels
e.contentSeason, e.contentEpisodeNumber = season_episode.split("x") e.contentSeason, e.contentEpisodeNumber = season_episode.split("x")
new_episodelist.append(e) new_episodelist.append(e)
except: except:
if e.contentType == 'episode':
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle)
continue continue
# No hay lista de episodios, no hay nada que guardar # No hay lista de episodios, no hay nada que guardar
@@ -496,6 +541,18 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
head_nfo, tvshow_item = read_nfo(tvshow_path) head_nfo, tvshow_item = read_nfo(tvshow_path)
tvshow_item.library_playcounts.update(news_in_playcounts) 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: if tvshow_item.active == 30:
tvshow_item.active = 1 tvshow_item.active = 1
update_last = datetime.date.today() 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()) filetools.write(tvshow_path, head_nfo + tvshow_item.tojson())
except: except:
logger.error("Error al actualizar tvshow.nfo") 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 fallidos = -1
else: else:
# ... si ha sido correcto actualizamos la videoteca de Kodi # ... si ha sido correcto actualizamos la videoteca de Kodi
@@ -546,7 +604,6 @@ 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 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 #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 item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
#if item.tmdb_stat: #if item.tmdb_stat:
# del item.tmdb_stat #Limpiamos el status para que no se grabe en la Videoteca # del item.tmdb_stat #Limpiamos el status para que no se grabe en la Videoteca
@@ -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 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 #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 item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
#if item.tmdb_stat: #if item.tmdb_stat:
# del item.tmdb_stat #Limpiamos el status para que no se grabe en la Videoteca # 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() xbmc_videolibrary.sync_trakt_kodi()
# Se lanza la sincronización para la videoteca del addon # Se lanza la sincronización para la videoteca del addon
xbmc_videolibrary.sync_trakt_addon(path) 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
+132 -30
View File
@@ -294,6 +294,8 @@ def post_tmdb_listado(item, itemlist):
del item_local.url_alt del item_local.url_alt
if item_local.extra2: if item_local.extra2:
del 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 #Ajustamos el nombre de la categoría
if item_local.channel == channel_py: if item_local.channel == channel_py:
@@ -508,6 +510,11 @@ def post_tmdb_seasons(item, itemlist):
itemlist_temporadas = [] itemlist_temporadas = []
itemlist_fo = [] 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 #Restauramos valores si ha habido fail-over
channel_alt = '' channel_alt = ''
if item.channel == channel_py: if item.channel == channel_py:
@@ -555,6 +562,7 @@ def post_tmdb_seasons(item, itemlist):
title = title.replace('[', '-').replace(']', '-').replace('.', ',').strip() title = title.replace('[', '-').replace(']', '-').replace('.', ',').strip()
title = title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip() title = title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
if config.get_setting("show_all_seasons", 'videolibrary'):
itemlist_temporadas.append(item_season.clone(title=title, from_title_season_colapse=item.title)) itemlist_temporadas.append(item_season.clone(title=title, from_title_season_colapse=item.title))
#Repasamos todos los episodios para detectar las diferentes temporadas #Repasamos todos los episodios para detectar las diferentes temporadas
@@ -566,8 +574,8 @@ def post_tmdb_seasons(item, itemlist):
item_season.title = 'Temporada %s' % item_season.contentSeason item_season.title = 'Temporada %s' % item_season.contentSeason
itemlist_temporadas.append(item_season.clone(from_title_season_colapse=item.title)) 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 #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: if len(itemlist_temporadas) > 2 or config.get_setting("no_pile_on_seasons", 'videolibrary') == 0:
for item_local in itemlist_temporadas: 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 if "** Todas las Temporadas" in item_local.title: #Si es el título de TODAS las Temporadas, lo ignoramos
continue continue
@@ -708,6 +716,8 @@ def post_tmdb_episodios(item, itemlist):
del item.from_action del item.from_action
if item.from_channel: if item.from_channel:
del 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 for item_local in itemlist: #Recorremos el Itemlist generado por el canal
if item_local.add_videolibrary: if item_local.add_videolibrary:
@@ -742,6 +752,10 @@ def post_tmdb_episodios(item, itemlist):
del item_local.from_action del item_local.from_action
if item_local.from_channel: if item_local.from_channel:
del 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) #logger.debug(item_local)
#Ajustamos el nombre de la categoría si es un clone de NewPct1 #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) #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, # Saber si estamos en una ventana emergente lanzada desde una viñeta del menú principal,
# con la función "play_from_library" # con la función "play_from_library"
item.unify = False item.unify = False
@@ -994,6 +1005,9 @@ def post_tmdb_findvideos(item, itemlist):
item.contentSeason = item.contentSeason_save item.contentSeason = item.contentSeason_save
del 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 #Salvamos la información de max num. de episodios por temporada para despues de TMDB
num_episodios = item.contentEpisodeNumber num_episodios = item.contentEpisodeNumber
if item.infoLabels['temporada_num_episodios'] and item.contentEpisodeNumber <= item.infoLabels['temporada_num_episodios']: if item.infoLabels['temporada_num_episodios'] and item.contentEpisodeNumber <= item.infoLabels['temporada_num_episodios']:
@@ -1022,6 +1036,9 @@ def post_tmdb_findvideos(item, itemlist):
if item.channel == channel_py: if item.channel == channel_py:
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize() 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 #Quitamos el la categoría o nombre del título, si lo tiene
if item.contentTitle: if item.contentTitle:
item.contentTitle = re.sub(r' -%s-' % item.category, '', 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) #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": 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 #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": 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 #Añadimos la opción de ver trailers
if item.contentChannel != "videolibrary": if item.contentChannel != "videolibrary":
@@ -1280,14 +1297,14 @@ def get_torrent_size(url):
size = convert_size(sizet) size = convert_size(sizet)
except: 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: try:
os.remove(torrents_path + "/generictools.torrent") #borramos el .torrent os.remove(torrents_path + "/generictools.torrent") #borramos el .torrent
except: except:
pass pass
#logger.debug(url + ' / ' + size) #logger.debug(str(url) + ' / ' + str(size))
return size return size
@@ -1552,6 +1569,20 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
return (item, data) 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): def web_intervenida(item, data, desactivar=True):
logger.info() 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) - patron4: expresión Regex aplicable a la url (opcional)
- patron5: 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_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: - 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 - force: indica al canal que analize toda la serie y que videolibrary_service la reescriba
- auto: indica a videolibrary_service que la reescriba - auto: indica a videolibrary_service que la reescriba
- no: no acción para videolibrary_service, solo redirige en visionado de videolibrary - 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 - 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: 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.?-[^-]+-(?:[^-]+-)([^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', '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', 'torrentrapid', 'torrentlocura', 'http://torrentrapid.com/', 'http://torrentlocura.com/', '', '', '', '', '', '*', '', 'no'),
('1', 'newpct1', '', '', '', '', '', '', '', '', '*', '', 'del'), ('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. 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: if not it:
it = Item() it = Item()
#logger.debug(item)
ow_force_param = True ow_force_param = True
channel_enabled = False channel_enabled = False
update_stat = 0 update_stat = 0
@@ -1721,13 +1755,43 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if channel_alt != 'videolibrary': if channel_alt != 'videolibrary':
item.category = channel_alt.capitalize() item.category = channel_alt.capitalize()
category = "'%s'" % channel_alt 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 if channel in fail_over_list : #Si es un clone de Newpct1, se actualiza el canal y la categoría
item.channel = channel_py item.channel = channel_py
channel_py_alt = "'%s'" % channel_py channel_py_alt = "'%s'" % channel_py
if item.channel_host: #y se borran resto de pasadas anteriores if item.channel_host: #y se borran resto de pasadas anteriores
del item.channel_host del item.channel_host
#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 #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 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 return (item, it, overwrite) #... el canal/clone está listado
@@ -1739,10 +1803,11 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
if lookup == True: if lookup == True:
overwrite = False #Solo avisamos si hay cambios 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: 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? #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 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 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 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 url_total_status = True #marcamos esta url como válida
overwrite = True #Le decimos que sobreescriba todos los .jsons overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas 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 item.library_urls.pop(canal_org, None) #borramos la url del canal a borrar
overwrite = True #Le decimos que sobreescriba todos los .jsons overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas 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... if lookup == False: #si es migración completa...
delete_stat += 1 #Ya hemos actualizado algo, o habrá que hacerlo... 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: else:
if channel_alt == 'videolibrary': #Viene de videolibrary.list_movies: IMPRESCINDIBLE 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: if url:
url_total = url #Guardamos la suma de los resultados intermedios url_total = url #Guardamos la suma de los resultados intermedios
update_stat += 1 #Ya hemos actualizado algo 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 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': if (update_stat > 0 and path != False) or item.ow_force == '1':
logger.error('** Lista de Actualizaciones a realizar: ' + str(canal_org_des_list)) 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 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': if ow_force_def != 'del' and ow_force_def != 'emerg':
url_total_def = url_total 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": if item.contentType == "tvshow":
url_total_def = re.sub(r'\/\d+\/?$', '', url_total) #parece que con el título encuentra la serie, normalmente... url_total_def = re.sub(r'\/\d+\/?$', '', url_total) #parece que con el título encuentra la serie, normalmente...
if item.url: 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 # Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno
canal_erase_list = [] canal_erase_list = []
from core import videolibrarytools
raiz, carpetas_series, ficheros = filetools.walk(path).next() 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 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 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 = '[%s]' % canal_org_def
canal_erase_alt = "'%s'" % canal_org_def
canal_new = '[%s]' % canal_des_def canal_new = '[%s]' % canal_des_def
if canal_erase in archivo: #Borramos los .json que sean de los canal afectados archivo_alt = "'%s'" % scrapertools.find_single_match(archivo, '\[(\w+)\].json')
if canal_des_def: 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... 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 title = item_json.title #... el título con su formato
language = item_json.language #... los idiomas, que no están en el .nfo language = item_json.language #... los idiomas, que no están en el .nfo
wanted = item_json.wanted #... y wanted con el título original 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 = 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 filetools.remove(archivo) #Borramos el .json
logger.error('** BORRAMOS: ' + str(archivo)) 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 overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas item.ow_force = '1' #Le decimos que revise todas las temporadas
#Si se ha cambiado algo, se actualizan los .nfo #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 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: if item.contentType != "movie" and "tvshow.nfo" in archivo:
filetools.write(archivo, head_nfo + it.tojson()) #escribo el tvshow.nfo por si aborta update 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.library_urls
del item_movie.nfo del item_movie.nfo
del item_movie.path del item_movie.path
del item_movie.strm_path if item_movie.strm_path: del item_movie.strm_path
del item_movie.text_color if item_movie.text_color: del item_movie.text_color
if not item_movie.context: item_movie.context = "['buscar_trailer']" if not item_movie.context: item_movie.context = "['buscar_trailer']"
if not item_movie.extra: item_movie.extra = "peliculas" if not item_movie.extra: item_movie.extra = "peliculas"
if json_path_list: if json_path_list:
logger.error('** .json LIST: ' + str(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) 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 item_movie.channel = canal_des_def #mombre del canal migrado
if not item_movie.category: item_movie.category = canal_des_def.capitalize() #categoría if not item_movie.category: item_movie.category = canal_des_def.capitalize() #categoría
item_movie.url = url_total #url migrada 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 language: item_movie.language = language #restaurmos los idiomas
if wanted: item_movie.wanted = wanted #restaurmos wanted if wanted: item_movie.wanted = wanted #restaurmos wanted
item_movie.added_replacing = canal_org_def #guardamos la traza del canal reemplazado 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 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: 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') logger.error('ITEM cambiado')
if it.emergency_urls:
logger.error(it.emergency_urls)
logger.error(item) logger.error(item)
return (item, it, overwrite) return (item, it, overwrite)
@@ -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 ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
try: 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) serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite)
except: except:
pass pass