NewPct1: implantación de apartado de Novedades

This commit is contained in:
Kingbox
2018-07-10 19:26:43 +02:00
parent d85583ca57
commit 3d89989881
3 changed files with 405 additions and 127 deletions

View File

@@ -53,7 +53,7 @@
"id": "clonenewpct1_channels_list",
"type": "text",
"label": "Lista de clones de NewPct1 y orden de uso",
"default": "('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', ''), ('1', 'torrentlocura', 'http://torrentlocura.com/', 'movie, tvshow, season, episode', ''), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'tvsinpagar', 'http://www.tvsinpagar.com/', 'tvshow, season, episode', ''), ('1', 'descargas2020', 'http://descargas2020.com/', 'movie, tvshow, season, episode', ''), ('1', 'mispelisyseries', 'http://mispelisyseries.com/', 'movie', 'search')",
"default": "('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', 'serie_episodios'), ('1', 'torrentlocura', 'http://torrentlocura.com/', 'movie, tvshow, season, episode', ''), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'tvsinpagar', 'http://www.tvsinpagar.com/', 'tvshow, season, episode', ''), ('1', 'descargas2020', 'http://descargas2020.com/', 'movie, tvshow, season, episode', ''), ('1', 'mispelisyseries', 'http://mispelisyseries.com/', 'movie', 'search, listado_busqueda')",
"enabled": true,
"visible": false
},
@@ -560,6 +560,33 @@
"9",
"10"
]
},
{
"id": "clonenewpct1_rango_fechas_novedades",
"type": "list",
"label": "Rango de fechas para búsquedas en Novedades",
"default": 2,
"enabled": true,
"visible": true,
"lvalues": [
"Hoy",
"Ayer",
"Semana",
"Mes",
"Siempre"
]
},
{
"id": "clonenewpct1_serie_episodio_novedades",
"type": "list",
"label": "Ver en Novedades las series como episodios sueltos o serie completa",
"default": 1,
"enabled": true,
"visible": true,
"lvalues": [
"Episodios sueltos",
"Serie completa"
]
}
]
}

View File

