Merge pull request #486 from lopezvg/master
Mejoras en el cacheo de urls de emergencia y en la disponiblidad de los clones de Newpct1
This commit is contained in:
@@ -599,7 +599,7 @@ def findvideos(item):
|
||||
item_local.url = scrapedurl
|
||||
if host not in item_local.url and host.replace('https', 'http') not in item_local.url and not item.armagedon:
|
||||
item_local.url = host + item_local.url
|
||||
if item_local.url and not item.armagedon:
|
||||
if item_local.url and not item.armagedon and item.emergency_urls:
|
||||
item_local.torrent_alt = item.emergency_urls[0][0] #Guardamos la url del .Torrent ALTERNATIVA
|
||||
if item.armagedon: #Si es catastrófico, lo marcamos
|
||||
item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
|
||||
|
||||
@@ -398,7 +398,7 @@ def findvideos(item):
|
||||
if item.armagedon: #Si es catastrófico, lo marcamos
|
||||
item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
|
||||
item_local.url = link_torrent
|
||||
if item_local.url and not item.armagedon:
|
||||
if item_local.url and item.emergency_urls and not item.armagedon:
|
||||
item_local.torrent_alt = item.emergency_urls[0][0] #Guardamos la url del .Torrent ALTERNATIVA
|
||||
|
||||
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language)) #Preparamos título de Torrent
|
||||
|
||||
@@ -47,6 +47,28 @@
|
||||
"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": "emergency_urls_torrents",
|
||||
"type": "bool",
|
||||
"label": "Se quieren guardar Torrents de Emergencia por si se cae la Web?",
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"visible": "!eq(-1,'No')"
|
||||
},
|
||||
{
|
||||
"id": "timeout_downloadpage",
|
||||
"type": "list",
|
||||
|
||||
@@ -657,7 +657,6 @@ def findvideos(item):
|
||||
if not data_torrent and not data_directo:
|
||||
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url)
|
||||
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': 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
|
||||
|
||||
patron = '<div class="content"><a href="([^"]+).*?'
|
||||
patron += '(?:<div class="content_medium">(.*?)<\/div>.*?)?'
|
||||
@@ -665,13 +664,26 @@ def findvideos(item):
|
||||
matches_torrent = re.compile(patron, re.DOTALL).findall(data_torrent)
|
||||
matches_directo = re.compile(patron, re.DOTALL).findall(data_directo)
|
||||
if not matches_torrent and not matches_directo and scrapertools.find_single_match(data_directo, '<div id="where_i_am".*?<a href="[^"]+">Ver Online<\/a>.*?href="([^"]+)">') != url: #error
|
||||
logger.error("ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web " + " / PATRON: " + patron)
|
||||
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web. Verificar en la Web esto último y reportar el error con el log'))
|
||||
if data_torrent:
|
||||
logger.error(data_torrent)
|
||||
if data_directo:
|
||||
logger.error(data_directo)
|
||||
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
|
||||
|
||||
if item.emergency_urls and not item.videolibray_emergency_urls: #Hay urls de emergencia?
|
||||
matches_torrent = item.emergency_urls[1] #Guardamos los matches de los .Torrents
|
||||
try:
|
||||
matches_directo = item.emergency_urls[3] #Guardamos los matches de Directos, si los hay
|
||||
except:
|
||||
pass
|
||||
item.armagedon = True #Marcamos la situación como catastrófica
|
||||
else:
|
||||
if len(itemlist) == 0:
|
||||
logger.error("ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web " + " / PATRON: " + patron)
|
||||
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web. Verificar en la Web esto último y reportar el error con el log'))
|
||||
if data_torrent:
|
||||
logger.error(data_torrent)
|
||||
if data_directo:
|
||||
logger.error(data_directo)
|
||||
if item.videolibray_emergency_urls:
|
||||
return item
|
||||
else:
|
||||
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
|
||||
|
||||
#logger.debug("PATRON: " + patron)
|
||||
#logger.debug(matches_torrent)
|
||||
@@ -679,8 +691,17 @@ def findvideos(item):
|
||||
#logger.debug(data_torrent)
|
||||
#logger.debug(data_directo)
|
||||
|
||||
if item.videolibray_emergency_urls:
|
||||
item.emergency_urls = [] #Iniciamos emergency_urls
|
||||
item.emergency_urls.append([]) #Reservamos el espacio para los .torrents locales
|
||||
item.emergency_urls.append(matches_torrent) #Guardamos los matches_torrent iniciales
|
||||
item.emergency_urls.append([]) #Reservamos el espacio para los matches_torrent finales
|
||||
item.emergency_urls.append(matches_directo) #Guardamos los matches_directo iniciales
|
||||
item.emergency_urls.append([]) #Reservamos el espacio para los matches_directo finales
|
||||
|
||||
#Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
|
||||
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
|
||||
if not item.videolibray_emergency_urls:
|
||||
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
|
||||
|
||||
#Si es un Episodio suelto, tratamos de poner un enlace a la Serie completa
|
||||
if item.extra3 == 'completa':
|
||||
@@ -702,7 +723,7 @@ def findvideos(item):
|
||||
item_local.contentType = 'tvshow'
|
||||
item_local.extra = 'series'
|
||||
item_local.action = 'episodios'
|
||||
item_local.season_colapse = True #Muestra las series agrupadas por temporadas
|
||||
item_local.season_colapse = True #Muestra las series agrupadas por temporadas
|
||||
|
||||
#Buscamos la url de la serie y verificamos que existe
|
||||
patron_serie = '<div class="linkMoreMovies"><div class="linkMore"><a href="([^"]+)">'
|
||||
@@ -741,106 +762,130 @@ def findvideos(item):
|
||||
item_local.language = ["%s" % IDIOMAS[scrapedlang]]
|
||||
|
||||
#Leemos la página definitiva para el enlace al .torrent
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url, timeout=timeout).data)
|
||||
except:
|
||||
pass
|
||||
|
||||
patron = '<div class="linksDescarga"><span class="titulo">Descargar Torrent: <\/span><br><a href="([^"]+)" class="TTlink">»\s?(.*?)\s?«<\/a>'
|
||||
matches = re.compile(patron, re.DOTALL).findall(data)
|
||||
data = ''
|
||||
if not item.armagedon:
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url, timeout=timeout).data)
|
||||
except:
|
||||
pass
|
||||
|
||||
patron = '<div class="linksDescarga"><span class="titulo">Descargar Torrent: <\/span><br><a href="([^"]+)" class="TTlink">»\s?(.*?)\s?«<\/a>'
|
||||
matches = re.compile(patron, re.DOTALL).findall(data)
|
||||
else:
|
||||
matches = item.emergency_urls[2][0] #Guardamos los matches de Directos, si los hay
|
||||
del item.emergency_urls[2][0] #Una vez tratado lo limpiamos
|
||||
data = 'xyz123' #iniciamos data para que no dé problemas
|
||||
|
||||
if item.videolibray_emergency_urls: #Si esyamos añadiendo a Videoteca...
|
||||
item.emergency_urls[2].append(matches) #Salvamos este matches
|
||||
|
||||
if not data or not matches:
|
||||
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / URL: " + item_local.url + " / DATA: " + data)
|
||||
continue #si no hay más datos, algo no funciona, pasamos a Ver Online
|
||||
continue #si no hay más datos, algo no funciona, pasamos a Ver Online
|
||||
|
||||
#logger.debug(patron)
|
||||
#logger.debug(matches)
|
||||
#logger.debug(data)
|
||||
|
||||
|
||||
for scrapedtorrent, scrapedtitle in matches:
|
||||
item_local = item_local.clone()
|
||||
quality = item_local.quality
|
||||
qualityscraped = ''
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
item_local.contentEpisodeNumber = 0
|
||||
|
||||
#Si son episodios múltiples, los listamos con sus títulos
|
||||
if len(matches) > 1 or len(itemlist_alt) > 1:
|
||||
if item_local.contentType == 'episode' or item_local.contentType == 'season':
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)'):
|
||||
qualityscraped = '%s' % scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)')
|
||||
if scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'))
|
||||
if not qualityscraped:
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
else:
|
||||
qualityscraped = '%s' % scrapedtitle
|
||||
|
||||
#Si todavía no sabemos el num de Episodio, lo buscamos
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
try:
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)'):
|
||||
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)')
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
except:
|
||||
pass
|
||||
|
||||
#Buscamos calidades
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+p)'):
|
||||
qualityscraped += ' ' + scrapertools.find_single_match(scrapedtitle, '(\d+p)')
|
||||
if qualityscraped:
|
||||
quality = '[%s] %s' % (qualityscraped, item_local.quality)
|
||||
if item.videolibray_emergency_urls:
|
||||
item.emergency_urls[0].append(host + scrapedtorrent)
|
||||
else:
|
||||
item_local = item_local.clone()
|
||||
quality = item_local.quality
|
||||
qualityscraped = ''
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
item_local.contentEpisodeNumber = 0
|
||||
|
||||
#Si son episodios múltiples, los listamos con sus títulos
|
||||
if len(matches) > 1 or len(itemlist_alt) > 1:
|
||||
if item_local.contentType == 'episode' or item_local.contentType == 'season':
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)'):
|
||||
qualityscraped = '%s' % scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)')
|
||||
if scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'))
|
||||
if not qualityscraped:
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
else:
|
||||
qualityscraped = '%s' % scrapedtitle
|
||||
|
||||
#Si todavía no sabemos el num de Episodio, lo buscamos
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
try:
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)'):
|
||||
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)')
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
except:
|
||||
pass
|
||||
|
||||
#Buscamos calidades
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+p)'):
|
||||
qualityscraped += ' ' + scrapertools.find_single_match(scrapedtitle, '(\d+p)')
|
||||
if qualityscraped:
|
||||
quality = '[%s] %s' % (qualityscraped, item_local.quality)
|
||||
|
||||
#Ahora pintamos el link del Torrent
|
||||
item_local.url = host + scrapedtorrent
|
||||
size = generictools.get_torrent_size(item_local.url) #Buscamos el tamaño en el .torrent
|
||||
if size:
|
||||
quality += ' [%s]' % size
|
||||
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 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)
|
||||
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" #Seridor Torrent
|
||||
|
||||
itemlist_t.append(item_local.clone(quality=quality)) #Pintar pantalla, si no se filtran idiomas
|
||||
#Ahora pintamos el link del Torrent
|
||||
item_local.url = host + scrapedtorrent
|
||||
if item.emergency_urls and not item.videolibray_emergency_urls:
|
||||
item_local.torrent_alt = item.emergency_urls[0][0] #Guardamos la url del .Torrent ALTERNATIVA
|
||||
if item.armagedon:
|
||||
item_local.url = item.emergency_urls[0][0] #... ponemos la emergencia como primaria
|
||||
del item.emergency_urls[0][0] #Una vez tratado lo limpiamos
|
||||
|
||||
size = ''
|
||||
if not item.armagedon:
|
||||
size = generictools.get_torrent_size(item_local.url) #Buscamos el tamaño en el .torrent
|
||||
if size:
|
||||
quality += ' [%s]' % size
|
||||
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 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)
|
||||
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" #Seridor Torrent
|
||||
|
||||
itemlist_t.append(item_local.clone(quality=quality)) #Pintar pantalla, si no se filtran idiomas
|
||||
|
||||
# Requerido para FilterTools
|
||||
if config.get_setting('filter_languages', channel) > 0: #Si hay idioma seleccionado, se filtra
|
||||
item_local.quality = quality #Calidad
|
||||
itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language) #Pintar pantalla, si no está vacío
|
||||
|
||||
#logger.debug("TORRENT: " + scrapedtorrent + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + scrapedsize + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
|
||||
#logger.debug(item_local)
|
||||
|
||||
if not item.videolibray_emergency_urls:
|
||||
if len(itemlist_f) > 0: #Si hay entradas filtradas...
|
||||
itemlist_alt.extend(itemlist_f) #Pintamos pantalla filtrada
|
||||
else:
|
||||
if config.get_setting('filter_languages', channel) > 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_alt.extend(itemlist_t) #Pintar pantalla con todo si no hay filtrado
|
||||
|
||||
# Requerido para FilterTools
|
||||
if config.get_setting('filter_languages', channel) > 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: " + scrapedtorrent + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + scrapedsize + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
|
||||
#logger.debug(item_local)
|
||||
|
||||
if len(itemlist_f) > 0: #Si hay entradas filtradas...
|
||||
itemlist_alt.extend(itemlist_f) #Pintamos pantalla filtrada
|
||||
else:
|
||||
if config.get_setting('filter_languages', channel) > 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_alt.extend(itemlist_t) #Pintar pantalla con todo si no hay filtrado
|
||||
|
||||
#Si son múltiples episodios, ordenamos
|
||||
if len(itemlist_alt) > 1 and (item.contentType == 'episode' or item.contentType == 'season'):
|
||||
itemlist_alt = sorted(itemlist_alt, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos
|
||||
tmdb.set_infoLabels(itemlist_alt, True) #TMDB de la lista de episodios
|
||||
itemlist.extend(itemlist_alt)
|
||||
#Si son múltiples episodios, ordenamos
|
||||
if len(itemlist_alt) > 1 and (item.contentType == 'episode' or item.contentType == 'season'):
|
||||
itemlist_alt = sorted(itemlist_alt, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos
|
||||
tmdb.set_infoLabels(itemlist_alt, True) #TMDB de la lista de episodios
|
||||
itemlist.extend(itemlist_alt)
|
||||
|
||||
#Ahora tratamos los servidores directo
|
||||
itemlist_alt = []
|
||||
itemlist_t = [] #Itemlist total de enlaces
|
||||
itemlist_f = [] #Itemlist de enlaces filtrados
|
||||
itemlist_t = [] #Itemlist total de enlaces
|
||||
itemlist_f = [] #Itemlist de enlaces filtrados
|
||||
if matches_directo:
|
||||
for scrapedurl, scrapedquality, scrapedlang in matches_directo: #leemos los torrents con la diferentes calidades
|
||||
#Generamos una copia de Item para trabajar sobre ella
|
||||
@@ -861,13 +906,22 @@ def findvideos(item):
|
||||
item_local.language = ["%s" % IDIOMAS[scrapedlang]] #Salvamos el idioma, si lo hay
|
||||
|
||||
#Leemos la página con el enlace al Servidor
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url, timeout=timeout).data)
|
||||
except:
|
||||
pass
|
||||
|
||||
patron = '<div class="linksDescarga"><span class="titulo">Video Online:\s?([^<]+)?<\/span><br><br><a href="([^"]+)'
|
||||
matches = re.compile(patron, re.DOTALL).findall(data)
|
||||
data = ''
|
||||
if not item.armagedon:
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url, timeout=timeout).data)
|
||||
except:
|
||||
pass
|
||||
|
||||
patron = '<div class="linksDescarga"><span class="titulo">Video Online:\s?([^<]+)?<\/span><br><br><a href="([^"]+)'
|
||||
matches = re.compile(patron, re.DOTALL).findall(data)
|
||||
else:
|
||||
matches = item.emergency_urls[4][0] #Guardamos los matches de Directos, si los hay
|
||||
del item.emergency_urls[4][0] #Una vez tratado lo limpiamos
|
||||
data = 'xyz123' #iniciamos data para que no dé problemas
|
||||
|
||||
if item.videolibray_emergency_urls: #Si esyamos añadiendo a Videoteca...
|
||||
item.emergency_urls[4].append(matches) #Salvamos este matches
|
||||
|
||||
if not data or not matches:
|
||||
logger.error("ERROR 02: FINDVIDEOS: El enlace no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
|
||||
@@ -877,114 +931,121 @@ def findvideos(item):
|
||||
#logger.debug(patron)
|
||||
#logger.debug(matches)
|
||||
#logger.debug(data)
|
||||
|
||||
|
||||
for scrapedtitle, scrapedenlace in matches:
|
||||
item_local = item_local.clone()
|
||||
|
||||
enlace = ''
|
||||
devuelve = ''
|
||||
mostrar_server = ''
|
||||
capitulo = ''
|
||||
|
||||
servidor = scrapedtitle.strip()
|
||||
servidor = servidor.replace("streamin", "streaminto")
|
||||
if not servidor or "Capituo" in servidor or "Capitulo" in servidor or scrapertools.find_single_match(servidor, '(\d+[x|X]\d+)'):
|
||||
capitulo = scrapertools.find_single_match(servidor, '(\d+[x|X]\d+)')
|
||||
servidor = scrapertools.find_single_match(scrapedenlace, ':\/\/(.*?)\.')
|
||||
quality = item_local.quality
|
||||
|
||||
qualityscraped = ''
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
item_local.contentEpisodeNumber = 0
|
||||
|
||||
#Si son episodios múltiples, los listamos con sus títulos
|
||||
if (len(matches) > 1 or len(itemlist_alt) > 1) and not servidor in scrapedtitle:
|
||||
if not capitulo and (item_local.contentType == 'episode' or item_local.contentType == 'season'):
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)'):
|
||||
qualityscraped = '%s' % scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)')
|
||||
if scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'))
|
||||
if not qualityscraped:
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
elif capitulo:
|
||||
if scrapertools.find_single_match(capitulo, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
qualityscraped = '%s' % capitulo
|
||||
else:
|
||||
qualityscraped = '%s' % scrapedtitle
|
||||
|
||||
#Si todavía no sabemos el num de Episodio, lo buscamos
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
try:
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)'):
|
||||
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)')
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
except:
|
||||
pass
|
||||
|
||||
#Buscamos calidades
|
||||
if scrapertools.find_single_match(scrapedenlace, '(\d+p)'):
|
||||
qualityscraped += ' ' + scrapertools.find_single_match(scrapedenlace, '(\d+p)')
|
||||
if qualityscraped:
|
||||
quality = '[%s] %s' % (qualityscraped, item_local.quality)
|
||||
|
||||
if scrapertools.find_single_match(item.url, '(\d+x\d+.*?\d+x\d+)') and not capitulo and not qualityscraped:
|
||||
quality = '[%s] %s' % (scrapertools.find_single_match(scrapedenlace, '(\d+x\d+)'), quality)
|
||||
elif capitulo and not qualityscraped:
|
||||
quality = '[%s] %s' % (capitulo, quality)
|
||||
if not item.videolibray_emergency_urls:
|
||||
item_local = item_local.clone()
|
||||
|
||||
enlace = ''
|
||||
devuelve = ''
|
||||
mostrar_server = ''
|
||||
capitulo = ''
|
||||
|
||||
servidor = scrapedtitle.strip()
|
||||
servidor = servidor.replace("streamin", "streaminto")
|
||||
if not servidor or "Capituo" in servidor or "Capitulo" in servidor or scrapertools.find_single_match(servidor, '(\d+[x|X]\d+)'):
|
||||
capitulo = scrapertools.find_single_match(servidor, '(\d+[x|X]\d+)')
|
||||
servidor = scrapertools.find_single_match(scrapedenlace, ':\/\/(.*?)\.')
|
||||
quality = item_local.quality
|
||||
|
||||
qualityscraped = ''
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
item_local.contentEpisodeNumber = 0
|
||||
|
||||
#Si son episodios múltiples, los listamos con sus títulos
|
||||
if (len(matches) > 1 or len(itemlist_alt) > 1) and not servidor in scrapedtitle:
|
||||
if not capitulo and (item_local.contentType == 'episode' or item_local.contentType == 'season'):
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)'):
|
||||
qualityscraped = '%s' % scrapertools.find_single_match(scrapedtitle, '(\d+[x|X]\d+(?:-\d{1,2})?)')
|
||||
if scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '[c|C]ap.*?(\d+)'))
|
||||
elif scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtorrent, '[s|S]\d{1,2}[e|E](\d{1,2})'))
|
||||
if not qualityscraped:
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
elif capitulo:
|
||||
if scrapertools.find_single_match(capitulo, '\d+[x|X](\d+)'):
|
||||
item_local.contentEpisodeNumber = int(scrapertools.find_single_match(scrapedtitle, '\d+[x|X](\d+)'))
|
||||
qualityscraped = '%s' % capitulo
|
||||
else:
|
||||
qualityscraped = '%s' % scrapedtitle
|
||||
|
||||
#Si todavía no sabemos el num de Episodio, lo buscamos
|
||||
if not item_local.contentEpisodeNumber and item_local.contentType == 'episode':
|
||||
try:
|
||||
if scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)'):
|
||||
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(scrapedtitle, '(\d+)[x|X](\d+)')
|
||||
qualityscraped = '%sx%s' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
|
||||
except:
|
||||
pass
|
||||
|
||||
#Buscamos calidades
|
||||
if scrapertools.find_single_match(scrapedenlace, '(\d+p)'):
|
||||
qualityscraped += ' ' + scrapertools.find_single_match(scrapedenlace, '(\d+p)')
|
||||
if qualityscraped:
|
||||
quality = '[%s] %s' % (qualityscraped, item_local.quality)
|
||||
|
||||
if scrapertools.find_single_match(item.url, '(\d+x\d+.*?\d+x\d+)') and not capitulo and not qualityscraped:
|
||||
quality = '[%s] %s' % (scrapertools.find_single_match(scrapedenlace, '(\d+x\d+)'), quality)
|
||||
elif capitulo and not qualityscraped:
|
||||
quality = '[%s] %s' % (capitulo, quality)
|
||||
if item.armagedon: #Si es catastrófico, lo marcamos
|
||||
quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % quality
|
||||
|
||||
#Verificamos el si el enlace del servidor está activo
|
||||
mostrar_server = True
|
||||
if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran
|
||||
mostrar_server = servertools.is_server_enabled(servidor)
|
||||
|
||||
try: #Obtenemos el enlace
|
||||
if mostrar_server:
|
||||
devuelve = servertools.findvideosbyserver(scrapedenlace, servidor) #existe el link ?
|
||||
if devuelve:
|
||||
enlace = devuelve[0][1] #Se guarda el link
|
||||
if not enlace:
|
||||
continue
|
||||
#Verificamos el si el enlace del servidor está activo
|
||||
mostrar_server = True
|
||||
if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran
|
||||
mostrar_server = servertools.is_server_enabled(servidor)
|
||||
|
||||
try: #Obtenemos el enlace
|
||||
if mostrar_server:
|
||||
devuelve = servertools.findvideosbyserver(scrapedenlace, servidor) #existe el link ?
|
||||
if devuelve:
|
||||
enlace = devuelve[0][1] #Se guarda el link
|
||||
if not enlace:
|
||||
continue
|
||||
|
||||
item_local.alive = servertools.check_video_link(enlace, servidor, timeout=timeout) #activo el link ?
|
||||
#Si el link no está activo se ignora
|
||||
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(), quality, str(item_local.language))
|
||||
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(), quality, str(item_local.language))
|
||||
logger.debug(item_local.alive + ": ALIVE / " + servidor + " / " + enlace)
|
||||
raise
|
||||
else: #Sí está activo
|
||||
item_local.title = '[COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), quality, str(item_local.language))
|
||||
|
||||
#Ahora pintamos el link Directo
|
||||
item_local.url = enlace
|
||||
|
||||
item_local.alive = servertools.check_video_link(enlace, servidor, timeout=timeout) #activo el link ?
|
||||
#Si el link no está activo se ignora
|
||||
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(), quality, str(item_local.language))
|
||||
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(), quality, str(item_local.language))
|
||||
logger.debug(item_local.alive + ": ALIVE / " + servidor + " / " + enlace)
|
||||
raise
|
||||
else: #Sí está activo
|
||||
item_local.title = '[COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), quality, str(item_local.language))
|
||||
#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)
|
||||
quality = quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
|
||||
|
||||
#Ahora pintamos el link Directo
|
||||
item_local.url = enlace
|
||||
|
||||
#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)
|
||||
quality = quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
|
||||
|
||||
item_local.action = "play" #Visualizar vídeo
|
||||
item_local.server = servidor #Seridor Directo
|
||||
|
||||
itemlist_t.append(item_local.clone(quality=quality)) #Pintar pantalla, si no se filtran idiomas
|
||||
|
||||
# Requerido para FilterTools
|
||||
if config.get_setting('filter_languages', channel) > 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
|
||||
except:
|
||||
logger.error('ERROR al procesar enlaces DIRECTOS: ' + servidor + ' / ' + scrapedenlace)
|
||||
item_local.action = "play" #Visualizar vídeo
|
||||
item_local.server = servidor #Servidor Directo
|
||||
|
||||
itemlist_t.append(item_local.clone(quality=quality)) #Pintar pantalla, si no se filtran idiomas
|
||||
|
||||
# Requerido para FilterTools
|
||||
if config.get_setting('filter_languages', channel) > 0: #Si hay idioma seleccionado, se filtra
|
||||
item_local.quality = quality #Calidad
|
||||
itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language) #Pintar pantalla, si no está vacío
|
||||
except:
|
||||
logger.error('ERROR al procesar enlaces DIRECTOS: ' + servidor + ' / ' + scrapedenlace)
|
||||
|
||||
#logger.debug("DIRECTO: " + scrapedenlace + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + scrapedsize + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
|
||||
#logger.debug(item_local)
|
||||
#logger.debug("DIRECTO: " + scrapedenlace + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + scrapedsize + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
|
||||
#logger.debug(item_local)
|
||||
|
||||
if item.videolibray_emergency_urls: #Si estamos cargados emergency_urls, no vamos
|
||||
return item
|
||||
|
||||
if len(itemlist_f) > 0: #Si hay entradas filtradas...
|
||||
itemlist_alt.extend(itemlist_f) #Pintamos pantalla filtrada
|
||||
@@ -997,11 +1058,11 @@ def findvideos(item):
|
||||
#Si son múltiples episodios, ordenamos
|
||||
if len(itemlist_alt) > 1 and (item.contentType == 'episode' or item.contentType == 'season'):
|
||||
itemlist_alt = sorted(itemlist_alt, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos
|
||||
tmdb.set_infoLabels(itemlist_alt, True) #TMDB de la lista de episodios
|
||||
tmdb.set_infoLabels(itemlist_alt, True) #TMDB de la lista de episodios
|
||||
itemlist.extend(itemlist_alt)
|
||||
|
||||
# Requerido para AutoPlay
|
||||
autoplay.start(itemlist, item) #Lanzamos Autoplay
|
||||
autoplay.start(itemlist, item) #Lanzamos Autoplay
|
||||
|
||||
return itemlist
|
||||
|
||||
|
||||
@@ -428,15 +428,17 @@ def findvideos(item):
|
||||
#logger.debug(item)
|
||||
|
||||
timeout_find = timeout
|
||||
follow_redirects=True
|
||||
if item.videolibray_emergency_urls: #Si se están cacheando enlaces aumentamos el timeout
|
||||
timeout_find = timeout * 2
|
||||
elif item.emergency_urls: #Si se llama desde la Videoteca con enlaces cacheados...
|
||||
timeout_find = timeout / 2 #reducimos el timeout antes de saltar a los enlaces cacheados
|
||||
follow_redirects=False
|
||||
|
||||
#Bajamos los datos de la página
|
||||
data = ''
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout_find).data)
|
||||
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout_find, follow_redirects=follow_redirects).data)
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -633,6 +635,8 @@ def episodios(item):
|
||||
temp_next = ''
|
||||
item.extra = "episodios"
|
||||
|
||||
#logger.debug(item)
|
||||
|
||||
# Obtener la información actualizada de la Serie. TMDB es imprescindible para Videoteca
|
||||
if not item.infoLabels['tmdb_id']:
|
||||
tmdb.set_infoLabels(item, True)
|
||||
@@ -716,6 +720,8 @@ def episodios(item):
|
||||
|
||||
if item.ow_force == '1': #Si viene formazado la reconstrucción de la serie, lo hacemo
|
||||
item.contentType = "tvshow"
|
||||
if not modo_ultima_temp: #Si se quiere actualiar toda la serie en vez de la última temporada...
|
||||
item.contentType = "tvshow"
|
||||
|
||||
temp_lista = []
|
||||
temp_bucle = 0
|
||||
|
||||
@@ -78,12 +78,13 @@
|
||||
"enabled": true,
|
||||
"visible": true,
|
||||
"lvalues": [
|
||||
"Aleatorio",
|
||||
"Descargas2020",
|
||||
"Tumejortorrent",
|
||||
"Torrentrapid",
|
||||
"Torrentlocura",
|
||||
"Tvsinpagar",
|
||||
"Planetatorrent",
|
||||
"Torrentrapid",
|
||||
"Tumejortorrent",
|
||||
"Descargas2020",
|
||||
"Mispelisyseries"
|
||||
]
|
||||
},
|
||||
@@ -91,7 +92,7 @@
|
||||
"id": "clonenewpct1_channels_list",
|
||||
"type": "text",
|
||||
"label": "Lista de clones de NewPct1 y orden de uso",
|
||||
"default": "('1', 'torrentlocura', 'http://torrentlocura.com/', 'movie, tvshow, season, episode', ''), ('1', 'tvsinpagar', 'http://www.tvsinpagar.com/', 'tvshow, season, episode', ''), ('1', 'planetatorrent', 'http://planetatorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', 'serie_episodios'), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'descargas2020', 'http://descargas2020.com/', 'movie, tvshow, season, episode', ''), ('1', 'mispelisyseries', 'http://mispelisyseries.com/', 'movie', 'search, listado_busqueda')",
|
||||
"default": "('1', 'descargas2020', 'http://descargas2020.com/', 'movie, tvshow, season, episode', ''), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', 'serie_episodios'), ('1', 'torrentlocura', 'http://torrentlocura.com/', 'movie, tvshow, season, episode', ''), ('1', 'tvsinpagar', 'http://www.tvsinpagar.com/', 'tvshow, season, episode', ''), ('1', 'planetatorrent', 'http://planetatorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'mispelisyseries', 'http://mispelisyseries.com/', 'movie', 'search, listado_busqueda')",
|
||||
"enabled": true,
|
||||
"visible": false
|
||||
},
|
||||
|
||||
@@ -6,6 +6,7 @@ import urllib
|
||||
import urlparse
|
||||
import datetime
|
||||
import ast
|
||||
import random
|
||||
|
||||
from channelselector import get_thumb
|
||||
from core import httptools
|
||||
@@ -31,27 +32,45 @@ channel_py = 'newpct1'
|
||||
#Código para permitir usar un único canal para todas las webs clones de NewPct1
|
||||
#Cargamos en .json del canal para ver las listas de valores en settings
|
||||
clone_list = channeltools.get_channel_json(channel_py)
|
||||
for settings in clone_list['settings']: #Se recorren todos los settings
|
||||
if settings['id'] == "clonenewpct1_channels_list": #Encontramos en setting
|
||||
clone_list = settings['default'] #Carga lista de clones
|
||||
for settings in clone_list['settings']: #Se recorren todos los settings
|
||||
if settings['id'] == "clonenewpct1_channels_list": #Encontramos en setting
|
||||
clone_list = settings['default'] #Carga lista de clones
|
||||
break
|
||||
clone_list = ast.literal_eval(clone_list) #la convierte en array
|
||||
clone_list = ast.literal_eval(clone_list) #la convierte en array
|
||||
host_index = 0
|
||||
host_index = config.get_setting('clonenewpct1_channel_default', channel_py) #Clone por defecto
|
||||
i = 0
|
||||
for active_clone, channel_clone, host_clone, contentType_clone, info_clone in clone_list:
|
||||
if i == host_index:
|
||||
channel_clone_name = channel_clone #Nombre del Canal elegido
|
||||
host = host_clone #URL del Canal elegido
|
||||
if active_clone == "1": #Comprueba que el clone esté activo
|
||||
host_index = config.get_setting('clonenewpct1_channel_default', channel_py) #Clone por defecto
|
||||
|
||||
clone_list_random = [] #Iniciamos la lista aleatoria de clones
|
||||
|
||||
if host_index == 0: #Si el clones es "Aleatorio"...
|
||||
i = 0
|
||||
j = 2 #... marcamos el último de los clones "buenos"
|
||||
for active_clone, channel_clone, host_clone, contentType_clone, info_clone in clone_list:
|
||||
if i <= j and active_clone == "1":
|
||||
clone_list_random += [clone_list[i]] #... añadimos el clone activo "bueno" a la lista
|
||||
else:
|
||||
break
|
||||
channel_clone_name = "*** DOWN ***" #es un fallo masivo ???
|
||||
for active_clone, channel_clone, host_clone, contentType_clone, info_clone in clone_list:
|
||||
if active_clone == "1": #Comprueba que el clone esté activo
|
||||
channel_clone_name = channel_clone #Nombre del Canal elegido
|
||||
host = host_clone #URL del Canal elegido
|
||||
i += 1
|
||||
if clone_list_random: #Si hay clones en la lista aleatoria...
|
||||
clone_list = [random.choice(clone_list_random)] #Seleccionamos un clone aleatorio
|
||||
#logger.debug(clone_list)
|
||||
host_index = 1 #mutamos el num. de clone para que se procese en el siguiente loop
|
||||
|
||||
if host_index > 0 or not clone_list_random: #Si el Clone por defecto no es Aleatorio, o hay ya un aleatorio sleccionado...
|
||||
i = 1
|
||||
for active_clone, channel_clone, host_clone, contentType_clone, info_clone in clone_list:
|
||||
if i == host_index:
|
||||
channel_clone_name = channel_clone #Nombre del Canal elegido
|
||||
host = host_clone #URL del Canal elegido
|
||||
if active_clone == "1": #Comprueba que el clone esté activo
|
||||
break
|
||||
i += 1
|
||||
channel_clone_name = "*** DOWN ***" #es un fallo masivo ???
|
||||
for active_clone, channel_clone, host_clone, contentType_clone, info_clone in clone_list:
|
||||
if active_clone == "1": #Comprueba que el clone esté activo
|
||||
channel_clone_name = channel_clone #Nombre del Canal elegido
|
||||
host = host_clone #URL del Canal elegido
|
||||
break
|
||||
i += 1
|
||||
|
||||
item = Item()
|
||||
if item.channel != channel_py:
|
||||
@@ -139,6 +158,11 @@ def submenu(item):
|
||||
itemlist = []
|
||||
item.extra2 = ''
|
||||
|
||||
#Renombramos el canal al nombre de clone inicial desde la URL
|
||||
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
|
||||
item.channel_host = host
|
||||
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
|
||||
|
||||
data = ''
|
||||
try:
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data)
|
||||
@@ -218,6 +242,11 @@ def submenu_novedades(item):
|
||||
itemlist_alt = []
|
||||
item.extra2 = ''
|
||||
|
||||
#Renombramos el canal al nombre de clone inicial desde la URL
|
||||
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
|
||||
item.channel_host = host
|
||||
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
|
||||
|
||||
data = ''
|
||||
timeout_search=timeout * 2 #Más tiempo para Novedades, que es una búsqueda
|
||||
thumb_settings = get_thumb("setting_0.png")
|
||||
@@ -315,6 +344,11 @@ def submenu_novedades(item):
|
||||
def alfabeto(item):
|
||||
logger.info()
|
||||
itemlist = []
|
||||
|
||||
#Renombramos el canal al nombre de clone inicial desde la URL
|
||||
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
|
||||
item.channel_host = host
|
||||
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
|
||||
|
||||
data = ''
|
||||
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data)
|
||||
@@ -365,6 +399,12 @@ def alfabeto(item):
|
||||
def listado(item):
|
||||
logger.info()
|
||||
itemlist = []
|
||||
|
||||
#Renombramos el canal al nombre de clone inicial desde la URL
|
||||
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
|
||||
item.channel_host = host
|
||||
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
|
||||
|
||||
clase = "pelilist" # etiqueta para localizar zona de listado de contenidos
|
||||
url_next_page ='' # Control de paginación
|
||||
cnt_tot = 30 # Poner el num. máximo de items por página
|
||||
@@ -1249,7 +1289,7 @@ def findvideos(item):
|
||||
#Renombramos el canal al nombre de clone elegido. Actualizados URL
|
||||
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
|
||||
item.channel_host = host
|
||||
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
|
||||
item.category = host.capitalize()
|
||||
|
||||
verify_fo = True #Verificamos si el clone a usar está activo
|
||||
item, data = generictools.fail_over_newpct1(item, verify_fo)
|
||||
@@ -1374,10 +1414,11 @@ def findvideos(item):
|
||||
pass
|
||||
|
||||
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
|
||||
patron_mult = 'torrent:check:status|' + patron
|
||||
if 'planetatorrent' in item.channel_host:
|
||||
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
|
||||
patron_mult += '|<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"'
|
||||
patron_mult = 'torrent:check:status|' + patron + '|<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"'
|
||||
if not scrapertools.find_single_match(data, patron):
|
||||
patron_alt = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
|
||||
if scrapertools.find_single_match(data, patron):
|
||||
patron = patron_alt
|
||||
#Verificamos si se ha cargado una página, y si además tiene la estructura correcta
|
||||
if not data or not scrapertools.find_single_match(data, patron) or not videolibrarytools.verify_url_torrent(scrapertools.find_single_match(data, patron)): # Si no hay datos o url, error
|
||||
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
|
||||
@@ -1475,7 +1516,7 @@ def findvideos(item):
|
||||
if not item_local.url: #error en url?
|
||||
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.item_local = item.emergency_urls[0][0] #Guardamos la url del .Torrent
|
||||
item_local.url = item.emergency_urls[0][0] #Restauramos la url del .Torrent
|
||||
item.armagedon = True #Marcamos la situación como catastrófica
|
||||
itemlist.append(item.clone(action='', title=item.category + ': [COLOR hotpink]Usando enlaces de emergencia[/COLOR]'))
|
||||
|
||||
@@ -1821,12 +1862,14 @@ def episodios(item):
|
||||
pass
|
||||
|
||||
modo_ultima_temp_alt = modo_ultima_temp
|
||||
if item.ow_force == "1": #Si hay un traspaso de canal o url, se actualiza todo
|
||||
if item.ow_force == "1": #Si hay un traspaso de canal o url, se actualiza todo
|
||||
modo_ultima_temp_alt = False
|
||||
|
||||
max_temp = 1
|
||||
if item.infoLabels['number_of_seasons']:
|
||||
max_temp = item.infoLabels['number_of_seasons']
|
||||
else:
|
||||
modo_ultima_temp_alt = False #No sabemos cuantas temporadas hay
|
||||
y = []
|
||||
if modo_ultima_temp_alt and item.library_playcounts: #Averiguar cuantas temporadas hay en Videoteca
|
||||
patron = 'season (\d+)'
|
||||
@@ -2043,11 +2086,12 @@ def episodios(item):
|
||||
else: #Si es un solo episodio, se formatea ya
|
||||
item_local.title = "%sx%s -" % (match["season"], str(match["episode"]).zfill(2))
|
||||
|
||||
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 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
|
||||
@@ -2055,7 +2099,7 @@ def episodios(item):
|
||||
# continue
|
||||
|
||||
if season_display > 0:
|
||||
if item_local.contentSeason > season_display:
|
||||
if item_local.contentSeason > season_display or (not modo_ultima_temp_alt and item_local.contentSeason != season_display):
|
||||
continue
|
||||
elif item_local.contentSeason < season_display:
|
||||
list_pages = [] #Sale del bucle de leer páginas
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import os, traceback
|
||||
|
||||
from channelselector import get_thumb
|
||||
from core import filetools
|
||||
@@ -35,7 +35,8 @@ def channel_config(item):
|
||||
def list_movies(item, silent=False):
|
||||
logger.info()
|
||||
itemlist = []
|
||||
|
||||
dead_list = []
|
||||
zombie_list = []
|
||||
for raiz, subcarpetas, ficheros in filetools.walk(videolibrarytools.MOVIES_PATH):
|
||||
for f in ficheros:
|
||||
if f.endswith(".nfo"):
|
||||
@@ -47,10 +48,57 @@ def list_movies(item, silent=False):
|
||||
from platformcode import xbmc_videolibrary
|
||||
xbmc_videolibrary.mark_content_as_watched_on_alfa(nfo_path)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
head_nfo, new_item = videolibrarytools.read_nfo(nfo_path)
|
||||
|
||||
if len(new_item.library_urls) > 1:
|
||||
multicanal = True
|
||||
else:
|
||||
multicanal = False
|
||||
|
||||
## verifica la existencia de los canales, en caso de no existir el canal se pregunta si se quieren
|
||||
## eliminar los enlaces de dicho canal
|
||||
|
||||
for canal_org in new_item.library_urls:
|
||||
canal = generictools.verify_channel(canal_org)
|
||||
logger.error(canal)
|
||||
try:
|
||||
channel_verify = __import__('channels.%s' % canal, fromlist=["channels.%s" % canal])
|
||||
logger.debug('El canal %s parece correcto' % channel_verify)
|
||||
except:
|
||||
dead_item = Item(multicanal=multicanal,
|
||||
contentType='movie',
|
||||
dead=canal,
|
||||
path=raiz,
|
||||
nfo=nfo_path,
|
||||
library_urls=new_item.library_urls,
|
||||
infoLabels={'title': new_item.contentTitle})
|
||||
if canal not in dead_list and canal not in zombie_list:
|
||||
confirm = platformtools.dialog_yesno('Videoteca',
|
||||
'Parece que el canal [COLOR red]%s[/COLOR] ya no existe.' % canal.upper(),
|
||||
'Deseas eliminar los enlaces de este canal?')
|
||||
|
||||
elif canal in zombie_list:
|
||||
confirm = False
|
||||
else:
|
||||
confirm = True
|
||||
|
||||
if confirm:
|
||||
delete(dead_item)
|
||||
if canal not in dead_list:
|
||||
dead_list.append(canal)
|
||||
continue
|
||||
else:
|
||||
if canal not in zombie_list:
|
||||
zombie_list.append(canal)
|
||||
|
||||
if len(dead_list) > 0:
|
||||
for canal in dead_list:
|
||||
if canal in new_item.library_urls:
|
||||
del new_item.library_urls[canal]
|
||||
|
||||
|
||||
new_item.nfo = nfo_path
|
||||
new_item.path = raiz
|
||||
new_item.thumbnail = new_item.contentThumbnail
|
||||
@@ -67,7 +115,7 @@ def list_movies(item, silent=False):
|
||||
try:
|
||||
new_item, new_item, overwrite = generictools.redirect_clone_newpct1(new_item, head_nfo, new_item, raiz)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
# Menu contextual: Marcar como visto/no visto
|
||||
visto = new_item.library_playcounts.get(os.path.splitext(f)[0], 0)
|
||||
@@ -85,10 +133,8 @@ def list_movies(item, silent=False):
|
||||
num_canales -= 1
|
||||
if num_canales > 1:
|
||||
texto_eliminar = config.get_localized_string(60018)
|
||||
multicanal = True
|
||||
else:
|
||||
texto_eliminar = config.get_localized_string(60019)
|
||||
multicanal = False
|
||||
|
||||
new_item.context = [{"title": texto_visto,
|
||||
"action": "mark_content_as_watched",
|
||||
@@ -113,10 +159,12 @@ def list_movies(item, silent=False):
|
||||
def list_tvshows(item):
|
||||
logger.info()
|
||||
itemlist = []
|
||||
|
||||
dead_list = []
|
||||
zombie_list = []
|
||||
# Obtenemos todos los tvshow.nfo de la videoteca de SERIES recursivamente
|
||||
for raiz, subcarpetas, ficheros in filetools.walk(videolibrarytools.TVSHOWS_PATH):
|
||||
for f in ficheros:
|
||||
|
||||
if f == "tvshow.nfo":
|
||||
tvshow_path = filetools.join(raiz, f)
|
||||
# logger.debug(tvshow_path)
|
||||
@@ -127,10 +175,58 @@ def list_tvshows(item):
|
||||
from platformcode import xbmc_videolibrary
|
||||
xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_path)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path)
|
||||
try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing
|
||||
|
||||
if len(item_tvshow.library_urls) > 1:
|
||||
multicanal = True
|
||||
else:
|
||||
multicanal = False
|
||||
|
||||
## verifica la existencia de los canales, en caso de no existir el canal se pregunta si se quieren
|
||||
## eliminar los enlaces de dicho canal
|
||||
|
||||
for canal in item_tvshow.library_urls:
|
||||
canal = generictools.verify_channel(canal)
|
||||
try:
|
||||
channel_verify = __import__('channels.%s' % canal, fromlist=["channels.%s" % canal])
|
||||
logger.debug('El canal %s parece correcto' % channel_verify)
|
||||
except:
|
||||
dead_item = Item(multicanal=multicanal,
|
||||
contentType='tvshow',
|
||||
dead=canal,
|
||||
path=raiz,
|
||||
nfo=tvshow_path,
|
||||
library_urls=item_tvshow.library_urls,
|
||||
infoLabels={'title': item_tvshow.contentTitle})
|
||||
if canal not in dead_list and canal not in zombie_list:
|
||||
confirm = platformtools.dialog_yesno('Videoteca',
|
||||
'Parece que el canal [COLOR red]%s[/COLOR] ya no existe.' % canal.upper(),
|
||||
'Deseas eliminar los enlaces de este canal?')
|
||||
|
||||
elif canal in zombie_list:
|
||||
confirm = False
|
||||
else:
|
||||
confirm = True
|
||||
|
||||
if confirm:
|
||||
delete(dead_item)
|
||||
if canal not in dead_list:
|
||||
dead_list.append(canal)
|
||||
continue
|
||||
else:
|
||||
if canal not in zombie_list:
|
||||
zombie_list.append(canal)
|
||||
|
||||
if len(dead_list) > 0:
|
||||
for canal in dead_list:
|
||||
if canal in item_tvshow.library_urls:
|
||||
del item_tvshow.library_urls[canal]
|
||||
|
||||
### continua la carga de los elementos de la videoteca
|
||||
|
||||
try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing
|
||||
item_tvshow.title = item_tvshow.contentTitle
|
||||
item_tvshow.path = raiz
|
||||
item_tvshow.nfo = tvshow_path
|
||||
@@ -146,6 +242,7 @@ def list_tvshows(item):
|
||||
|
||||
except:
|
||||
logger.error('No encuentra: ' + str(tvshow_path))
|
||||
logger.error(traceback.format_exc())
|
||||
continue
|
||||
|
||||
# Menu contextual: Buscar automáticamente nuevos episodios o no
|
||||
@@ -164,10 +261,8 @@ def list_tvshows(item):
|
||||
num_canales -= 1
|
||||
if num_canales > 1:
|
||||
texto_eliminar = config.get_localized_string(60024)
|
||||
multicanal = True
|
||||
else:
|
||||
texto_eliminar = config.get_localized_string(60025)
|
||||
multicanal = False
|
||||
|
||||
item_tvshow.context = [{"title": texto_visto,
|
||||
"action": "mark_content_as_watched",
|
||||
@@ -189,7 +284,14 @@ def list_tvshows(item):
|
||||
# "channel": "videolibrary"}]
|
||||
|
||||
# logger.debug("item_tvshow:\n" + item_tvshow.tostring('\n'))
|
||||
itemlist.append(item_tvshow)
|
||||
|
||||
## verifica la existencia de los canales ##
|
||||
|
||||
logger.debug(item_tvshow)
|
||||
if len(item_tvshow.library_urls) > 0:
|
||||
itemlist.append(item_tvshow)
|
||||
|
||||
|
||||
|
||||
if itemlist:
|
||||
itemlist = sorted(itemlist, key=lambda it: it.title.lower())
|
||||
@@ -368,7 +470,7 @@ def findvideos(item):
|
||||
try:
|
||||
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
item_json.contentChannel = "local"
|
||||
# Soporte para rutas relativas en descargas
|
||||
if filetools.is_relative(item_json.url):
|
||||
@@ -413,7 +515,7 @@ def findvideos(item):
|
||||
try:
|
||||
item_canal, it, overwrite = generictools.redirect_clone_newpct1(item_canal)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
nom_canal = item_canal.channel
|
||||
|
||||
# Importamos el canal de la parte seleccionada
|
||||
@@ -427,7 +529,7 @@ def findvideos(item):
|
||||
try:
|
||||
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
list_servers = []
|
||||
|
||||
try:
|
||||
@@ -452,6 +554,7 @@ def findvideos(item):
|
||||
template = "An exception of type %s occured. Arguments:\n%r"
|
||||
message = template % (type(ex).__name__, ex.args)
|
||||
logger.error(message)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
# Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
|
||||
# las infoLabels y las imagenes del item si el server no tiene
|
||||
@@ -778,7 +881,7 @@ def mark_tvshow_as_updatable(item):
|
||||
def delete(item):
|
||||
def delete_all(_item):
|
||||
for file in filetools.listdir(_item.path):
|
||||
if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json"):
|
||||
if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json")or file.endswith(".torrent"):
|
||||
filetools.remove(filetools.join(_item.path, file))
|
||||
raiz, carpeta_serie, ficheros = filetools.walk(_item.path).next()
|
||||
if ficheros == []:
|
||||
@@ -803,39 +906,45 @@ def delete(item):
|
||||
heading = config.get_localized_string(70084)
|
||||
else:
|
||||
heading = config.get_localized_string(70085)
|
||||
|
||||
if item.multicanal:
|
||||
# Obtener listado de canales
|
||||
opciones = [config.get_localized_string(70086) % k.capitalize() for k in item.library_urls.keys() if
|
||||
k != "downloads"]
|
||||
opciones.insert(0, heading)
|
||||
if item.dead == '':
|
||||
opciones = [config.get_localized_string(70086) % k.capitalize() for k in item.library_urls.keys() if
|
||||
k != "downloads"]
|
||||
opciones.insert(0, heading)
|
||||
|
||||
index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
|
||||
index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
|
||||
|
||||
if index == 0:
|
||||
# Seleccionado Eliminar pelicula/serie
|
||||
delete_all(item)
|
||||
if index == 0:
|
||||
# Seleccionado Eliminar pelicula/serie
|
||||
delete_all(item)
|
||||
|
||||
elif index > 0:
|
||||
# Seleccionado Eliminar canal X
|
||||
canal = opciones[index].replace(config.get_localized_string(70079), "").lower()
|
||||
elif index > 0:
|
||||
# Seleccionado Eliminar canal X
|
||||
canal = opciones[index].replace(config.get_localized_string(70079), "").lower()
|
||||
else:
|
||||
return
|
||||
else:
|
||||
canal = item.dead
|
||||
|
||||
num_enlaces = 0
|
||||
for fd in filetools.listdir(item.path):
|
||||
if fd.endswith(canal + '].json'):
|
||||
if filetools.remove(filetools.join(item.path, fd)):
|
||||
num_enlaces += 1
|
||||
num_enlaces = 0
|
||||
for fd in filetools.listdir(item.path):
|
||||
if fd.endswith(canal + '].json') or scrapertools.find_single_match(fd, '%s]_\d+.torrent' % canal):
|
||||
if filetools.remove(filetools.join(item.path, fd)):
|
||||
num_enlaces += 1
|
||||
|
||||
if num_enlaces > 0:
|
||||
# Actualizar .nfo
|
||||
head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo)
|
||||
del item_nfo.library_urls[canal]
|
||||
filetools.write(item.nfo, head_nfo + item_nfo.tojson())
|
||||
if num_enlaces > 0:
|
||||
# Actualizar .nfo
|
||||
head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo)
|
||||
del item_nfo.library_urls[canal]
|
||||
if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False):
|
||||
del item_nfo.emergency_urls[canal]
|
||||
filetools.write(item.nfo, head_nfo + item_nfo.tojson())
|
||||
|
||||
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal)
|
||||
logger.info(msg_txt)
|
||||
platformtools.dialog_notification(heading, msg_txt)
|
||||
platformtools.itemlist_refresh()
|
||||
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal)
|
||||
logger.info(msg_txt)
|
||||
platformtools.dialog_notification(heading, msg_txt)
|
||||
platformtools.itemlist_refresh()
|
||||
|
||||
else:
|
||||
if platformtools.dialog_yesno(heading,
|
||||
@@ -867,7 +976,6 @@ def check_season_playcount(item, season):
|
||||
|
||||
def check_tvshow_playcount(item, season):
|
||||
logger.info()
|
||||
# logger.debug(item)
|
||||
if season:
|
||||
temporadas_serie = 0
|
||||
temporadas_vistas_serie = 0
|
||||
|
||||
@@ -267,11 +267,19 @@ def downloadpage(url, post=None, headers=None, timeout=None, follow_redirects=Tr
|
||||
|
||||
if response["headers"].get('content-encoding') == 'gzip':
|
||||
logger.info("Descomprimiendo...")
|
||||
data_alt = response["data"]
|
||||
try:
|
||||
response["data"] = gzip.GzipFile(fileobj=StringIO(response["data"])).read()
|
||||
logger.info("Descomprimido")
|
||||
except:
|
||||
logger.info("No se ha podido descomprimir")
|
||||
logger.info("No se ha podido descomprimir con gzip. Intentando con zlib")
|
||||
response["data"] = data_alt
|
||||
try:
|
||||
import zlib
|
||||
response["data"] = zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(response["data"])
|
||||
except:
|
||||
logger.info("No se ha podido descomprimir con zlib")
|
||||
response["data"] = data_alt
|
||||
|
||||
# Anti Cloudflare
|
||||
if bypass_cloudflare and count_retries < 5:
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import errno
|
||||
import math
|
||||
import traceback
|
||||
|
||||
from core import filetools
|
||||
from core import scraper
|
||||
@@ -195,6 +196,7 @@ def save_movie(item):
|
||||
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)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if filetools.write(json_path, item.tojson()):
|
||||
p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
|
||||
@@ -441,6 +443,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
|
||||
except:
|
||||
if e.contentType == 'episode':
|
||||
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle)
|
||||
logger.error(traceback.format_exc())
|
||||
continue
|
||||
|
||||
# No hay lista de episodios, no hay nada que guardar
|
||||
@@ -568,6 +571,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
|
||||
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)
|
||||
logger.error(traceback.format_exc())
|
||||
fallidos = -1
|
||||
else:
|
||||
# ... si ha sido correcto actualizamos la videoteca de Kodi
|
||||
@@ -731,16 +735,18 @@ def emergency_urls(item, channel=None, path=None):
|
||||
channel = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel])
|
||||
if hasattr(channel, 'findvideos'): #Si el canal tiene "findvideos"...
|
||||
item.videolibray_emergency_urls = True #... se marca como "lookup"
|
||||
item_res = getattr(channel, 'findvideos')(item) #... se procesa
|
||||
channel_save = item.channel #... guarda el canal original por si hay fail-over en Newpct1
|
||||
item_res = getattr(channel, 'findvideos')(item) #... se procesa Findvideos
|
||||
item_res.channel = channel_save #... restaura el canal original por si hay fail-over en Newpct1
|
||||
item_res.category = channel_save.capitalize() #... y la categoría
|
||||
del item_res.videolibray_emergency_urls #... y se borra la marca de lookup
|
||||
except:
|
||||
logger.error('ERROR al procesar el episodio')
|
||||
logger.error('ERROR al procesar el título en Findvideos del Canal: ' + item.channel + ' / ' + item.title)
|
||||
logger.error(traceback.format_exc())
|
||||
item_res = item.clone() #Si ha habido un error, se devuelve el Item original
|
||||
|
||||
#Si el usuario ha activado la opción "emergency_urls_torrents", se descargarán los archivos .torrent de cada título
|
||||
else: #Si se han cacheado con éxito los enlaces...
|
||||
logger.debug('HOLA')
|
||||
logger.debug(item_res.emergency_urls)
|
||||
try:
|
||||
channel_bis = generictools.verify_channel(item.channel)
|
||||
if config.get_setting("emergency_urls_torrents", channel_bis) and item_res.emergency_urls and path != None:
|
||||
@@ -760,13 +766,15 @@ def emergency_urls(item, channel=None, path=None):
|
||||
item_res.emergency_urls[0][i-1] = path_real.replace(videolibrary_path, '') #se guarda el "path" relativo
|
||||
i += 1
|
||||
except:
|
||||
logger.error('ERROR al cachear el .torrent de: ' + item.channel + ' / ' + item.title)
|
||||
logger.error(traceback.format_exc())
|
||||
item_res = item.clone() #Si ha habido un error, se devuelve el Item original
|
||||
|
||||
#logger.debug(item_res.emergency_urls)
|
||||
return item_res #Devolvemos el Item actualizado con los enlaces de emergencia
|
||||
|
||||
|
||||
def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, lookup=False):
|
||||
def caching_torrents(url, torrents_path=None, timeout=10, lookup=False, data_torrent=False):
|
||||
if torrents_path != None:
|
||||
logger.info("path = " + torrents_path)
|
||||
else:
|
||||
@@ -774,98 +782,80 @@ def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, loo
|
||||
import urllib
|
||||
import re
|
||||
from core import httptools
|
||||
torrent_file = ''
|
||||
|
||||
"""
|
||||
Descarga en el path recibido el .torrent de la url recibida, y pasa el decode
|
||||
Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito
|
||||
"""
|
||||
|
||||
def decode(text):
|
||||
try:
|
||||
src = tokenize(text)
|
||||
data = decode_item(src.next, src.next())
|
||||
for token in src: # look for more tokens
|
||||
raise SyntaxError("trailing junk")
|
||||
except (AttributeError, ValueError, StopIteration):
|
||||
try:
|
||||
data = data
|
||||
except:
|
||||
data = src
|
||||
|
||||
return data
|
||||
|
||||
def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
|
||||
i = 0
|
||||
while i < len(text):
|
||||
m = match(text, i)
|
||||
s = m.group(m.lastindex)
|
||||
i = m.end()
|
||||
if m.lastindex == 2:
|
||||
yield "s"
|
||||
yield text[i:i + int(s)]
|
||||
i = i + int(s)
|
||||
else:
|
||||
yield s
|
||||
|
||||
def decode_item(next, token):
|
||||
if token == "i":
|
||||
# integer: "i" value "e"
|
||||
data = int(next())
|
||||
if next() != "e":
|
||||
raise ValueError
|
||||
elif token == "s":
|
||||
# string: "s" value (virtual tokens)
|
||||
data = next()
|
||||
elif token == "l" or token == "d":
|
||||
# container: "l" (or "d") values "e"
|
||||
data = []
|
||||
tok = next()
|
||||
while tok != "e":
|
||||
data.append(decode_item(next, tok))
|
||||
tok = next()
|
||||
if token == "d":
|
||||
data = dict(zip(data[0::2], data[1::2]))
|
||||
else:
|
||||
raise ValueError
|
||||
return data
|
||||
if torrents_path == None:
|
||||
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
|
||||
if not videolibrary_path:
|
||||
torrents_path = ''
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path #Si hay un error, devolvemos el "path" vacío
|
||||
torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path de descarga temporal
|
||||
if '.torrent' not in torrents_path:
|
||||
torrents_path += '.torrent' #path para dejar el .torrent
|
||||
torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
|
||||
|
||||
if url.endswith(".rar"): #No es un archivo .torrent
|
||||
logger.error('No es un archivo Torrent: ' + url)
|
||||
torrents_path = ''
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path #Si hay un error, devolvemos el "path" vacío
|
||||
|
||||
#Módulo PRINCIPAL
|
||||
try:
|
||||
if lookup:
|
||||
torrents_path = lookup
|
||||
else:
|
||||
if '.torrent' not in torrents_path:
|
||||
torrents_path += '.torrent' #path para dejar el .torrent
|
||||
|
||||
torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
|
||||
response = httptools.downloadpage(url, timeout=timeout) #Descargamos el .torrent
|
||||
if not response.sucess:
|
||||
logger.error('Archivo .torrent no encontrado: ' + url)
|
||||
torrents_path = ''
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path #Si hay un error, devolvemos el "path" vacío
|
||||
torrent_file = response.data
|
||||
|
||||
|
||||
if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso
|
||||
response = httptools.downloadpage("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(), timeout=timeout)
|
||||
if not response.sucess:
|
||||
logger.error('Archivo .torrent no encontrado: ' + url)
|
||||
torrents_path = ''
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path #Si hay un error, devolvemos el "path" vacío
|
||||
torrent_file = response.data
|
||||
|
||||
if decode_flag:
|
||||
torrent_file = decode(torrent_file) #decodificamos el .torrent
|
||||
if not scrapertools.find_single_match(torrent_file, '^d\d+:\w+\d+:'): #No es un archivo .torrent (RAR, ZIP, HTML,..., vacío)
|
||||
logger.error('No es un archivo Torrent: ' + url)
|
||||
torrents_path = ''
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path #Si hay un error, devolvemos el "path" vacío
|
||||
|
||||
if not lookup:
|
||||
filetools.write(torrents_path_encode, torrent_file) #Salvamos el .torrent
|
||||
if not filetools.write(torrents_path_encode, torrent_file): #Salvamos el .torrent
|
||||
logger.error('ERROR: Archivo .torrent no escrito: ' + torrents_path_encode)
|
||||
torrents_path = '' #Si hay un error, devolvemos el "path" vacío
|
||||
torrent_file = '' #... y el buffer del .torrent
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path
|
||||
except:
|
||||
torrents_path = '' #Si hay un error, devolvemos el "path" vacío
|
||||
|
||||
torrent_file = '' #... y el buffer del .torrent
|
||||
logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#logger.debug(torrents_path)
|
||||
if data_torrent:
|
||||
return (torrents_path, torrent_file)
|
||||
return torrents_path
|
||||
|
||||
|
||||
def verify_url_torrent(url, decode_flag=False, timeout=5):
|
||||
def verify_url_torrent(url, timeout=5):
|
||||
"""
|
||||
Verifica si el archivo .torrent al que apunta la url está disponible, descargándolo en un area temporal
|
||||
Entrada: url
|
||||
@@ -874,12 +864,8 @@ def verify_url_torrent(url, decode_flag=False, timeout=5):
|
||||
|
||||
if not url or url == 'javascript:;': #Si la url viene vacía...
|
||||
return False #... volvemos con error
|
||||
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode
|
||||
if torrents_path: #Si ha tenido éxito...
|
||||
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent
|
||||
if torrents_path: #Si ha tenido éxito...
|
||||
return True
|
||||
try:
|
||||
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode
|
||||
if torrents_path: #Si ha tenido éxito...
|
||||
return True
|
||||
except:
|
||||
return False #en caso de error, False
|
||||
else:
|
||||
return False
|
||||
|
||||
@@ -14,6 +14,7 @@ import urllib
|
||||
import urlparse
|
||||
import datetime
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from channelselector import get_thumb
|
||||
from core import httptools
|
||||
@@ -183,7 +184,7 @@ def update_title(item):
|
||||
rating_new = round(rating_new, 1)
|
||||
item.title = item.title.replace("[" + str(rating_old) + "]", "[" + str(rating_new) + "]")
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if item.wanted: #Actualizamos Wanted, si existe
|
||||
item.wanted = item.contentTitle
|
||||
if new_item.contentSeason: #Restauramos el núm. de Temporada después de TMDB
|
||||
@@ -236,7 +237,7 @@ def refresh_screen(item):
|
||||
xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xlistitem) #Preparamos el entorno para evitar error Kod1 18
|
||||
time.sleep(1) #Dejamos tiempo para que se ejecute
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
platformtools.itemlist_update(item) #refrescamos la pantalla con el nuevo Item
|
||||
|
||||
@@ -329,7 +330,7 @@ def post_tmdb_listado(item, itemlist):
|
||||
if rating == 0.0:
|
||||
rating = ''
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
__modo_grafico__ = config.get_setting('modo_grafico', item.channel)
|
||||
|
||||
@@ -346,7 +347,7 @@ def post_tmdb_listado(item, itemlist):
|
||||
try:
|
||||
tmdb.set_infoLabels(item_local, __modo_grafico__) #pasamos otra vez por TMDB
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
logger.error(item_local)
|
||||
|
||||
# Si TMDB no ha encontrado nada y hemos usado el año de la web, lo intentamos sin año
|
||||
@@ -357,7 +358,7 @@ def post_tmdb_listado(item, itemlist):
|
||||
try:
|
||||
tmdb.set_infoLabels(item_local, __modo_grafico__) #pasamos otra vez por TMDB
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if not item_local.infoLabels['tmdb_id']: #ha tenido éxito?
|
||||
item_local.infoLabels['year'] = year #no, restauramos el año y lo dejamos ya
|
||||
|
||||
@@ -539,7 +540,7 @@ def post_tmdb_seasons(item, itemlist):
|
||||
try:
|
||||
tmdb.set_infoLabels(item, True) #TMDB de cada Temp
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
item_season = item.clone()
|
||||
if item_season.season_colapse: #Quitamos el indicador de listado por Temporadas
|
||||
@@ -554,7 +555,7 @@ def post_tmdb_seasons(item, itemlist):
|
||||
rating = float(item_season.infoLabels['rating'])
|
||||
rating = round(rating, 1)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if rating and rating == 0.0:
|
||||
rating = ''
|
||||
|
||||
@@ -586,7 +587,7 @@ def post_tmdb_seasons(item, itemlist):
|
||||
try:
|
||||
tmdb.set_infoLabels(item_local, True) #TMDB de cada Temp
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if item_local.infoLabels['temporada_air_date']: #Fecha de emisión de la Temp
|
||||
item_local.title += ' [%s]' % str(scrapertools.find_single_match(str(item_local.infoLabels['temporada_air_date']), r'\/(\d{4})'))
|
||||
@@ -597,7 +598,7 @@ def post_tmdb_seasons(item, itemlist):
|
||||
# rating = float(item_local.infoLabels['rating'])
|
||||
# rating = round(rating, 1)
|
||||
# except:
|
||||
# pass
|
||||
# logger.error(traceback.format_exc())
|
||||
#if rating and rating > 0.0:
|
||||
# item_local.title += ' [%s]' % str(rating)
|
||||
|
||||
@@ -813,6 +814,7 @@ def post_tmdb_episodios(item, itemlist):
|
||||
num_episodios = item_local.infoLabels['temporada_num_episodios']
|
||||
except:
|
||||
num_episodios = 0
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Preparamos el Rating del vídeo
|
||||
rating = ''
|
||||
@@ -823,7 +825,7 @@ def post_tmdb_episodios(item, itemlist):
|
||||
if rating == 0.0:
|
||||
rating = ''
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
# Si TMDB no ha encontrado el vídeo limpiamos el año
|
||||
if item_local.infoLabels['year'] == "-":
|
||||
@@ -883,7 +885,7 @@ def post_tmdb_episodios(item, itemlist):
|
||||
try:
|
||||
num_episodios_lista[item_local.contentSeason] = num_episodios
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#logger.debug("title: " + item_local.title + " / url: " + item_local.url + " / calidad: " + item_local.quality + " / Season: " + str(item_local.contentSeason) + " / EpisodeNumber: " + str(item_local.contentEpisodeNumber) + " / num_episodios_lista: " + str(num_episodios_lista) + str(num_episodios_flag))
|
||||
#logger.debug(item_local)
|
||||
@@ -900,6 +902,7 @@ def post_tmdb_episodios(item, itemlist):
|
||||
item_local.infoLabels['temporada_num_episodios'] = int(num_episodios_lista[item_local.contentSeason])
|
||||
except:
|
||||
logger.error("ERROR 07: EPISODIOS: Num de Temporada fuera de rango " + " / TEMPORADA: " + str(item_local.contentSeason) + " / " + str(item_local.contentEpisodeNumber) + " / MAX_TEMPORADAS: " + str(num_temporada_max) + " / LISTA_TEMPORADAS: " + str(num_episodios_lista))
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#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", tmdb_stat=False, from_action=item.action, from_title_tmdb=item.title, from_update=True))
|
||||
@@ -938,6 +941,7 @@ def post_tmdb_episodios(item, itemlist):
|
||||
videolibrarytools.save_tvshow(item, itemlist_fake) #Se actualiza el .nfo
|
||||
except:
|
||||
logger.error("ERROR 08: EPISODIOS: No se ha podido actualizar la URL a la nueva Temporada")
|
||||
logger.error(traceback.format_exc())
|
||||
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a Videoteca-[/COLOR]" + title, action="add_serie_to_library"))
|
||||
|
||||
elif modo_serie_temp == 1: #si es Serie damos la opción de guardar la última temporada o la serie completa
|
||||
@@ -1006,6 +1010,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
item.unify = config.get_setting("unify")
|
||||
except:
|
||||
item.unify = config.get_setting("unify")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if item.contentSeason_save: #Restauramos el num. de Temporada
|
||||
item.contentSeason = item.contentSeason_save
|
||||
@@ -1027,7 +1032,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
try:
|
||||
tmdb.set_infoLabels(item, True) #TMDB de cada Temp
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
#Restauramos la información de max num. de episodios por temporada despues de TMDB
|
||||
try:
|
||||
if item.infoLabels['temporada_num_episodios']:
|
||||
@@ -1036,7 +1041,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
else:
|
||||
item.infoLabels['temporada_num_episodios'] = num_episodios
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Ajustamos el nombre de la categoría
|
||||
if item.channel == channel_py:
|
||||
@@ -1068,7 +1073,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
if rating == 0.0:
|
||||
rating = ''
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if item.quality.lower() in ['gb', 'mb']:
|
||||
item.quality = item.quality.replace('GB', 'G B').replace('Gb', 'G b').replace('MB', 'M B').replace('Mb', 'M b')
|
||||
@@ -1085,6 +1090,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
tiempo = item.infoLabels['duration']
|
||||
except:
|
||||
tiempo = item.infoLabels['duration']
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
elif item.contentChannel == 'videolibrary': #No hay, viene de la Videoteca? buscamos en la DB
|
||||
#Leo de la BD de Kodi la duración de la película o episodio. En "from_fields" se pueden poner las columnas que se quiera
|
||||
@@ -1095,7 +1101,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
else:
|
||||
nun_records, records = get_field_from_kodi_DB(item, from_fields='c09') #Leo de la BD de Kodi la duración del episodio
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if nun_records > 0: #Hay registros?
|
||||
#Es un array, busco el campo del registro: añadir en el FOR un fieldX por nueva columna
|
||||
for strFileName, field1 in records:
|
||||
@@ -1111,7 +1117,7 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
if not scrapertools.find_single_match(item.quality, '(\[\d+:\d+)'): #si ya tiene la duración, pasamos
|
||||
item.quality += ' [/COLOR][COLOR white][%s:%s h]' % (str(horas).zfill(2), str(resto).zfill(2)) #Lo agrego a Calidad del Servidor
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Ajustamos el nombre de la categoría
|
||||
if item.channel != channel_py:
|
||||
@@ -1193,8 +1199,9 @@ def post_tmdb_findvideos(item, itemlist):
|
||||
return (item, itemlist)
|
||||
|
||||
|
||||
def get_torrent_size(url):
|
||||
def get_torrent_size(url, data_torrent=False):
|
||||
logger.info()
|
||||
from core import videolibrarytools
|
||||
|
||||
"""
|
||||
|
||||
@@ -1203,9 +1210,11 @@ def get_torrent_size(url):
|
||||
Calcula el tamaño de los archivos que contienen un .torrent. Descarga el archivo .torrent en una carpeta,
|
||||
lo lee y descodifica. Si contiene múltiples archivos, suma el tamaño de todos ellos
|
||||
|
||||
Llamada: generictools.get_torrent_size(url)
|
||||
Llamada: generictools.get_torrent_size(url, data_torrent=False)
|
||||
Entrada: url: url del archivo .torrent
|
||||
Entrada: data_torrent: Flag por si se quiere el contenido del .torretn de vuelta
|
||||
Salida: size: str con el tamaño y tipo de medida ( MB, GB, etc)
|
||||
Salida: torrent: dict() con el contenido del .torrent (opcional)
|
||||
|
||||
"""
|
||||
|
||||
@@ -1271,6 +1280,7 @@ def get_torrent_size(url):
|
||||
|
||||
#Móludo principal
|
||||
size = ""
|
||||
torrent = ''
|
||||
try:
|
||||
#torrents_path = config.get_videolibrary_path() + '/torrents' #path para dejar el .torrent
|
||||
|
||||
@@ -1281,25 +1291,12 @@ def get_torrent_size(url):
|
||||
#urllib.urlretrieve(url, torrents_path + "/generictools.torrent") #desacargamos el .torrent a la carpeta
|
||||
#torrent_file = open(torrents_path + "/generictools.torrent", "rb").read() #leemos el .torrent
|
||||
|
||||
response = httptools.downloadpage(url, timeout=2) #Descargamos el .torrent
|
||||
if not response.sucess:
|
||||
size = ''
|
||||
return size #Si hay un error, devolvemos el "size" vacío
|
||||
torrent_file = response.data
|
||||
torrents_path, torrent_file = videolibrarytools.caching_torrents(url, timeout=2, lookup=True, data_torrent=True)
|
||||
if not torrent_file:
|
||||
if data_torrent:
|
||||
return (size, torrent)
|
||||
return size #Si hay un error, devolvemos el "size" y "torrent" vacíos
|
||||
|
||||
if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso
|
||||
#try:
|
||||
# urllib.urlretrieve("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(),
|
||||
# torrents_path + "/generictools.torrent")
|
||||
# torrent_file = open(torrents_path + "/generictools.torrent", "rb").read()
|
||||
#except:
|
||||
# torrent_file = ""
|
||||
response = httptools.downloadpage("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip())
|
||||
if not response.sucess:
|
||||
size = ''
|
||||
return size #Si hay un error, devolvemos el "size" vacío
|
||||
torrent_file = response.data
|
||||
|
||||
torrent = decode(torrent_file) #decodificamos el .torrent
|
||||
|
||||
#si sólo tiene un archivo, tomamos la longitud y la convertimos a una unidad legible, si no dará error
|
||||
@@ -1311,20 +1308,27 @@ def get_torrent_size(url):
|
||||
|
||||
#si tiene múltiples archivos sumamos la longitud de todos
|
||||
if not size:
|
||||
check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]), "'length': (\d+).*?}")
|
||||
sizet = sum([int(i) for i in check_video])
|
||||
size = convert_size(sizet)
|
||||
try:
|
||||
check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]), "'length': (\d+).*?}")
|
||||
sizet = sum([int(i) for i in check_video])
|
||||
size = convert_size(sizet)
|
||||
except:
|
||||
pass
|
||||
|
||||
except:
|
||||
logger.error('ERROR al buscar el tamaño de un .Torrent: ' + str(url))
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#try:
|
||||
# os.remove(torrents_path + "/generictools.torrent") #borramos el .torrent
|
||||
#except:
|
||||
# pass
|
||||
|
||||
#logger.debug(str(url) + ' / ' + str(size))
|
||||
#logger.debug(str(url))
|
||||
logger.info(str(size))
|
||||
|
||||
if data_torrent:
|
||||
return (size, torrent)
|
||||
return size
|
||||
|
||||
|
||||
@@ -1401,7 +1405,7 @@ def get_field_from_kodi_DB(item, from_fields='*', files='file'):
|
||||
if nun_records == 0: #hay error?
|
||||
logger.error("Error en la SQL: " + sql + ": 0 registros") #No estará catalogada o hay un error en el SQL
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
return (nun_records, records)
|
||||
|
||||
@@ -1455,7 +1459,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
|
||||
verify_torrent, patron1, patron_alt = patron.split('|') #Si es así, los separamos y los tratamos
|
||||
patron = patron1
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Array con los datos de los canales alternativos
|
||||
#Cargamos en .json del canal para ver las listas de valores en settings
|
||||
@@ -1530,6 +1534,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
|
||||
url_alt += [scrapertools.find_single_match(item.url, 'http.*?\/temporada-\d+.*?\/capitulo.?-\d+.*?\/')]
|
||||
except:
|
||||
logger.error("ERROR 88: " + item.action + ": Error al convertir la url: " + item.url)
|
||||
logger.error(traceback.format_exc())
|
||||
logger.debug('URLs convertidas: ' + str(url_alt))
|
||||
|
||||
if patron == True: #solo nos han pedido verificar el clone
|
||||
@@ -1545,6 +1550,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
|
||||
data_comillas = data.replace("'", "\"")
|
||||
except:
|
||||
data = ''
|
||||
logger.error(traceback.format_exc())
|
||||
if not data: #no ha habido suerte, probamos con la siguiente url
|
||||
logger.error("ERROR 01: " + item.action + ": La Web no responde o la URL es erronea: " + url)
|
||||
continue
|
||||
@@ -1700,6 +1706,7 @@ def web_intervenida(item, data, desactivar=True):
|
||||
json.dump(json_data, outfile, sort_keys = True, indent = 2, ensure_ascii = False)
|
||||
except:
|
||||
logger.error("ERROR 98 al salvar el archivo: %s" % channel_path)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#logger.debug(item)
|
||||
|
||||
@@ -1764,10 +1771,11 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
|
||||
delete_stat = 0
|
||||
canal_org_des_list = []
|
||||
json_path_list = []
|
||||
emergency_urls_force = False
|
||||
|
||||
if item.ow_force == '1': #Ha podido qudar activado de una pasada anteriores
|
||||
del item.ow_force
|
||||
logger.error('** item.ow_force: ' + item.path) #aviso que ha habido una incidencia
|
||||
#if item.ow_force == '1': #Ha podido qudar activado de una pasada anteriores
|
||||
# del item.ow_force
|
||||
# logger.error('** item.ow_force: ' + item.path) #aviso que ha habido una incidencia
|
||||
if it.ow_force == '1': #Ha podido qudar activado de una pasada anteriores
|
||||
del it.ow_force
|
||||
if path and it.contentType != 'movies':
|
||||
@@ -1777,6 +1785,7 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
|
||||
logger.error('** .nfo ACTUALIZADO: it.ow_force: ' + nfo) #aviso que ha habido una incidencia
|
||||
except:
|
||||
logger.error('** .nfo ERROR actualizar: it.ow_force: ' + nfo) #aviso que ha habido una incidencia
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Array con los datos de los canales alternativos
|
||||
#Cargamos en .json de Newpct1 para ver las listas de valores en settings
|
||||
@@ -1819,46 +1828,72 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
|
||||
if it.emergency_urls:
|
||||
item.emergency_urls = it.emergency_urls #Refrescar desde el .nfo
|
||||
|
||||
verify_cached_torrents() #TEMPORAL: verificamos si los .torrents son correctos
|
||||
try: #Si ha habido errores, vemos la lista y los reparamos
|
||||
json_error_path = filetools.join(config.get_runtime_path(), 'error_cached_torrents.json')
|
||||
if filetools.exists(json_error_path): #hay erroer que hay que reparar?
|
||||
from core import jsontools
|
||||
json_error_file = jsontools.load(filetools.read(json_error_path)) #Leemos la lista de errores
|
||||
if not json_error_file:
|
||||
filetools.remove(json_error_path) #si ya no quedan errores, borramos el .json
|
||||
elif path in json_error_file: #está este títu,o en la lista de errores?
|
||||
json_error_file.pop(path) #sí. Lo quitamos
|
||||
if not json_error_file:
|
||||
filetools.remove(json_error_path) #si ya no quedan errores, borramos el .json
|
||||
else:
|
||||
filetools.write(json_error_path, jsontools.dump(json_error_file)) #si quedan, actualizamos el .json
|
||||
if item.contentType == 'movie': #si es una pelicula, forzamos su actualización
|
||||
emergency_urls_force = True
|
||||
else: #si es una serie, que regenere los episodios que faltan (en error)
|
||||
item.ow_force = '1' #... de todas las temporadas
|
||||
except:
|
||||
logger.error('Error en el proceso de REPARACION de vídeos con .torrents dañados')
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#Arreglo temporal para Newpct1
|
||||
if channel in fail_over_list or channel_alt == 'videolibrary':
|
||||
channel_bis = channel_py
|
||||
if not item.url and it.library_urls and channel_alt == 'videolibrary':
|
||||
for canal_vid, url_vid in it.library_urls.items(): #Se recorre "item.library_urls" para buscar canales candidatos
|
||||
try:
|
||||
if channel in fail_over_list or channel_alt == 'videolibrary':
|
||||
channel_bis = channel_py
|
||||
if not item.url and it.library_urls and channel_alt == 'videolibrary':
|
||||
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
|
||||
channel_alt = canal_vid
|
||||
channel = "'%s'" % channel_alt
|
||||
break
|
||||
else:
|
||||
channel_bis = canal_vid
|
||||
if channel_bis == channel_py and config.get_setting("emergency_urls", channel_bis) == 1 and config.get_setting("emergency_urls_torrents", channel_bis) and item.emergency_urls and item.emergency_urls.get(channel_alt, False):
|
||||
raiz, carpetas_series, ficheros = filetools.walk(path).next()
|
||||
objetivo = '[%s]_01.torrent' % channel_alt
|
||||
encontrado = False
|
||||
for fichero in ficheros:
|
||||
if objetivo in fichero:
|
||||
encontrado = True
|
||||
break
|
||||
if not encontrado:
|
||||
logger.error('REGENERANDO: ' + str(item.emergency_urls))
|
||||
item.emergency_urls.pop(channel_alt, None)
|
||||
|
||||
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 or emergency_urls_force:
|
||||
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
|
||||
if canal_vid_alt in fail_over_list: #Se busca si es un clone de newpct1
|
||||
channel_bis = channel_py
|
||||
channel_alt = canal_vid
|
||||
channel = "'%s'" % channel_alt
|
||||
break
|
||||
else:
|
||||
channel_bis = canal_vid
|
||||
if channel_bis == channel_py and config.get_setting("emergency_urls", channel_bis) == 1 and config.get_setting("emergency_urls_torrents", channel_bis) and item.emergency_urls and item.emergency_urls.get(channel_alt, False):
|
||||
raiz, carpetas_series, ficheros = filetools.walk(path).next()
|
||||
objetivo = '[%s]_01.torrent' % channel_alt
|
||||
encontrado = False
|
||||
for fichero in ficheros:
|
||||
if objetivo in fichero:
|
||||
encontrado = True
|
||||
break
|
||||
if not encontrado:
|
||||
logger.error('REGENERANDO: ' + str(item.emergency_urls))
|
||||
item.emergency_urls.pop(channel_alt, None)
|
||||
|
||||
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))
|
||||
#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 or emergency_urls_force:
|
||||
intervencion += ", ('1', '%s', '%s', '', '', '', '', '', '', '', '*', '%s', 'emerg')" % (canal_vid, canal_vid, config.get_setting("emergency_urls", channel_bis))
|
||||
except:
|
||||
logger.error('Error en el proceso de ALMACENAMIENTO de URLs de Emergencia')
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
#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
|
||||
@@ -2009,7 +2044,7 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
|
||||
try:
|
||||
response = httptools.downloadpage(url_total, only_headers=True)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if not response.sucess:
|
||||
logger.error('Web ' + canal_des_def.upper() + ' INACTIVA. Regla no procesada: ' + str(canal_org_des_list[i]))
|
||||
item = item_back.clone() #Restauro las imágenes inciales
|
||||
@@ -2122,6 +2157,101 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
|
||||
return (item, it, overwrite)
|
||||
|
||||
|
||||
def verify_cached_torrents():
|
||||
logger.info()
|
||||
import json
|
||||
|
||||
"""
|
||||
Verifica que todos los archivos .torrent estén descomprimidos. Si no lo están, los descomprime y regraba
|
||||
|
||||
Método para uso temporal y controlado
|
||||
|
||||
Deja el archivo verify_cached_torrents.json como marca de que se ha ejecutado para esa versión de Alfa
|
||||
"""
|
||||
|
||||
try:
|
||||
#Localiza los paths donde dejar el archivo .json de control, y de la Videoteca
|
||||
json_path = filetools.exists(filetools.join(config.get_runtime_path(), 'verify_cached_torrents.json'))
|
||||
if json_path:
|
||||
logger.info('Torrents verificados anteriormente: NOS VAMOS')
|
||||
return
|
||||
json_path = filetools.join(config.get_runtime_path(), 'verify_cached_torrents.json')
|
||||
json_error_path = filetools.join(config.get_runtime_path(), 'error_cached_torrents.json')
|
||||
json_error_path_BK = filetools.join(config.get_runtime_path(), 'error_cached_torrents_BK.json')
|
||||
|
||||
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
|
||||
movies = config.get_setting("folder_movies")
|
||||
series = config.get_setting("folder_tvshows")
|
||||
torrents_movies = filetools.join(videolibrary_path, config.get_setting("folder_movies")) #path de CINE
|
||||
torrents_series = filetools.join(videolibrary_path, config.get_setting("folder_tvshows")) #path de SERIES
|
||||
|
||||
#Inicializa variables
|
||||
torren_list = []
|
||||
torren_list.append(torrents_movies)
|
||||
torren_list.append(torrents_series)
|
||||
i = 0
|
||||
j = 0
|
||||
k = 0
|
||||
descomprimidos = []
|
||||
errores = []
|
||||
json_data = dict()
|
||||
|
||||
#Recorre las carpetas de CINE y SERIES de la Videoteca, leyendo, descomprimiendo y regrabando los archivos .torrent
|
||||
for contentType in torren_list:
|
||||
for root, folders, files in filetools.walk(contentType):
|
||||
for file in files:
|
||||
if not '.torrent' in file:
|
||||
continue
|
||||
i += 1
|
||||
torrent_file = ''
|
||||
torrent_path = filetools.join(root, file)
|
||||
torrent_file = filetools.read(torrent_path)
|
||||
if not scrapertools.find_single_match(torrent_file, '^d\d+:\w+\d+:'):
|
||||
logger.debug('Torrent comprimido: DESCOMPRIMIENDO: ' + str(torrent_path))
|
||||
try:
|
||||
torrent_file_deco = ''
|
||||
import zlib
|
||||
torrent_file_deco = zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(torrent_file)
|
||||
except:
|
||||
k += 1
|
||||
errores += [torrent_path]
|
||||
logger.error(traceback.format_exc())
|
||||
logger.error('No es un archivo TORRENT. Archivo borrado: ' + str(torrent_path))
|
||||
if not json_data.get(root, False):
|
||||
json_data[root] = 'ERROR'
|
||||
if scrapertools.find_single_match(file, '^\d+x\d+'):
|
||||
torrent_json = re.sub(r'\]_\d+.torrent$', '].json', torrent_path)
|
||||
filetools.remove(torrent_json)
|
||||
filetools.remove(torrent_path)
|
||||
continue
|
||||
|
||||
if not scrapertools.find_single_match(torrent_file_deco, '^d\d+:\w+\d+:'):
|
||||
logger.error('Error de DESCOMPRESIÓN: ' + str(torrent_path))
|
||||
k += 1
|
||||
errores += [torrent_path]
|
||||
else:
|
||||
filetools.write(torrent_path, torrent_file_deco)
|
||||
j += 1
|
||||
descomprimidos += [torrent_path]
|
||||
else:
|
||||
#logger.info('Torrent OK. No hace falta descompresión: ' + str(torrent_path))
|
||||
h = 0
|
||||
|
||||
if json_data:
|
||||
filetools.write(json_error_path, json.dumps(json_data))
|
||||
filetools.write(json_error_path_BK, json.dumps(json_data))
|
||||
filetools.write(json_path, json.dumps({"torrent_verify": True}))
|
||||
except:
|
||||
logger.error('Error en el proceso de VERIFICACIÓN de los .torrents')
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
logger.error(str(i) + ' archivos .torrent revisados. / ' + str(j) + ' descomporimidos / ' + str(k) + ' errores')
|
||||
if descomprimidos:
|
||||
logger.error('Lista de .torrents DESCOMPRIMIDOS: ' + str(descomprimidos))
|
||||
if errores:
|
||||
logger.error('Lista de .torrents en ERROR: ' + str(errores))
|
||||
|
||||
|
||||
def dejuice(data):
|
||||
logger.info()
|
||||
# Metodo para desobfuscar datos de JuicyCodes
|
||||
|
||||
@@ -1094,27 +1094,37 @@ def play_torrent(item, xlistitem, mediaurl):
|
||||
time.sleep(0.5) #Dejamos tiempo para que se ejecute
|
||||
|
||||
#Nuevo método de descarga previa del .torrent. Si da error, miramos si hay alternatica local. Si ya es local, lo usamos
|
||||
url = ''
|
||||
url_stat = False
|
||||
torrents_path = ''
|
||||
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
|
||||
if not filetools.exists(videolibrary_path): #Si no existe el path, pasamos al modo clásico
|
||||
url_stat = True
|
||||
elif not filetools.exists(videolibrary_path + 'temp_torrents_Alfa'): #Si no existe la carpeta temporal para .torrents, la creamos
|
||||
filetools.mkdir(videolibrary_path + 'temp_torrents_Alfa')
|
||||
torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path de descarga temporal
|
||||
|
||||
videolibrary_path = False
|
||||
else:
|
||||
torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path descarga temporal
|
||||
if videolibrary_path and not filetools.exists(filetools.join(videolibrary_path, 'temp_torrents_Alfa')): #Si no existe la carpeta temporal, la creamos
|
||||
filetools.mkdir(filetools.join(videolibrary_path, 'temp_torrents_Alfa'))
|
||||
|
||||
#identificamos si es una url o un path de archivo. Los Magnets los tratamos de la forma clásica
|
||||
if not item.url.startswith("\\") and not item.url.startswith("/") and not item.url.startswith("magnet:") and not url_stat:
|
||||
timeout = 10
|
||||
if item.torrent_alt:
|
||||
timeout = 5
|
||||
item.url = videolibrarytools.caching_torrents(item.url, torrents_path=torrents_path, timeout=timeout) #Descargamos el .torrent
|
||||
if item.url: url_stat = True
|
||||
|
||||
if not item.url and item.torrent_alt: #Si hay error, se busca un .torrent alternativo
|
||||
item.url = item.torrent_alt #El .torrent alternativo puede estar en una url o en local
|
||||
url = videolibrarytools.caching_torrents(item.url, torrents_path=torrents_path, timeout=timeout) #Descargamos el .torrent
|
||||
if url:
|
||||
url_stat = True
|
||||
item.url = url
|
||||
if "torrentin" in torrent_options[seleccion][1]:
|
||||
item.url = 'file://' + item.url
|
||||
|
||||
if not url and item.torrent_alt: #Si hay error, se busca un .torrent alternativo
|
||||
if (item.torrent_alt.startswith("\\") or item.torrent_alt.startswith("/")) and videolibrary_path:
|
||||
item.url = item.torrent_alt #El .torrent alternativo puede estar en una url o en local
|
||||
elif not item.url.startswith("\\") and not item.url.startswith("/") and not item.url.startswith("magnet:"):
|
||||
item.url = item.torrent_alt
|
||||
|
||||
#Si es un archivo .torrent local, actualizamos el path relativo a path absoluto
|
||||
if item.url.startswith("\\") or item.url.startswith("/") and not url_stat: #.torrent alternativo local
|
||||
if (item.url.startswith("\\") or item.url.startswith("/")) and not url_stat and videolibrary_path: #.torrent alternativo local
|
||||
movies = config.get_setting("folder_movies")
|
||||
series = config.get_setting("folder_tvshows")
|
||||
if item.contentType == 'movie':
|
||||
@@ -1122,7 +1132,11 @@ def play_torrent(item, xlistitem, mediaurl):
|
||||
else:
|
||||
folder = series #o series
|
||||
item.url = filetools.join(videolibrary_path, folder, item.url) #dirección del .torrent local en la Videoteca
|
||||
|
||||
if filetools.copy(item.url, torrents_path, silent=True): #se copia a la carpeta generíca para evitar problemas de encode
|
||||
item.url = torrents_path
|
||||
if "torrentin" in torrent_options[seleccion][1]: #Si es Torrentin, hay que añadir un prefijo
|
||||
item.url = 'file://' + item.url
|
||||
|
||||
mediaurl = urllib.quote_plus(item.url)
|
||||
#Llamada con más parámetros para completar el título
|
||||
if ("quasar" in torrent_options[seleccion][1] or "elementum" in torrent_options[seleccion][1]) and item.infoLabels['tmdb_id']:
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
from platformcode import config, logger, platformtools
|
||||
|
||||
@@ -140,6 +141,7 @@ def check_addon_updates(verbose=False):
|
||||
|
||||
except:
|
||||
logger.error('Error al comprobar actualizaciones del addon!')
|
||||
logger.error(traceback.format_exc())
|
||||
if verbose:
|
||||
platformtools.dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones')
|
||||
return False
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# Service for updating new episodes on library series
|
||||
# ------------------------------------------------------------
|
||||
|
||||
import datetime, imp, math, threading
|
||||
import datetime, imp, math, threading, traceback
|
||||
|
||||
from core import channeltools, filetools, videolibrarytools
|
||||
from platformcode import config, logger
|
||||
@@ -32,7 +32,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
|
||||
serie.category = category
|
||||
serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
channel_enabled = channeltools.is_enabled(serie.channel)
|
||||
|
||||
@@ -89,7 +89,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
|
||||
from platformcode import xbmc_videolibrary
|
||||
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
return insertados_total > 0
|
||||
|
||||
@@ -127,7 +127,7 @@ def check_for_update(overwrite=True):
|
||||
try:
|
||||
serie, serie, overwrite_forced = generictools.redirect_clone_newpct1(serie, head_nfo, serie, path, overwrite, lookup=True)
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
if overwrite_forced == True:
|
||||
overwrite = True
|
||||
serie.update_next = ''
|
||||
@@ -143,7 +143,7 @@ def check_for_update(overwrite=True):
|
||||
if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora
|
||||
serie, estado = videolibrary.verify_playcount_series(serie, path) #También se pasa si falta un PlayCount por completo
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
else:
|
||||
if estado: #Si ha tenido éxito la actualización...
|
||||
estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca
|
||||
@@ -159,7 +159,7 @@ def check_for_update(overwrite=True):
|
||||
from platformcode import xbmc_videolibrary
|
||||
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
|
||||
except:
|
||||
pass
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
continue
|
||||
|
||||
|
||||
Reference in New Issue
Block a user