@@ -11,6 +11,7 @@ from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import channeltools
from core.item import Item
from platformcode import config, logger
from core import tmdb
@@ -19,7 +20,12 @@ from lib import generictools
channel_py = 'newpct1'
#Código para permitir usar un único canal para todas las webs clones de NewPct1
clone_list = config.get_setting('clonenewpct1_channels_list', channel_py) #Carga lista de clones
#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
break
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
@@ -39,6 +45,13 @@ __modo_grafico__ = config.get_setting('modo_grafico', channel_py)
modo_ultima_temp = config.get_setting('seleccionar_ult_temporadda_activa', channel_py) #Actualización sólo últ. Temporada?
timeout = config.get_setting('clonenewpct1_timeout_downloadpage', channel_py) #Timeout downloadpage
if timeout == 0: timeout = None
fecha_rango = config.get_setting('clonenewpct1_rango_fechas_novedades', channel_py) #Rango fechas para Novedades
if fecha_rango == 0: fecha_rango = 'Hoy'
elif fecha_rango == 1: fecha_rango = 'Ayer'
elif fecha_rango == 2: fecha_rango = 'Semana'
elif fecha_rango == 3: fecha_rango = 'Mes'
elif fecha_rango == 4: fecha_rango = 'Siempre'
episodio_serie = config.get_setting('clonenewpct1_serie_episodio_novedades', channel_py) #Episodio o serie para Novedades
def mainlist(item):
@@ -60,6 +73,8 @@ def mainlist(item):
thumb_buscar = get_thumb("search.png")
thumb_settings = get_thumb("setting_0.png")
itemlist.append(Item(channel=item.channel, action="submenu_novedades", title="Novedades", url=item.channel_host + "ultimas-descargas/", extra="novedades", thumbnail=thumb_pelis, category=item.category, channel_host=item.channel_host))
itemlist.append(Item(channel=item.channel, action="submenu", title="Películas", url=item.channel_host,
extra="peliculas", thumbnail=thumb_pelis, category=item.category, channel_host=item.channel_host))
@@ -88,6 +103,7 @@ def settingCanal(item):
def submenu(item):
logger.info()
itemlist = []
data = ''
@@ -148,6 +164,82 @@ def submenu(item):
return itemlist
def submenu_novedades(item):
logger.info()
itemlist = []
itemlist_alt = []
data = ''
timeout_search=timeout * 2 #Más tiempo para Novedades, que es una búsqueda
#Establecer los valores del .json por si se entra directamente desde un favorito
item.channel_host = host
item.url = host + "ultimas-descargas/"
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
item.extra = "novedades"
try:
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout_search).data)
except:
pass
patron = '<div class="content">.*?<ul class="noticias'
#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):
logger.error("ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL: " + item.url + data)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el submenú
item, data = generictools.fail_over_newpct1(item, patron)
if not data: #Si no ha logrado encontrar nada, salimos
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.category + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL. 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
elif item.channel_alt: #Si ha habido fail-over, lo comento
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.category + '[/COLOR] [ALT ] en uso'))
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible'))
if item.url_alt: del item.url_alt
del item.channel_alt
data = scrapertools.get_match(data, patron) #Seleccionamos el trozo que nos interesa
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
data = data.replace("'", '"').replace('/series"', '/series/"') #Compatibilidad con mispelisy.series.com
patron = '<option value="([^"]+)".*?>(.*?)<\/option>'
matches = re.compile(patron, re.DOTALL).findall(data)
itemlist.append(item.clone(action='', title="[COLOR yellow]Ver lo Último de:[/COLOR]"))
for value, title in matches:
if not value.isdigit():
if title not in "Mes":
item.post = "date=%s" % value
itemlist.append(item.clone(action="listado_busqueda", title=title, url=item.url, post=item.post))
itemlist.append(item.clone(action='', title="[COLOR yellow]Lo Último en la Categoría:[/COLOR]"))
for value, title in matches:
if value.isdigit():
if title not in "Juegos, Software, Musica, Deportes":
#tratamos de poner al principio las categorías más relevantes
if value == '1027': title = "01" + title #Pelis HD
elif value == '757': title = "02" + title #Pelis Castellano
elif value == '1527': title = "03" + title #Pelis Latino
elif value == '1469': title = "04" + title #Series HD
elif value == '767': title = "05" + title #Series
else: title = "99" + title #Resto
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
itemlist_alt.append(item.clone(action="listado_busqueda", title=title, url=item.url, post=item.post))
itemlist_alt = sorted(itemlist_alt, key=lambda it: it.title) #clasificamos
for item_local in itemlist_alt:
item_local.title = re.sub(r'^\d{2}', '', item_local.title) #Borramos la secuencia
itemlist.append(item_local.clone())
return itemlist
def alfabeto(item):
logger.info()
itemlist = []
@@ -483,15 +575,17 @@ def listado_busqueda(item):
#Renombramos el canal al nombre de clone elegido. Actualizados URL
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
#item.channel = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/')
if item.category and item.category != "newest":
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
item.channel_host = host
item.category_new = ''
if item.category:
item.category_new = item.category
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
itemlist = []
cnt_tot = 40 # Poner el num. máximo de items por página. Dejamos que la web lo controle
cnt_title = 0 # Contador de líneas insertadas en Itemlist
cnt_pag = 0 # Contador de líneas leídas de Matches
timeout_search = timeout * 2 # Timeout un poco más largo para las búsquedas
timeout_search = timeout * 2 # Timeout un poco más largo para las búsquedas
if timeout_search < 5:
timeout_search = 5 # Timeout un poco más largo para las búsquedas
data = ''
@@ -527,7 +621,10 @@ def listado_busqueda(item):
pass
cnt_next += 1
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa
if item.extra == "novedades":
pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->' #seleccionamos el bloque que nos interesa
else:
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa
if not data or (not scrapertools.find_single_match(data, pattern) and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data):
logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item.url + item.post + " / DATA: " + data)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el submenú
@@ -543,7 +640,11 @@ def listado_busqueda(item):
#Obtiene la dirección de la próxima página, si la hay
try:
post_actual = item.post #Guardamos el post actual por si hay overflow de Itemlist y hay que hechar marcha atrás
get, post, total_pag = scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+)"(?:\s*onClick=".*?\(\'([^"]+)\'\);">Next<\/a>.*?onClick=".*?\(\'([^"]+)\'\);">Last<\/a>)')
if item.extra == "novedades":
get, post, total_pag = scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+pg\/)(\d+)">Next<\/a>.*?<a\s*href="[^"]+pg\/(\d+)">Last<\/a>')
else:
get, post, total_pag = scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+)"(?:\s*onClick=".*?\(\'([^"]+)\'\);">Next<\/a>.*?onClick=".*?\(\'([^"]+)\'\);">Last<\/a>)')
except:
post = False
cnt_next = 99 #No hay más páginas. Salir del bucle después de procesar ésta
@@ -556,17 +657,29 @@ def listado_busqueda(item):
post_num = int(post)-1 #Guardo página actual
# Preparamos un patron que pretence recoger todos los datos significativos del video
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa
if item.extra == "novedades":
pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->' #seleccionamos el bloque que nos interesa
else:
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa
data_alt = data
data = scrapertools.get_match(data, pattern)
pattern = '<li[^>]*><a href="(?P<scrapedurl>[^"]+).*?' #url
pattern += 'title="(?P<scrapedtitle>[^"]+).*?' #título
pattern += '<img.*?src="(?P<scrapedthumbnail>[^"]+)?".*?' #thumb
pattern += '<h2.*?(?P<calidad>\[.*?)?<\/h2.*?' #calidad
pattern += '<span.*?>\d+-\d+-(?P<year>\d{4})?<\/span>*.?' #año
pattern += '<span.*?>(?P<size>\d+[\.|\s].*?[GB|MB])?<\/span>' #tamaño (significativo para peliculas)
if item.extra == "novedades":
pattern = '<a href="(?P<scrapedurl>[^"]+)"\s?' #url
pattern += 'title="(?P<scrapedtitle>[^"]+)"[^>]*>' #título
pattern += '<img[^>]*src="(?P<scrapedthumbnail>[^"]+)"?.*?' #thumb
pattern += '<\/h2><\/a><span.*?">(?P<calidad>.*?)?' #calidad
pattern += '<(?P<year>.*?)?' #año
pattern += '>Tama.*?\s(?P<size>\d+[.|\s].*?[GB|MB])?\s?<\/strong>' #tamaño (significativo para peliculas)
else:
pattern = '<li[^>]*><a href="(?P<scrapedurl>[^"]+).*?' #url
pattern += 'title="(?P<scrapedtitle>[^"]+).*?' #título
pattern += '<img.*?src="(?P<scrapedthumbnail>[^"]+)?".*?' #thumb
pattern += '<h2.*?(?P<calidad>\[.*?)?<\/h2.*?' #calidad
pattern += '<span.*?>\d+-\d+-(?P<year>\d{4})?<\/span>*.?' #año
pattern += '<span.*?>(?P<size>\d+[\.|\s].*?[GB|MB])?<\/span>' #tamaño (significativo para peliculas)
matches_alt = re.compile(pattern, re.DOTALL).findall(data)
if not matches_alt and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data_alt: #error
if not matches_alt and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data_alt and not '<ul class="noticias-series"></ul></form></div><!-- end .page-box -->' in data_alt: #error
logger.error("ERROR 02: LISTADO_BUSQUEDA: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / DATA: " + data_alt)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: LISTADO_BUSQUEDA: Ha cambiado la estructura de la Web. Reportar el error con el log'))
item, itemlist = generictools.post_tmdb_listado(item, itemlist) #Pintamos los datos de fail-over, si los hay
@@ -648,8 +761,8 @@ def listado_busqueda(item):
#Creamos una copia de Item para cada contenido
item_local = item.clone()
if item_local.category:
del item_local.category
if item_local.category_new:
del item_local.category_new
if item_local.tipo:
del item_local.tipo
if item_local.totalItems:
@@ -666,17 +779,71 @@ def listado_busqueda(item):
del item_local.folder
item_local.title = ''
item_local.context = "['buscar_trailer']"
item_local.contentType = ""
title_subs = []
#Si son episodios sueltos de Series que vienen de Novedades, se busca la url de la Serie
if item.extra == "novedades" and "/serie" in scrapedurl and episodio_serie == 1:
item_local.url = scrapedurl
item_local.extra2 = 'serie_episodios' #Creamos acción temporal excluyente para otros clones
if item_local.category == 'Mispelisyseries': #Esta web no gestiona bien el cambio de episodio a Serie
pattern = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
#Como no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el cambio de episodio por serie
item_local, data_serie = generictools.fail_over_newpct1(item_local, pattern)
else:
try:
data_serie = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item_local.url, timeout=timeout).data)
except:
pass
pattern = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not data_serie or (not scrapertools.find_single_match(data_serie, pattern) and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data and not '<ul class="noticias-series"></ul></form></div><!-- end .page-box -->' in data):
logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item_local.url + " / DATA: " + data_serie)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el cambio de episodio por serie
item_local, data_serie = generictools.fail_over_newpct1(item_local, pattern)
if not data_serie: #Si no ha logrado encontrar nada, salimos
title_subs += ["ERR"]
elif item_local.channel_alt: #Si ha habido fail-over, lo comento
scrapedurl = scrapedurl.replace(item_local.channel_alt, item_local.category.lower())
title_subs += ["ALT"]
try:
pattern = '<div class="content">.*?<h1>.*?<a href="([^"]+)"' #Patron para Serie completa
item_local.url = scrapertools.find_single_match(data_serie, pattern)
if (item.post and '775' in item.post and 'vo/' not in item_local.url) or 'vo/' in scrapedurl: #Son series VO mal formadas?
item_local.url = item_local.url.replace('/series/', '/series-vo/')
#item_local.url = re.sub(r'\/\d+$', '/', item_local.url) #Quitamos el ID de la serie por compatib.
if item_local.url:
title_subs += ["Episodio %sx%s" % (scrapertools.find_single_match(scrapedurl, '\/temp.*?-(\d+)\/cap.*?-(\d+)\/'))]
scrapedurl = item_local.url
except:
pass
if item.extra == "novedades" and "/serie" in scrapedurl:
if not item_local.url or episodio_serie == 0:
item_local.url = scrapedurl
if scrapertools.find_single_match(scrapedurl, '\/temp.*?-(\d+)\/cap.*?-(\d+)\/'):
title_subs += ["Episodio %sx%s" % (scrapertools.find_single_match(scrapedurl, '\/temp.*?-(\d+)\/cap.*?-(\d+)\/'))]
else:
title_subs += ["Episodio 1x01"]
#Establecemos los valores básicos en función del tipo de contenido
if (".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl) and not "/miniseries" in scrapedurl: #Series
if (".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl) and not "/miniseries" in scrapedurl and (not "/capitulo" in scrapedurl or "pelisyseries.com" in item_local.channel_host): #Series
item_local.action = "episodios"
item_local.contentType = "tvshow"
item_local.extra = "series"
elif "varios/" in scrapedurl or "/miniseries" in scrapedurl: #Documentales y varios
elif "varios/" in scrapedurl or "/miniseries" in scrapedurl: #Documentales y varios
item_local.action = "findvideos"
item_local.contentType = "movie"
item_local.extra = "varios"
else: #Películas
elif "/capitulo" in scrapedurl: #Documentales y varios
item_local.action = "findvideos"
item_local.contentType = "episode"
item_local.extra = "series"
else: #Películas
item_local.action = "findvideos"
item_local.contentType = "movie"
item_local.extra = "peliculas"
@@ -686,8 +853,7 @@ def listado_busqueda(item):
title = title.replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u").replace("ü", "u").replace("�", "ñ").replace("ñ", "ñ")
item_local.quality = scrapertools.htmlclean(calidad)
title_subs = []
#Determinamos y marcamos idiomas distintos del castellano
item_local.language = []
if "[vos" in title.lower() or "v.o.s" in title.lower() or "vo" in title.lower() or ".com/pelicula/" in scrapedurl or ".com/series-vo" in scrapedurl or "-vo/" in scrapedurl or "vos" in calidad.lower() or "vose" in calidad.lower() or "v.o.s" in calidad.lower() or "sub" in calidad.lower() or ".com/peliculas-vo" in item.url:
@@ -822,6 +988,11 @@ def listado_busqueda(item):
item_local.contentThumbnail = scrapedthumbnail
#Guardamos el año que puede venir en la url, por si luego no hay resultados desde TMDB
try:
year = int(year)
except:
year = ""
year = str(year)
if year >= "1900" and year <= "2040" and year != "2020":
title_subs += [year]
item_local.infoLabels['year'] = '-'
@@ -830,11 +1001,11 @@ def listado_busqueda(item):
item_local.title_subs = title_subs
# Codigo para rescatar lo que se pueda en pelisy.series.com de Series para la Videoteca. la URL apunta al capítulo y no a la Serie. Nombre de Serie frecuentemente en blanco. Se obtiene de Thumb, así como el id de la serie
if ("/serie" in item_local.url or "-serie" in item_local.url) and "pelisyseries.com" in host:
if ("/serie" in item_local.url or "-serie" in item_local.url) and "pelisyseries.com" in item_local.channel_host:
#Extraer la calidad de la serie basados en la info de la url
if "seriehd" in url:
if "seriehd" in item_local.url:
calidad_mps = "series-hd/"
elif "serievo" in url or "serie-vo" in url:
elif "serievo" in item_local.url or "serie-vo" in item_local.url:
calidad_mps = "series-vo/"
else:
calidad_mps = "series/"
@@ -847,7 +1018,7 @@ def listado_busqueda(item):
#Extraer el ID de la serie desde Thumbs (4 dígitos). Si no hay, nulo
if "/0_" not in scrapedthumbnail and not "no_image" in scrapedthumbnail:
serieid = scrapertools.find_single_match(scrapedthumbnail, r'.*?\/\w\/(?P<serieid>\d+).*?.*')
serieid = scrapertools.find_single_match(scrapedthumbnail, r'\/\w\/(?P<serieid>\d+)')
if len(serieid) > 5:
serieid = ""
else:
@@ -879,13 +1050,14 @@ def listado_busqueda(item):
#logger.debug("url: " + item_local.url + " / title o/n: " + item_local.title + " / " + real_title_mps + " / calidad_mps : " + calidad_mps + " / contentType : " + item_local.contentType)
item_local.title = real_title_mps #Esperemos que el nuevo título esté bien
item_local.title = real_title_mps.replace('-', ' ').title().strip() #Esperemos que el nuevo título esté bien
item_local.contentSerieName = item_local.title
#Agrega el item local a la lista itemlist
itemlist.append(item_local.clone())
if not item.category: #Si este campo no existe es que viene de la primera pasada de una búsqueda global
return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorra tiempo
if not item.category_new: #Si este campo no existe es que viene de la primera pasada de una búsqueda global
return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorra tiempo
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
@@ -901,12 +1073,11 @@ def listado_busqueda(item):
return itemlist
def findvideos(item):
from core import channeltools
logger.info()
#Renombramos el canal al nombre de clone elegido. Actualizados URL
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
#item.channel = 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()
itemlist = []
@@ -1266,10 +1437,16 @@ def episodios(item):
#Renombramos el canal al nombre de clone elegido. Actualizados URL
host = scrapertools.find_single_match(item.url, '(http.?\:\/\/(?:www.)?\w+\.\w+\/)')
#item.channel = 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()
itemlist = []
#Limpiamos num. Temporada y Episodio que ha podido quedar por Novedades
if item.contentSeason:
del item.infoLabels['season']
if item.contentEpisodeNumber:
del item.infoLabels['episode']
# Obtener la información actualizada de la Serie. TMDB es imprescindible para Videoteca
if not item.infoLabels['tmdb_id']:
@@ -1287,10 +1464,14 @@ def episodios(item):
max_temp = max(y)
data = ''
data_alt = ''
try:
if "pelisyseries.com" in item.url:
patron = '<ul class="%s">(.*?)</ul>' % "chapters" # item.pattern
else:
patron = '<ul class="%s">(.*?)</ul>' % "buscar-list" # item.pattern
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout).data)
patron = '<ul class="%s">(.*?)</ul>' % "buscar-list" # item.pattern
data_alt = ''
if data: data_alt = scrapertools.get_match(data, patron)
except: #Algún error de proceso
pass
@@ -1303,6 +1484,7 @@ def episodios(item):
#Verificamos si se ha cargado una página, y si además tiene la estructura correcta
if not data_alt or not scrapertools.find_single_match(data_alt, pattern):
logger.error("ERROR 01: EPISODIOS: La Web no responde o la URL es erronea: " + item.url)
logger.error(pattern + data)
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el vídeo
item, data = generictools.fail_over_newpct1(item, patron, pattern)
@@ -1472,9 +1654,10 @@ def episodios(item):
item_local.infoLabels['episodio_titulo'] = match['lang']
item_local.infoLabels['title'] = item_local.infoLabels['episodio_titulo']
item_local.contentEpisodeNumber = match['episode']
if match['episode'] == 0: match['episode'] = 1 #Evitar errores en Videoteca
item_local.contentEpisodeNumber = match['episode']
if match["episode2"]: #Hay episodio dos? es una entrada múltiple?
item_local.title = "%sx%s al %s -" % (str(match["season"]), str(match["episode"]).zfill(2), str(match["episode2"]).zfill(2)) #Creamos un título con el rango de episodios
else: #Si es un solo episodio, se formatea ya
@@ -1543,6 +1726,7 @@ def search(item, texto):
# texto = texto.replace(" ", "+")
try:
item.url = host + "buscar"
item.post = "q=%s" % texto
item.pattern = "buscar-list"
itemlist = listado_busqueda(item)
@@ -1563,51 +1747,57 @@ def newest(categoria):
item.title = "newest"
item.category = "newest"
item.action = "listado"
item.channel = scrapertools.find_single_match(host, r'(\w+)\.com\/')
item.channel = channel_py
try:
if categoria == 'peliculas':
item.url = host+'peliculas/'
item.url = host + 'ultimas-descargas/'
value = 757
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
item.extra = "novedades"
item.action = "listado_busqueda"
itemlist = listado_busqueda(item)
elif categoria == 'series':
item.url = host + 'ultimas-descargas/'
value = 767
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
item.extra = "novedades"
item.action = "listado_busqueda"
itemlist = listado_busqueda(item)
elif categoria == '4k':
item.url = host + 'ultimas-descargas/'
value = 1027
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
item.extra = "novedades"
item.action = "listado_busqueda"
itemlist = listado_busqueda(item)
elif categoria == 'anime':
item.url = host + 'anime/'
item.extra = "peliculas"
item.action = "listado"
itemlist = listado(item)
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
if categoria == 'series':
item.url = host+'series/'
item.extra = "series"
itemlist.extend(listado(item))
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
if categoria == '4k':
item.url = host+'peliculas-hd/4kultrahd/'
item.extra = "peliculas"
itemlist.extend(listado(item))
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
if categoria == 'anime':
item.url = host+'anime/'
item.extra = "peliculas"
itemlist.extend(listado(item))
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
if categoria == 'documentales':
item.url = host+'documentales/'
item.extra = "varios"
itemlist.extend(listado(item))
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
elif categoria == 'documentales':
item.url = host + 'ultimas-descargas/'
value = 780
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
item.extra = "novedades"
item.action = "listado_busqueda"
itemlist = listado_busqueda(item)
if categoria == 'latino':
item.url = host+'peliculas-latino/'
item.extra = "peliculas"
itemlist.extend(listado(item))
if ">> Página siguiente" in itemlist[-1].title:
itemlist.pop()
elif categoria == 'latino':
item.url = host + 'ultimas-descargas/'
value = 1527
item.post = "categoryIDR=%s&date=%s" % (value, fecha_rango)
item.extra = "novedades"
item.action = "listado_busqueda"
itemlist = listado_busqueda(item)
if ">> Página siguiente" in itemlist[-1].title or "Pagina siguiente >>" in itemlist[-1].title:
itemlist.pop()
# Se captura la excepción, para no interrumpir al canal novedades si un canal falla
except:

View File

@@ -17,6 +17,7 @@ from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import channeltools
from core.item import Item
from platformcode import config, logger
from core import tmdb
@@ -57,6 +58,7 @@ def update_title(item):
Si lo hace en "Completar Información", cambia al nuevo título, pero no busca en TMDB. Hay que hacerlo de nuevo
Si se cancela la segunda pantalla, la variable "scraper_return" estará en False. El usuario no quiere seguir
"""
#logger.debug(item)
#Restauramos y borramos las etiquetas intermedias (si se ha llamado desde el canal)
if item.from_action:
@@ -65,14 +67,16 @@ def update_title(item):
if item.from_title:
item.title = item.from_title
del item.from_title
else:
if item.contentType != "movie":
item.add_videolibrary = True #Estamos Añadiendo a la Videoteca. Indicador para control de uso de los Canales
else:
if item.channel == channel_py: #Si es una peli de NewPct1, ponemos el nombre del clone
item.channel = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/')
elif item.contentType != "movie":
item.add_videolibrary = True #Estamos Añadiendo a la Videoteca. Indicador para control de uso de los Canales
if item.contentType == "movie":
if item.channel == channel_py: #Si es una peli de NewPct1, ponemos el nombre del clone
item.channel = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/')
if item.channel_host: #Borramos ya el indicador para que no se guarde en la Videoteca
del item.channel_host
if item.contentTitle:
item.contentTitle = re.sub(r' -%s-' % item.category, '', item.contentTitle)
item.title = re.sub(r' -%s-' % item.category, '', item.title)
#Sólo ejecutamos este código si no se ha hecho antes en el Canal. Por ejemplo, si se ha llamado desde Episodios,
#ya no se ejecutará al Añadia a Videoteca, aunque desde el canal se podrá llamar tantas veces como se quiera,
@@ -114,29 +118,31 @@ def update_title(item):
item.tmdb_stat = True #Marcamos Item como procesado correctamente por TMDB (pasada 1)
#Si el usuario ha seleccionado una opción distinta o cambiado algo, ajustamos los títulos
if new_item.contentSerieName: #Si es serie...
item.title = item.title.replace(new_item.contentSerieName, item.contentTitle)
item.contentSerieName = item.contentTitle
if new_item.contentSeason: item.contentSeason = new_item.contentSeason #Restauramos Temporada
if item.infoLabels['title']: del item.infoLabels['title'] #Borramos título de peli (es serie)
else: #Si es película...
item.title = item.title.replace(new_item.contentTitle, item.contentTitle)
if new_item.infoLabels['year']: #Actualizamos el Año en el título
item.title = item.title.replace(str(new_item.infoLabels['year']), str(item.infoLabels['year']))
if new_item.infoLabels['rating']: #Actualizamos en Rating en el título
rating_old = ''
if new_item.infoLabels['rating'] and new_item.infoLabels['rating'] != '0.0':
rating_old = float(new_item.infoLabels['rating'])
rating_old = round(rating_old, 1)
rating_new = ''
if item.infoLabels['rating'] and item.infoLabels['rating'] != '0.0':
rating_new = float(item.infoLabels['rating'])
rating_new = round(rating_new, 1)
item.title = item.title.replace("[" + str(rating_old) + "]", "[" + str(rating_new) + "]")
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
item.contentSeason = new_item.contentSeason
if item.tmdb_stat == True:
if new_item.contentSerieName: #Si es serie...
item.title_from_channel = new_item.contentSerieName #Guardo el título incial para Filtertools
item.title = item.title.replace(new_item.contentSerieName, item.contentTitle)
item.contentSerieName = item.contentTitle
if new_item.contentSeason: item.contentSeason = new_item.contentSeason #Restauramos Temporada
if item.infoLabels['title']: del item.infoLabels['title'] #Borramos título de peli (es serie)
else: #Si es película...
item.title = item.title.replace(new_item.contentTitle, item.contentTitle)
if new_item.infoLabels['year']: #Actualizamos el Año en el título
item.title = item.title.replace(str(new_item.infoLabels['year']), str(item.infoLabels['year']))
if new_item.infoLabels['rating']: #Actualizamos en Rating en el título
rating_old = ''
if new_item.infoLabels['rating'] and new_item.infoLabels['rating'] != '0.0':
rating_old = float(new_item.infoLabels['rating'])
rating_old = round(rating_old, 1)
rating_new = ''
if item.infoLabels['rating'] and item.infoLabels['rating'] != '0.0':
rating_new = float(item.infoLabels['rating'])
rating_new = round(rating_new, 1)
item.title = item.title.replace("[" + str(rating_old) + "]", "[" + str(rating_new) + "]")
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
item.contentSeason = new_item.contentSeason
#Para evitar el "efecto memoria" de TMDB, se le llama con un título ficticio para que resetee los buffers
if item.contentSerieName:
@@ -172,6 +178,7 @@ def post_tmdb_listado(item, itemlist):
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
"""
#logger.debug(item)
#Borramos valores si ha habido fail-over
channel_alt = ''
@@ -181,12 +188,14 @@ def post_tmdb_listado(item, itemlist):
if item.url_alt:
del item.url_alt
#Ajustamos el nombre de la categoría
if item.category != "newest":
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
if not item.category_new:
item.category_new = ''
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
for item_local in itemlist: #Recorremos el Itenlist generado por el canal
title = item_local.title
#logger.debug(item_local)
if item_local.contentSeason_save: #Restauramos el num. de Temporada
item_local.contentSeason = item_local.contentSeason_save
@@ -197,8 +206,7 @@ def post_tmdb_listado(item, itemlist):
del item_local.url_alt
#Ajustamos el nombre de la categoría
if item_local.category != "newest":
item_local.category = scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
item_local.category = scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
#Restauramos la info adicional guarda en la lista title_subs, y la borramos de Item
title_add = ' '
@@ -211,9 +219,9 @@ def post_tmdb_listado(item, itemlist):
if not item_local.infoLabels['year'] or item_local.infoLabels['year'] == "-":
item_local.infoLabels['year'] = scrapertools.find_single_match(title_subs, r'(\d{4})')
continue
title_add = title_add.rstrip()
title_add += '%s -%s-' % (title_add, title_subs) #se agregan el resto de etiquetas salvadas
title_add = '%s -%s-' % (title_add, title_subs) #se agregan el resto de etiquetas salvadas
item_local.title_subs = []
del item_local.title_subs
@@ -233,7 +241,7 @@ def post_tmdb_listado(item, itemlist):
# Para Episodios, tomo el año de exposición y no el de inicio de la serie
elif item_local.infoLabels['aired']:
item_local.infoLabels['year'] = scrapertools.find_single_match(str(item_local.infoLabels['aired']), r'\/(\d{4})')
# Preparamos el título para series, con los núm. de temporadas, si las hay
if item_local.contentType in ['season', 'tvshow', 'episode']:
if item_local.infoLabels['title']: del item_local.infoLabels['title']
@@ -252,8 +260,14 @@ def post_tmdb_listado(item, itemlist):
item_local.infoLabels['episodio_titulo'] = '%s, %s [%s] [%s]' % (item_local.infoLabels['episodio_titulo'], item_local.contentSerieName, item_local.infoLabels['year'], rating)
else: #Si no hay título de episodio, ponermos el nombre de la serie
title = '%s %s' % (title, item_local.contentSerieName)
if item_local.contentSerieName not in title:
title = '%s %s' % (title, item_local.contentSerieName)
item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.contentSerieName, item_local.infoLabels['year'], rating)
if not item_local.contentSeason or not item_local.contentEpisodeNumber:
if "Episodio" in title_add:
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(title_add, 'Episodio (\d+)x(\d+)')
title = '%s [%s] [%s]' % (title, item_local.infoLabels['year'], rating)
elif item_local.contentType == "season":
if not item_local.contentSeason:
@@ -271,7 +285,7 @@ def post_tmdb_listado(item, itemlist):
elif item.action == "search":
title += " -Serie-"
elif item_local.extra == "varios" and item.action == "search":
elif item_local.extra == "varios" and (item.action == "search" or item.action == "listado_busqueda"):
title += " -Varios-"
item_local.contentTitle += " -Varios-"
@@ -282,7 +296,7 @@ def post_tmdb_listado(item, itemlist):
title = '%s [COLOR yellow][%s][/COLOR] [%s] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (title, str(item_local.infoLabels['year']), rating, item_local.quality, str(item_local.language))
else: #Si Titulos Inteligentes SÍ seleccionados:
title = title.replace("[", "-").replace("]", "-")
title = title.replace("[", "-").replace("]", "-").replace(".", ",")
#Limpiamos las etiquetas vacías
if item_local.infoLabels['episodio_titulo']:
@@ -291,10 +305,13 @@ def post_tmdb_listado(item, itemlist):
title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', title).strip()
title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', title).strip()
if item.category == "newest": #Viene de Novedades. Marcamos el título con el nombre del canal
if item.category_new == "newest": #Viene de Novedades. Marcamos el título con el nombre del canal
title += ' -%s-' % scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
if item_local.contentType == "movie":
item_local.contentTitle += ' -%s-' % scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
elif "Episodio " in title:
if not item_local.contentSeason or not item_local.contentEpisodeNumber:
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(title_add, 'Episodio (\d+)x(\d+)')
item_local.title = title
@@ -303,10 +320,12 @@ def post_tmdb_listado(item, itemlist):
#logger.debug(item_local)
#Si ha habido fail-over, lo comento
if channel_alt:
if channel_alt and item.category_new != "newest":
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.category + '[/COLOR] [ALT ] en uso'))
itemlist.append(item.clone(action='', title="[COLOR yellow]" + channel_alt.capitalize() + '[/COLOR] inaccesible'))
del item.category_new
return (item, itemlist)
@@ -329,6 +348,7 @@ def post_tmdb_episodios(item, itemlist):
item, itemlist = generictools.post_tmdb_episodios(item, itemlist)
"""
#logger.debug(item)
modo_serie_temp = ''
if config.get_setting('seleccionar_serie_temporada', item.channel) >= 0:
@@ -371,6 +391,8 @@ def post_tmdb_episodios(item, itemlist):
if item.url_alt:
item.url = item.url_alt
del item.url_alt
if item.title_from_channel:
del item.title_from_channel
for item_local in itemlist: #Recorremos el Itenlist generado por el canal
if item_local.add_videolibrary:
@@ -379,6 +401,8 @@ def post_tmdb_episodios(item, itemlist):
del item_local.add_menu
if item_local.contentSeason_save:
del item_local.contentSeason_save
if item_local.title_from_channel:
del item_local.title_from_channel
#Ajustamos el nombre de la categoría si es un clone de NewPct1
item_local.category = scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
@@ -538,20 +562,20 @@ 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")
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a la Videoteca[/COLOR]" + title, action="add_serie_to_library"))
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
itemlist.append(item.clone(title="[COLOR yellow]Añadir última Temp. a Videoteca[/COLOR]" + title, action="add_serie_to_library", contentType="season", contentSeason=contentSeason, url=item_local.url, add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a Videoteca[/COLOR]" + title, action="add_serie_to_library", contentType="tvshow", add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir última Temp. a Videoteca-[/COLOR]" + title, action="add_serie_to_library", contentType="season", contentSeason=contentSeason, url=item_local.url, add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a Videoteca-[/COLOR]" + title, action="add_serie_to_library", contentType="tvshow", add_menu=True))
else: #si no, damos la opción de guardar la temporada actual o la serie completa
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a Videoteca[/COLOR]" + title, action="add_serie_to_library", contentType="tvshow", add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Serie a Videoteca-[/COLOR]" + title, action="add_serie_to_library", contentType="tvshow", add_menu=True))
if item.add_videolibrary and not item.add_menu:
item.contentSeason = contentSeason
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Temp. a Videoteca[/COLOR]" + title, action="add_serie_to_library", contentType="season", contentSeason=contentSeason, add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta Temp. a Videoteca-[/COLOR]" + title, action="add_serie_to_library", contentType="season", contentSeason=contentSeason, add_menu=True))
else: #Es un canal estándar, sólo una linea de Añadir a Videoteca
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta serie a la videoteca[/COLOR]" + title, action="add_serie_to_library", extra="episodios", add_menu=True))
itemlist.append(item.clone(title="[COLOR yellow]Añadir esta serie a videoteca-[/COLOR]" + title, action="add_serie_to_library", extra="episodios", add_menu=True))
#Si ha habido fail-over, lo comento
if channel_alt:
@@ -618,7 +642,12 @@ def post_tmdb_findvideos(item, itemlist):
item.infoLabels['temporada_num_episodios'] = num_episodios
except:
pass
#Quitamos el la categoría o nombre del título, si lo tiene
if item.contentTitle:
item.contentTitle = re.sub(r' -%s-' % item.category, '', item.contentTitle)
item.title = re.sub(r' -%s-' % item.category, '', item.title)
#Limpiamos de año y rating de episodios
if item.infoLabels['episodio_titulo']:
item.infoLabels['episodio_titulo'] = re.sub(r'\s?\[.*?\]', '', item.infoLabels['episodio_titulo'])
@@ -665,6 +694,7 @@ def post_tmdb_findvideos(item, itemlist):
title_gen = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', title_gen).strip() #Quitamos etiquetas vacías
title_gen = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', title_gen).strip() #Quitamos colores vacíos
title_gen = title_gen.replace(" []", "").strip() #Quitamos etiquetas vacías
title_videoteca = title_gen #Salvamos el título para Videoteca
if not item.unify: #Si Titulos Inteligentes NO seleccionados:
title_gen = '**- [COLOR gold]Enlaces Ver: [/COLOR]%s[COLOR gold] -**[/COLOR]' % (title_gen)
@@ -681,6 +711,14 @@ def post_tmdb_findvideos(item, itemlist):
item.server = ""
itemlist.append(item.clone(title=title_gen)) #Título con todos los datos del vídeo
#agregamos la opción de Añadir a Videoteca para péliculas (no series)
if item.contentType == 'movie' and item.contentChannel != "videolibrary":
itemlist.append(item.clone(title="**-[COLOR yellow] Añadir a la videoteca [/COLOR]-**", action="add_pelicula_to_library", extra="películas", from_title=title_videoteca))
#Añadimos la opción de ver trailers
if item.contentChannel != "videolibrary":
itemlist.append(item.clone(channel="trailertools", title="**-[COLOR magenta] Buscar Trailer [/COLOR]-**", action="buscartrailer", context=""))
#logger.debug(item)
return (item, itemlist)
@@ -713,16 +751,28 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
- Saida: data: devuelve los datos del la nueva web. Si vuelve vacía es que no se ha encontrado alternativa
"""
#logger.debug(item)
if timeout == None:
timeout = config.get_setting('clonenewpct1_timeout_downloadpage', channel_py) #Timeout downloadpage
if timeout == 0: timeout = None
if item.action == "search" or item.action == "listado_busqueda": timeout = timeout * 2 #Mas tiempo para búsquedas
data = ''
channel_failed = ''
if not item.category:
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
if not item.extra2:
item.extra2 = 'z9z8z7z6z5'
#Array con los datos de los canales alternativos
fail_over_list = config.get_setting('clonenewpct1_channels_list', channel_py)
#Cargamos en .json del canal para ver las listas de valores en settings
fail_over_list = channeltools.get_channel_json(channel_py)
for settings in fail_over_list['settings']: #Se recorren todos los settings
if settings['id'] == "clonenewpct1_channels_list": #Encontramos en setting
fail_over_list = settings['default'] #Carga lista de clones
break
#fail_over_list = config.get_setting('clonenewpct1_channels_list', channel_py)
fail_over_list = ast.literal_eval(fail_over_list)
#Recorremos el Array identificando el canal que falla
@@ -738,17 +788,18 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
channel_url_failed = item.url #salvamos la url
if (item.action == 'episodios' or item.action == 'findvideos') and item.contentType not in contentType: #soporta el fail_over de este contenido?
data = ''
logger.error("ERROR 99: " + item.action.upper() + ": Acción no soportada para Fail-Over en canal: " + item.url)
return (item, data) #no soporta el fail_over de este contenido, no podemos hacer nada
break
if not channel_failed:
logger.debug(item)
logger.error(item)
return (item, data) #Algo no ha funcionado, no podemos hacer nada
#Recorremos el Array identificando canales activos que funcionen, distintos del caído, que soporten el contenido
for active, channel, channel_host, contentType, action_excluded in fail_over_list:
data_alt = ''
if channel == channel_failed or active == '0' or item.action in action_excluded: #es válido el nuevo canal?
if channel == channel_failed or active == '0' or item.action in action_excluded or item.extra2 in action_excluded: #es válido el nuevo canal?
continue
if (item.action == 'episodios' or item.action == 'findvideos') and item.contentType not in contentType: #soporta el contenido?
continue
@@ -787,6 +838,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
data_alt = scrapertools.find_single_match(data_alt, patron2)
if not data_alt: #no ha habido suerte, probamos con el siguiente canal
logger.error("ERROR 02: " + item.action + ": Ha cambiado la estructura de la Web: " + item.url + " / Patron: " + patron)
data = ''
continue
else:
break #por fin !!! Este canal parece que funciona
@@ -795,6 +847,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
data = ''
continue
del item.extra2 #Borramos acción temporal excluyente
if not data: #Si no ha logrado encontrar nada, salimos limpiando variables
if item.channel == channel_py:
if item.channel_alt:
@@ -809,6 +862,8 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
del item.url_alt
item.channel_host = channel_host_failed
#logger.debug(item)
return (item, data)
@@ -832,7 +887,13 @@ def redirect_clone_newpct1(item):
"""
#Array con los datos de los canales alternativos
fail_over_list = config.get_setting('clonenewpct1_channels_list', channel_py)
#Cargamos en .json del canal para ver las listas de valores en settings
fail_over_list = channeltools.get_channel_json(channel_py)
for settings in fail_over_list['settings']: #Se recorren todos los settings
if settings['id'] == "clonenewpct1_channels_list": #Encontramos en setting
fail_over_list = settings['default'] #Carga lista de clones
break
#fail_over_list = config.get_setting('clonenewpct1_channels_list', channel_py)
channel = "'%s'" % item.channel
if channel in fail_over_list: