Merge pull request #427 from lopezvg/master

NewPct1: clon Planetatorrent añadido
This commit is contained in:
Alfa
2018-09-05 14:12:16 -05:00
committed by GitHub
13 changed files with 779 additions and 661 deletions
+10 -10
View File
@@ -100,14 +100,14 @@ def categorias(item):
if not data: #Si no ha logrado encontrar nada, salimos if not data: #Si no ha logrado encontrar nada, salimos
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')) 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches: if not matches:
logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug(item.url_plus) #logger.debug(item.url_plus)
#logger.debug(matches) #logger.debug(matches)
@@ -173,7 +173,7 @@ def listado(item):
cnt_tot = 40 # Poner el num. máximo de items por página cnt_tot = 40 # Poner el num. máximo de items por página
cnt_title = 0 # Contador de líneas insertadas en Itemlist cnt_title = 0 # Contador de líneas insertadas en Itemlist
inicio = time.time() # Controlaremos que el proceso no exceda de un tiempo razonable inicio = time.time() # Controlaremos que el proceso no exceda de un tiempo razonable
fin = inicio + 10 # Después de este tiempo pintamos (segundos) fin = inicio + 10 # Después de este tiempo pintamos (segundos)
timeout_search = timeout # Timeout para descargas timeout_search = timeout # Timeout para descargas
if item.extra == 'search': if item.extra == 'search':
@@ -182,8 +182,8 @@ def listado(item):
timeout_search = 5 # Timeout un poco más largo para las búsquedas timeout_search = 5 # Timeout un poco más largo para las búsquedas
#Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios #Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios
title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas
if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada
title_lista.extend(item.title_lista) # Se usa la lista de páginas anteriores en Item title_lista.extend(item.title_lista) # Se usa la lista de páginas anteriores en Item
del item.title_lista # ... limpiamos del item.title_lista # ... limpiamos
@@ -206,7 +206,7 @@ def listado(item):
if not data and not item.extra2: #Si la web está caída salimos sin dar error if not data and not item.extra2: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 break #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Patrón para todo, menos para Series completas, incluido búsquedas en cualquier caso #Patrón para todo, menos para Series completas, incluido búsquedas en cualquier caso
patron = '<tr><td(?: class="[^"]+")?><a href="([^"]+)".?title="([^"]+)".*?<\/a><\/td><td(?: class="[^"]+")?>(?:<a href="[^"]+">)?(.*?)(?:<\/a>)?<\/td><td(?: class="[^"]+")?>.*?<\/td><td(?: class="[^"]+")?>(.*?)<\/td><\/tr>' patron = '<tr><td(?: class="[^"]+")?><a href="([^"]+)".?title="([^"]+)".*?<\/a><\/td><td(?: class="[^"]+")?>(?:<a href="[^"]+">)?(.*?)(?:<\/a>)?<\/td><td(?: class="[^"]+")?>.*?<\/td><td(?: class="[^"]+")?>(.*?)<\/td><\/tr>'
@@ -224,7 +224,7 @@ def listado(item):
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
@@ -547,7 +547,7 @@ def episodios(item):
itemlist = [] itemlist = []
item.category = categoria item.category = categoria
logger.debug(item) #logger.debug(item)
if item.from_title: if item.from_title:
item.title = item.from_title item.title = item.from_title
@@ -616,8 +616,8 @@ def episodios(item):
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
logger.debug(matches) #logger.debug(matches)
#logger.debug(data) #logger.debug(data)
season = max_temp season = max_temp
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "Elite Torrent", "name": "Elite Torrent",
"active": true, "active": true,
"adult": false, "adult": false,
"language": ["*"], "language": ["cast", "lat"],
"thumbnail": "elitetorrent.png", "thumbnail": "elitetorrent.png",
"banner": "elitetorrent.png", "banner": "elitetorrent.png",
"categories": [ "categories": [
+44 -44
View File
@@ -49,14 +49,14 @@ def submenu(item):
if not data: if not data:
logger.error("ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL: " + item.url) logger.error("ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL: " + item.url)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log'))
return itemlist #Algo no funciona, pintamos lo que tenemos return itemlist #Algo no funciona, pintamos lo que tenemos
patron = '<div class="cab_menu">.*?<\/div>' #Menú principal patron = '<div class="cab_menu">.*?<\/div>' #Menú principal
data1 = scrapertools.get_match(data, patron) data1 = scrapertools.get_match(data, patron)
patron = '<div id="menu_langen">.*?<\/div>' #Menú de idiomas patron = '<div id="menu_langen">.*?<\/div>' #Menú de idiomas
data1 += scrapertools.get_match(data, patron) data1 += scrapertools.get_match(data, patron)
patron = '<a href="(.*?)".*?title="(.*?)"' #Encontrar todos los apartados patron = '<a href="(.*?)".*?title="(.*?)"' #Encontrar todos los apartados
matches = re.compile(patron, re.DOTALL).findall(data1) matches = re.compile(patron, re.DOTALL).findall(data1)
if not matches: if not matches:
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
@@ -68,25 +68,25 @@ def submenu(item):
logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data1) logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data1)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
for scrapedurl, scrapedtitle in matches: for scrapedurl, scrapedtitle in matches:
scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').strip() scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').strip()
scrapedtitle = scrapedtitle.replace(" torrent", "").replace(" Torrent", "").replace("Series y ", "").title() scrapedtitle = scrapedtitle.replace(" torrent", "").replace(" Torrent", "").replace("Series y ", "").title()
if "castellano" in scrapedtitle.lower(): #Evita la entrada de peliculas castellano del menú de idiomas if "castellano" in scrapedtitle.lower(): #Evita la entrada de peliculas castellano del menú de idiomas
continue continue
if item.extra == "series": #Tratamos Series if item.extra == "series": #Tratamos Series
if not "/serie" in scrapedurl: if not "/serie" in scrapedurl:
continue continue
else: #Tratamos Películas else: #Tratamos Películas
if "/serie" in scrapedurl: if "/serie" in scrapedurl:
continue continue
itemlist.append(item.clone(action="listado", title=scrapedtitle, url=scrapedurl)) itemlist.append(item.clone(action="listado", title=scrapedtitle, url=scrapedurl))
if item.extra == "series": #Añadimos Series VOSE que está fuera del menú principal if item.extra == "series": #Añadimos Series VOSE que está fuera del menú principal
itemlist.append(item.clone(action="listado", title="Series VOSE", url=host + "/series-vose/")) itemlist.append(item.clone(action="listado", title="Series VOSE", url=host + "/series-vose/"))
return itemlist return itemlist
@@ -103,24 +103,24 @@ def listado(item):
except: except:
pass pass
if not data: #Si la web está caída salimos sin dar error if not data: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
patron = '<div id="principal">.*?<\/nav><\/div><\/div>' patron = '<div id="principal">.*?<\/nav><\/div><\/div>'
data = scrapertools.find_single_match(data, patron) data = scrapertools.find_single_match(data, patron)
patron = '<li>.*?<a href="(.*?)".*?' #url patron = '<li>.*?<a href="(.*?)".*?' #url
patron += 'title="(.*?)".*?' #título patron += 'title="(.*?)".*?' #título
patron += 'src="(.*?)".*?' #thumb patron += 'src="(.*?)".*?' #thumb
patron += "title='(.*?)'.*?" #categoría, idioma patron += "title='(.*?)'.*?" #categoría, idioma
patron += '"><i>(.*?)<\/i><\/span.*?' #calidad patron += '"><i>(.*?)<\/i><\/span.*?' #calidad
patron += '="dig1">(.*?)<.*?' #tamaño patron += '="dig1">(.*?)<.*?' #tamaño
patron += '="dig2">(.*?)<\/span><\/div>' #tipo tamaño patron += '="dig2">(.*?)<\/span><\/div>' #tipo tamaño
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches and not '<title>503 Backend fetch failed</title>' in data: #error if not matches and not '<title>503 Backend fetch failed</title>' in data: #error
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
item, itemlist = generictools.post_tmdb_listado(item, itemlist) #Llamamos al método para el pintado del error item, itemlist = generictools.post_tmdb_listado(item, itemlist) #Llamamos al método para el pintado del error
@@ -128,21 +128,21 @@ def listado(item):
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
#logger.debug(data) #logger.debug(data)
for scrapedurl, scrapedtitle, scrapedthumbnail, scrapedcategory, scrapedcalidad, scrapedsize, scrapedsizet in matches: for scrapedurl, scrapedtitle, scrapedthumbnail, scrapedcategory, scrapedcalidad, scrapedsize, scrapedsizet in matches:
item_local = item.clone() #Creamos copia de Item para trabajar item_local = item.clone() #Creamos copia de Item para trabajar
title = re.sub('\r\n', '', scrapedtitle).decode('utf8').strip() title = re.sub('\r\n', '', scrapedtitle).decode('utf8').strip()
title = title.replace(" torrent", "").replace(" Torrent", "").replace("Series y ", "") title = title.replace(" torrent", "").replace(" Torrent", "").replace("Series y ", "")
item_local.url = urlparse.urljoin(host, scrapedurl) item_local.url = urlparse.urljoin(host, scrapedurl)
item_local.thumbnail = urlparse.urljoin(host, scrapedthumbnail) item_local.thumbnail = urlparse.urljoin(host, scrapedthumbnail)
if "---" in scrapedcalidad: #limpiamos calidades if "---" in scrapedcalidad: #limpiamos calidades
scrapedcalidad = '' scrapedcalidad = ''
if "microhd" in title.lower(): if "microhd" in title.lower():
item_local.quality = "microHD" item_local.quality = "microHD"
@@ -158,7 +158,7 @@ def listado(item):
else: else:
item_local.quality += ' [%s %s]' % (scrapedsize.replace(".", ","), scrapedsizet) item_local.quality += ' [%s %s]' % (scrapedsize.replace(".", ","), scrapedsizet)
item_local.language = [] #Verificamos el idioma por si encontramos algo item_local.language = [] #Verificamos el idioma por si encontramos algo
if "latino" in scrapedcategory.lower() or "latino" in item.url or "latino" in title.lower(): if "latino" in scrapedcategory.lower() or "latino" in item.url or "latino" in title.lower():
item_local.language += ["LAT"] item_local.language += ["LAT"]
if "ingles" in scrapedcategory.lower() or "ingles" in item.url or "vose" in scrapedurl or "vose" in item.url: if "ingles" in scrapedcategory.lower() or "ingles" in item.url or "vose" in scrapedurl or "vose" in item.url:
@@ -175,7 +175,7 @@ def listado(item):
title = re.sub(r'\??\s?\d*?\&.*', '', title).title().strip() title = re.sub(r'\??\s?\d*?\&.*', '', title).title().strip()
item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título
if item_local.extra == "peliculas": #preparamos Item para películas if item_local.extra == "peliculas": #preparamos Item para películas
if "/serie" in scrapedurl or "/serie" in item.url: if "/serie" in scrapedurl or "/serie" in item.url:
continue continue
if not "/serie" in scrapedurl and not "/serie" in item.url: if not "/serie" in scrapedurl and not "/serie" in item.url:
@@ -183,7 +183,7 @@ def listado(item):
item_local.contentTitle = title item_local.contentTitle = title
item_local.extra = "peliculas" item_local.extra = "peliculas"
if item_local.extra == "series": #preparamos Item para series if item_local.extra == "series": #preparamos Item para series
if not "/serie" in scrapedurl and not "/serie" in item.url: if not "/serie" in scrapedurl and not "/serie" in item.url:
continue continue
if "/serie" in scrapedurl or "/serie" in item.url: if "/serie" in scrapedurl or "/serie" in item.url:
@@ -202,7 +202,7 @@ def listado(item):
item_local.contentEpisodeNumber = 1 item_local.contentEpisodeNumber = 1
item_local.contentSerieName = title item_local.contentSerieName = title
if epi_mult: if epi_mult:
title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(epi_mult).zfill(2)) #Creamos un título con el rango de episodios title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(epi_mult).zfill(2)) #Creamos un título con el rango de episodios
else: else:
title = '%sx%s ' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2)) title = '%sx%s ' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
@@ -214,7 +214,7 @@ def listado(item):
if item.category: #Si este campo no existe es que viene de la primera pasada de una búsqueda global, pasamos if item.category: #Si este campo no existe es que viene de la primera pasada de una búsqueda global, pasamos
tmdb.set_infoLabels(item_local, True) tmdb.set_infoLabels(item_local, True)
itemlist.append(item_local.clone()) #Pintar pantalla itemlist.append(item_local.clone()) #Pintar pantalla
#if not item.category: #Si este campo no existe es que viene de la primera pasada de una búsqueda global #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 # return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorra tiempo
@@ -227,12 +227,12 @@ def listado(item):
# Extrae el paginador # Extrae el paginador
patron = '<div class="paginacion">.*?<span class="pagina pag_actual".*?' patron = '<div class="paginacion">.*?<span class="pagina pag_actual".*?'
patron += "<a href='([^']+)'.*?" #url siguiente página patron += "<a href='([^']+)'.*?" #url siguiente página
patron += 'class="pagina">(\d+)<' #próxima página patron += 'class="pagina">(\d+)<' #próxima página
matches = scrapertools.find_single_match(data, patron) matches = scrapertools.find_single_match(data, patron)
patron = 'class="pagina pag_sig">Siguiente.*?' patron = 'class="pagina pag_sig">Siguiente.*?'
patron += "<a href='.*?\/page\/(\d+)\/" #total de páginas patron += "<a href='.*?\/page\/(\d+)\/" #total de páginas
last_page = scrapertools.find_single_match(data, patron) last_page = scrapertools.find_single_match(data, patron)
if not last_page: if not last_page:
patron = '<div class="paginacion">.*?' patron = '<div class="paginacion">.*?'
@@ -265,7 +265,7 @@ def findvideos(item):
if not data: if not data:
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data) logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
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')) 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#data = unicode(data, "utf-8", errors="replace") #data = unicode(data, "utf-8", errors="replace")
#Añadimos el tamaño para todos #Añadimos el tamaño para todos
@@ -278,7 +278,7 @@ def findvideos(item):
patron_t = '<div class="enlace_descarga".*?<a href="(.*?\.torrent)"' patron_t = '<div class="enlace_descarga".*?<a href="(.*?\.torrent)"'
link_torrent = scrapertools.find_single_match(data, patron_t) link_torrent = scrapertools.find_single_match(data, patron_t)
link_torrent = urlparse.urljoin(item.url, link_torrent) link_torrent = urlparse.urljoin(item.url, link_torrent)
link_torrent = link_torrent.replace(" ", "%20") #sustituimos espacios por %20, por si acaso link_torrent = link_torrent.replace(" ", "%20") #sustituimos espacios por %20, por si acaso
#logger.info("link Torrent: " + link_torrent) #logger.info("link Torrent: " + link_torrent)
patron_m = '<div class="enlace_descarga".*?<a href="(magnet:?.*?)"' patron_m = '<div class="enlace_descarga".*?<a href="(magnet:?.*?)"'
@@ -286,7 +286,7 @@ def findvideos(item):
link_magnet = urlparse.urljoin(item.url, link_magnet) link_magnet = urlparse.urljoin(item.url, link_magnet)
#logger.info("link Magnet: " + link_magnet) #logger.info("link Magnet: " + link_magnet)
if not link_torrent and not link_magnet: #error if not link_torrent and not link_magnet: #error
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error
@@ -294,7 +294,7 @@ def findvideos(item):
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron_t + " / " + patron_m + " / DATA: " + data) logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron_t + " / " + patron_m + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB #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) item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
@@ -315,14 +315,14 @@ def findvideos(item):
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 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
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Seridor Torrent item_local.server = "torrent" #Seridor Torrent
itemlist.append(item_local.clone()) #Pintar pantalla itemlist.append(item_local.clone()) #Pintar pantalla
#Ahora pintamos el link del Magnet, si lo hay #Ahora pintamos el link del Magnet, si lo hay
if link_magnet: # Hay Magnet ? if link_magnet: # Hay Magnet ?
if item_local.quality: if item_local.quality:
item_local.quality += " " item_local.quality += " "
item_local.quality = item_local.quality.replace("[Torrent]", "") + "[Magnet]" item_local.quality = item_local.quality.replace("[Torrent]", "") + "[Magnet]"
@@ -330,11 +330,11 @@ def findvideos(item):
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 Magnet 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 Magnet
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Seridor Torrent item_local.server = "torrent" #Seridor Torrent
itemlist.append(item_local.clone()) #Pintar pantalla itemlist.append(item_local.clone()) #Pintar pantalla
#logger.debug("TORRENT: " + link_torrent + "MAGNET: " + link_magnet + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName) #logger.debug("TORRENT: " + link_torrent + "MAGNET: " + link_magnet + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
#logger.debug(item_local) #logger.debug(item_local)
@@ -380,7 +380,7 @@ def newest(categoria):
item.category_new= 'newest' item.category_new= 'newest'
itemlist = listado(item) itemlist = listado(item)
if itemlist[-1].title == "Página siguiente >>": if "Página siguiente >>" in itemlist[-1].title:
itemlist.pop() itemlist.pop()
# Se captura la excepción, para no interrumpir al canal novedades si un canal falla # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
+3 -2
View File
@@ -3,7 +3,7 @@
"name": "EstrenosGo", "name": "EstrenosGo",
"active": true, "active": true,
"adult": false, "adult": false,
"language": ["cast", "LAT", "VOSE", "VOS"], "language": ["cast", "lat"],
"fanart": "estrenosgo.png", "fanart": "estrenosgo.png",
"thumbnail": "estrenosgo.png", "thumbnail": "estrenosgo.png",
"banner": "estrenosgo.png", "banner": "estrenosgo.png",
@@ -11,7 +11,8 @@
"movie", "movie",
"tvshow", "tvshow",
"torrent", "torrent",
"direct" "direct",
"vos"
], ],
"settings": [ "settings": [
{ {
+94 -84
View File
@@ -113,7 +113,7 @@ def categorias(item):
if not data: #Si no ha logrado encontrar nada, salimos if not data: #Si no ha logrado encontrar nada, salimos
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')) 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8") data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
@@ -121,7 +121,7 @@ def categorias(item):
if not matches: if not matches:
logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug(matches) #logger.debug(matches)
@@ -182,7 +182,7 @@ def listado(item):
cnt_tot = 40 # Poner el num. máximo de items por página cnt_tot = 40 # Poner el num. máximo de items por página
cnt_title = 0 # Contador de líneas insertadas en Itemlist cnt_title = 0 # Contador de líneas insertadas en Itemlist
inicio = time.time() # Controlaremos que el proceso no exceda de un tiempo razonable inicio = time.time() # Controlaremos que el proceso no exceda de un tiempo razonable
fin = inicio + 10 # Después de este tiempo pintamos (segundos) fin = inicio + 10 # Después de este tiempo pintamos (segundos)
timeout_search = timeout # Timeout para descargas timeout_search = timeout # Timeout para descargas
if item.extra == 'search': if item.extra == 'search':
@@ -191,9 +191,9 @@ def listado(item):
timeout_search = 5 # Timeout un poco más largo para las búsquedas timeout_search = 5 # Timeout un poco más largo para las búsquedas
#Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios #Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios
title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas
if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada
title_lista.extend(item.title_lista) # Se usa la lista de páginas anteriores en Item title_lista.extend(item.title_lista) # Se usa la lista de páginas anteriores en Item
del item.title_lista # ... limpiamos del item.title_lista # ... limpiamos
if not item.extra2: # Si viene de Catálogo o de Alfabeto if not item.extra2: # Si viene de Catálogo o de Alfabeto
@@ -215,7 +215,12 @@ def listado(item):
if not data: #Si la web está caída salimos sin dar error if not data: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + url + " / DATA: " + data) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + url + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Patrón para todo menos para Series completas #Patrón para todo menos para Series completas
patron = '<div class="MiniFicha"><a href="([^"]+)" title="([^"]+)">' patron = '<div class="MiniFicha"><a href="([^"]+)" title="([^"]+)">'
@@ -237,7 +242,12 @@ def listado(item):
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
@@ -253,9 +263,9 @@ def listado(item):
except: except:
last_page = 1 #Si no lo encuentra, lo ponemos a 1 last_page = 1 #Si no lo encuentra, lo ponemos a 1
if item.extra == 'series': #Si son series completas, vamos a un listado especializado if item.extra == 'series': #Si son series completas, vamos a un listado especializado
item.matches = matches #salvamos todas las matches, no hay paginación item.matches = matches #salvamos todas las matches, no hay paginación
return listado_series(item) #llamamos a un método especializado return listado_series(item) #llamamos a un método especializado
#Empezamos el procesado de matches #Empezamos el procesado de matches
for scrapedurl, scrapedenlace, scrapedthumbnail, scrapedtitle, cat_ppal, cat_sec, opciones in matches: for scrapedurl, scrapedenlace, scrapedthumbnail, scrapedtitle, cat_ppal, cat_sec, opciones in matches:
@@ -280,25 +290,25 @@ def listado(item):
except: except:
pass pass
if not data_serie: #Si la web está caída salimos sin dar error. Pintamos el episodio if not data_serie: #Si la web está caída salimos sin dar error. Pintamos el episodio
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + scrapedurl + " / SERIE: " + cat_sec) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + scrapedurl + " / SERIE: " + cat_sec)
else: else:
patron_serie = '<div id="where_i_am">.*?<a href="[^"]+">.*?<\/a>.*?<a href="([^"]+)">' patron_serie = '<div id="where_i_am">.*?<a href="[^"]+">.*?<\/a>.*?<a href="([^"]+)">'
url = scrapertools.find_single_match(data_serie, patron_serie) #buscamos la url de la serie completa url = scrapertools.find_single_match(data_serie, patron_serie) #buscamos la url de la serie completa
if url: if url:
url = host + url url = host + url
extra = 'series' #es una serie completa extra = 'series' #es una serie completa
title_lista += [cat_sec] #la añadimos a la lista de series completas procesadas title_lista += [cat_sec] #la añadimos a la lista de series completas procesadas
title = cat_sec #salvamos el título de la serie completa title = cat_sec #salvamos el título de la serie completa
else: else:
url = scrapedurl #No se encuentra la Serie, se trata como Episodio suelto url = scrapedurl #No se encuentra la Serie, se trata como Episodio suelto
elif "Archivo Torrent" not in scrapedenlace and "Video Online" not in scrapedenlace: #Si no tiene enlaces pasamos elif "Archivo Torrent" not in scrapedenlace and "Video Online" not in scrapedenlace: #Si no tiene enlaces pasamos
continue continue
cnt_title += 1 cnt_title += 1
item_local = item.clone() #Creamos copia de Item para trabajar item_local = item.clone() #Creamos copia de Item para trabajar
if item_local.tipo: #... y limpiamos if item_local.tipo: #... y limpiamos
del item_local.tipo del item_local.tipo
if item_local.totalItems: if item_local.totalItems:
del item_local.totalItems del item_local.totalItems
@@ -317,18 +327,18 @@ def listado(item):
item_local.text_color = True item_local.text_color = True
del item_local.text_color del item_local.text_color
title_subs = [] #creamos una lista para guardar info importante title_subs = [] #creamos una lista para guardar info importante
item_local.language = [] #creamos lista para los idiomas item_local.language = [] #creamos lista para los idiomas
item_local.quality = '' #iniciamos calidad item_local.quality = '' #iniciamos calidad
quality_alt = '' quality_alt = ''
if 'series' not in cat_ppal: #si no son series, contiene la calidad if 'series' not in cat_ppal: #si no son series, contiene la calidad
quality_alt = cat_sec.lower().strip() quality_alt = cat_sec.lower().strip()
item_local.extra = extra #guardamos el extra procesado item_local.extra = extra #guardamos el extra procesado
item_local.url = url #guardamos la url final item_local.url = url #guardamos la url final
item_local.thumbnail = host[:-1] + scrapedthumbnail #guardamos el thumb item_local.thumbnail = host[:-1] + scrapedthumbnail #guardamos el thumb
item_local.context = "['buscar_trailer']" item_local.context = "['buscar_trailer']"
item_local.contentType = "movie" #por defecto, son películas item_local.contentType = "movie" #por defecto, son películas
item_local.action = "findvideos" item_local.action = "findvideos"
#Analizamos los formatos de la películas #Analizamos los formatos de la películas
@@ -347,7 +357,7 @@ def listado(item):
elif item_local.extra == 'series': elif item_local.extra == 'series':
item_local.contentType = "tvshow" item_local.contentType = "tvshow"
item_local.action = "episodios" 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
elif 'series' in cat_ppal or item_local.extra == 'episodios': elif 'series' in cat_ppal or item_local.extra == 'episodios':
item_local.contentType = "episode" item_local.contentType = "episode"
item_local.extra = "episodios" item_local.extra = "episodios"
@@ -361,7 +371,7 @@ def listado(item):
item_local.contentType = "season" item_local.contentType = "season"
item_local.extra = "season" item_local.extra = "season"
if item_local.contentType == "movie": #para las peliculas ponemos el mismo extra if item_local.contentType == "movie": #para las peliculas ponemos el mismo extra
item_local.extra = "peliculas" item_local.extra = "peliculas"
#Detectamos idiomas #Detectamos idiomas
@@ -495,13 +505,13 @@ def listado_series(item):
#logger.debug(item) #logger.debug(item)
#Control de paginación #Control de paginación
matches = item.matches #Restauramos la matches de la primera pasada matches = item.matches #Restauramos la matches de la primera pasada
del item.matches del item.matches
matches_tot = len(matches) #La web no pagina las Series, lo tenemos que controlar matches_tot = len(matches) #La web no pagina las Series, lo tenemos que controlar
if item.matches_current: #Llevamos los contadores de cuánto hemos pintado y cuánto queda if item.matches_current: #Llevamos los contadores de cuánto hemos pintado y cuánto queda
matches_current = item.matches_current matches_current = item.matches_current
if matches_tot >= matches_current + pag: if matches_tot >= matches_current + pag:
item.matches_current = matches_current + pag #Establecemos el bloque a pintar en este pasada item.matches_current = matches_current + pag #Establecemos el bloque a pintar en este pasada
else: else:
item.matches_current = matches_tot item.matches_current = matches_tot
@@ -566,8 +576,8 @@ def listado_series(item):
#logger.debug(item_local) #logger.debug(item_local)
#if not item.category: #Si este campo no existe es que viene de la primera pasada de una búsqueda global #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 # return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorra tiempo
#Pasamos a TMDB la lista completa Itemlist #Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__) tmdb.set_infoLabels(itemlist, __modo_grafico__)
@@ -607,7 +617,7 @@ def findvideos(item):
if not data_torrent and not data_directo: if not data_torrent and not data_directo:
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url) 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')) 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 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"><a href="([^"]+).*?'
patron += '(?:<div class="content_medium">(.*?)<\/div>.*?)?' patron += '(?:<div class="content_medium">(.*?)<\/div>.*?)?'
@@ -621,7 +631,7 @@ def findvideos(item):
logger.error(data_torrent) logger.error(data_torrent)
if data_directo: if data_directo:
logger.error(data_directo) logger.error(data_directo)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches_torrent) #logger.debug(matches_torrent)
@@ -652,17 +662,17 @@ def findvideos(item):
item_local.contentType = 'tvshow' item_local.contentType = 'tvshow'
item_local.extra = 'series' item_local.extra = 'series'
item_local.action = 'episodios' 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 #Buscamos la url de la serie y verificamos que existe
patron_serie = '<div class="linkMoreMovies"><div class="linkMore"><a href="([^"]+)">' patron_serie = '<div class="linkMoreMovies"><div class="linkMore"><a href="([^"]+)">'
item_local.url = scrapertools.find_single_match(data_torrent, patron_serie) #buscamos la url de la serie completa item_local.url = scrapertools.find_single_match(data_torrent, patron_serie) #buscamos la url de la serie completa
if not item_local.url: if not item_local.url:
item_local.url = scrapertools.find_single_match(data_directo, patron_serie) #buscamos la url de la serie completa item_local.url = scrapertools.find_single_match(data_directo, patron_serie) #buscamos la url de la serie completa
if item_local.url: if item_local.url:
item_local.url = item_local.url.replace('descargar-torrent', 'descarga').replace('-0-0-0-0-fx-', '-0-0-fx-') item_local.url = item_local.url.replace('descargar-torrent', 'descarga').replace('-0-0-0-0-fx-', '-0-0-fx-')
try: try:
tmdb.set_infoLabels(item_local, True) #TMDB de la serie completa tmdb.set_infoLabels(item_local, True) #TMDB de la serie completa
except: except:
pass pass
@@ -685,7 +695,7 @@ def findvideos(item):
if not item_local.quality: if not item_local.quality:
item_local.quality = item.quality item_local.quality = item.quality
elif scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])'): #Salvamos la duración elif scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])'): #Salvamos la duración
item_local.quality += ' [/COLOR][COLOR white]%s' % scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])') #Copiamos duración item_local.quality += ' [/COLOR][COLOR white]%s' % scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])') #Copiamos duración
if scrapedlang in IDIOMAS: #Salvamos el idioma, si lo hay if scrapedlang in IDIOMAS: #Salvamos el idioma, si lo hay
item_local.language = ["%s" % IDIOMAS[scrapedlang]] item_local.language = ["%s" % IDIOMAS[scrapedlang]]
@@ -701,7 +711,7 @@ def findvideos(item):
if not data or not 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) 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(patron)
#logger.debug(matches) #logger.debug(matches)
@@ -749,11 +759,11 @@ def findvideos(item):
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Seridor Torrent item_local.server = "torrent" #Seridor Torrent
itemlist_alt.append(item_local.clone(quality=quality)) #Pintar pantalla itemlist_alt.append(item_local.clone(quality=quality)) #Pintar pantalla
#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("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) #logger.debug(item_local)
@@ -761,17 +771,17 @@ def findvideos(item):
#Si son múltiples episodios, ordenamos #Si son múltiples episodios, ordenamos
if len(itemlist_alt) > 1 and (item.contentType == 'episode' or item.contentType == 'season'): 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 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) itemlist.extend(itemlist_alt)
#Ahora tratamos los servidores directo #Ahora tratamos los servidores directo
itemlist_alt = [] itemlist_alt = []
if matches_directo: if matches_directo:
for scrapedurl, scrapedquality, scrapedlang in matches_directo: #leemos los torrents con la diferentes calidades for scrapedurl, scrapedquality, scrapedlang in matches_directo: #leemos los torrents con la diferentes calidades
#Generamos una copia de Item para trabajar sobre ella #Generamos una copia de Item para trabajar sobre ella
item_local = item.clone() item_local = item.clone()
item_local.url = scrapedurl #Guardamos la url intermedia item_local.url = scrapedurl #Guardamos la url intermedia
item_local.quality = '' item_local.quality = ''
if scrapedquality: if scrapedquality:
@@ -779,11 +789,11 @@ def findvideos(item):
if not item_local.quality: if not item_local.quality:
item_local.quality = item.quality item_local.quality = item.quality
elif scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])'): #Salvamos la duración elif scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])'): #Salvamos la duración
item_local.quality += ' [/COLOR][COLOR white]%s' % scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])') #Copiamos duración item_local.quality += ' [/COLOR][COLOR white]%s' % scrapertools.find_single_match(item.quality, '(\[\d+:\d+ h\])') #Copiamos duración
if scrapedlang in IDIOMAS: if scrapedlang in IDIOMAS:
item_local.language = ["%s" % IDIOMAS[scrapedlang]] #Salvamos el idioma, si lo hay item_local.language = ["%s" % IDIOMAS[scrapedlang]] #Salvamos el idioma, si lo hay
#Leemos la página con el enlace al Servidor #Leemos la página con el enlace al Servidor
try: try:
@@ -797,7 +807,7 @@ def findvideos(item):
if not data or not 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) logger.error("ERROR 02: FINDVIDEOS: El enlace no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El enlace no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El enlace no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log'))
break #si no hay más datos, algo no funciona, pasamos a Ver Online continue #si no hay más datos, algo no funciona, salimos
#logger.debug(patron) #logger.debug(patron)
#logger.debug(matches) #logger.debug(matches)
@@ -862,14 +872,14 @@ def findvideos(item):
#Verificamos el si el enlace del servidor está activo #Verificamos el si el enlace del servidor está activo
mostrar_server = True mostrar_server = True
if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran
mostrar_server = servertools.is_server_enabled(servidor) mostrar_server = servertools.is_server_enabled(servidor)
try: #Obtenemos el enlace try: #Obtenemos el enlace
if mostrar_server: if mostrar_server:
devuelve = servertools.findvideosbyserver(scrapedenlace, servidor) #existe el link ? devuelve = servertools.findvideosbyserver(scrapedenlace, servidor) #existe el link ?
if devuelve: if devuelve:
enlace = devuelve[0][1] #Se guarda el link enlace = devuelve[0][1] #Se guarda el link
if not enlace: if not enlace:
continue continue
@@ -877,21 +887,21 @@ def findvideos(item):
#Si el link no está activo se ignora #Si el link no está activo se ignora
if "??" in item_local.alive: #dudoso if "??" in item_local.alive: #dudoso
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), quality, str(item_local.language)) item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), quality, str(item_local.language))
elif "no" in item_local.alive.lower(): #No está activo. Lo preparo, pero no lo pinto elif "no" in item_local.alive.lower(): #No está activo. Lo preparo, pero no lo pinto
item_local.title = '[COLOR red][%s][/COLOR] [COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.alive, servidor.capitalize(), quality, str(item_local.language)) 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) logger.debug(item_local.alive + ": ALIVE / " + servidor + " / " + enlace)
raise raise
else: #Sí está activo else: #Sí está activo
item_local.title = '[COLOR yellow][%s][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (servidor.capitalize(), quality, str(item_local.language)) 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 #Ahora pintamos el link Directo
item_local.url = enlace item_local.url = enlace
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = servidor #Seridor Directo item_local.server = servidor #Seridor Directo
itemlist_alt.append(item_local.clone(quality=quality)) #Pintar pantalla itemlist_alt.append(item_local.clone(quality=quality)) #Pintar pantalla
except: except:
logger.error('ERROR al procesar enlaces DIRECTOS: ' + servidor + ' / ' + scrapedenlace) logger.error('ERROR al procesar enlaces DIRECTOS: ' + servidor + ' / ' + scrapedenlace)
@@ -901,7 +911,7 @@ def findvideos(item):
#Si son múltiples episodios, ordenamos #Si son múltiples episodios, ordenamos
if len(itemlist_alt) > 1 and (item.contentType == 'episode' or item.contentType == 'season'): 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 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) itemlist.extend(itemlist_alt)
return itemlist return itemlist
@@ -913,14 +923,14 @@ def episodios(item):
#logger.debug(item) #logger.debug(item)
curr_page = 1 # Página inicial curr_page = 1 # Página inicial
last_page = 99999 # Última página inicial last_page = 99999 # Última página inicial
if item.curr_page: if item.curr_page:
curr_page = int(item.curr_page) # Si viene de una pasada anterior, lo usamos curr_page = int(item.curr_page) # Si viene de una pasada anterior, lo usamos
del item.curr_page # ... y lo borramos del item.curr_page # ... y lo borramos
if item.last_page: if item.last_page:
last_page = int(item.last_page) # Si viene de una pasada anterior, lo usamos last_page = int(item.last_page) # Si viene de una pasada anterior, lo usamos
del item.last_page # ... y lo borramos del item.last_page # ... y lo borramos
url_item = item.url.replace('1-.fx', '%s-.fx').replace('-1.fx', '-%s.fx') url_item = item.url.replace('1-.fx', '%s-.fx').replace('-1.fx', '-%s.fx')
if item.from_title: if item.from_title:
item.title = item.from_title item.title = item.from_title
@@ -928,8 +938,8 @@ def episodios(item):
#Limpiamos num. Temporada y Episodio que ha podido quedar por Novedades #Limpiamos num. Temporada y Episodio que ha podido quedar por Novedades
season_display = 0 season_display = 0
if item.contentSeason: if item.contentSeason:
if item.season_colapse: #Si viene del menú de Temporadas... if item.season_colapse: #Si viene del menú de Temporadas...
season_display = item.contentSeason #... salvamos el num de sesión a pintar season_display = item.contentSeason #... salvamos el num de sesión a pintar
item.from_num_season_colapse = season_display item.from_num_season_colapse = season_display
del item.season_colapse del item.season_colapse
item.contentType = "tvshow" item.contentType = "tvshow"
@@ -949,14 +959,14 @@ def episodios(item):
tmdb.set_infoLabels(item, True) tmdb.set_infoLabels(item, True)
modo_ultima_temp_alt = modo_ultima_temp 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 modo_ultima_temp_alt = False
max_temp = 1 max_temp = 1
if item.infoLabels['number_of_seasons']: if item.infoLabels['number_of_seasons']:
max_temp = item.infoLabels['number_of_seasons'] max_temp = item.infoLabels['number_of_seasons']
y = [] y = []
if modo_ultima_temp_alt and item.library_playcounts: #Averiguar cuantas temporadas hay en Videoteca if modo_ultima_temp_alt and item.library_playcounts: #Averiguar cuantas temporadas hay en Videoteca
patron = 'season (\d+)' patron = 'season (\d+)'
matches = re.compile(patron, re.DOTALL).findall(str(item.library_playcounts)) matches = re.compile(patron, re.DOTALL).findall(str(item.library_playcounts))
for x in matches: for x in matches:
@@ -967,19 +977,19 @@ def episodios(item):
# Descarga la página # Descarga la página
data = '' data = ''
url = url_item % curr_page #Inserto en num de página en la url url = url_item % curr_page #Inserto en num de página en la url
try: try:
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)|&nbsp;", "", httptools.downloadpage(url, timeout=timeout).data) data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)|&nbsp;", "", httptools.downloadpage(url, timeout=timeout).data)
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8") data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
except: #Algún error de proceso, salimos except: #Algún error de proceso, salimos
pass pass
if not data: if not data:
logger.error("ERROR 01: EPISODIOS: La Web no responde o la URL es erronea" + item.url) logger.error("ERROR 01: EPISODIOS: La Web no responde o la URL es erronea" + item.url)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist break #Pintamos lo que tenemos
curr_page += 1 #Apunto ya a la página siguiente curr_page += 1 #Apunto ya a la página siguiente
#Usamos el mismo patrón que en listado #Usamos el mismo patrón que en listado
patron = '<div class="MiniFicha"><a href="([^"]+)" title="([^"]+)">' patron = '<div class="MiniFicha"><a href="([^"]+)" title="([^"]+)">'
@@ -996,7 +1006,7 @@ def episodios(item):
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
@@ -1080,10 +1090,10 @@ def episodios(item):
else: else:
item_local.title = '%sx%s -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2)) item_local.title = '%sx%s -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca
if item_local.contentSeason < max_temp: if item_local.contentSeason < max_temp:
curr_page = 999999 #Sale del bucle de leer páginas curr_page = 999999 #Sale del bucle de leer páginas
break #Sale del bucle actual del WHILE de episodios por página break #Sale del bucle actual del WHILE de episodios por página
if season_display > 0: if season_display > 0:
if item_local.contentSeason > season_display: if item_local.contentSeason > season_display:
@@ -1098,10 +1108,10 @@ def episodios(item):
if len(itemlist) > 1: if len(itemlist) > 1:
itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos
if item.season_colapse and not item.add_videolibrary: #Si viene de listado, mostramos solo Temporadas if item.season_colapse and not item.add_videolibrary: #Si viene de listado, mostramos solo Temporadas
item, itemlist = generictools.post_tmdb_seasons(item, itemlist) item, itemlist = generictools.post_tmdb_seasons(item, itemlist)
if not item.season_colapse: #Si no es pantalla de Temporadas, pintamos todo if not item.season_colapse: #Si no es pantalla de Temporadas, pintamos todo
# Pasada por TMDB y clasificación de lista por temporada y episodio # Pasada por TMDB y clasificación de lista por temporada y episodio
tmdb.set_infoLabels(itemlist, True) tmdb.set_infoLabels(itemlist, True)
+3 -2
View File
@@ -3,14 +3,15 @@
"name": "GranTorrent", "name": "GranTorrent",
"active": true, "active": true,
"adult": false, "adult": false,
"language": ["*"], "language": ["cast", "lat"],
"thumbnail": "grantorrent.jpg", "thumbnail": "grantorrent.jpg",
"banner": "grantorrent.png", "banner": "grantorrent.png",
"fanart": "grantorrent.png", "fanart": "grantorrent.png",
"categories": [ "categories": [
"torrent", "torrent",
"movie", "movie",
"tvshow" "tvshow",
"vos"
], ],
"settings": [ "settings": [
{ {
+96 -82
View File
@@ -72,39 +72,39 @@ def submenu(item):
if not data: if not data:
logger.error("ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL: " + item.url) logger.error("ERROR 01: SUBMENU: La Web no responde o ha cambiado de URL: " + item.url)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log'))
return itemlist #Algo no funciona, pintamos lo que tenemos return itemlist #Algo no funciona, pintamos lo que tenemos
if item.extra == "peliculas": if item.extra == "peliculas":
patron = '<li class="navigation-top">.*?<a href="(.*?)".*?class="nav"> (.*?)\s?<\/a><\/li>' patron = '<li class="navigation-top">.*?<a href="(.*?)".*?class="nav"> (.*?)\s?<\/a><\/li>'
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches: if not matches:
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
for clone_inter, autoridad in item.intervencion: for clone_inter, autoridad in item.intervencion:
thumb_intervenido = get_thumb(autoridad) thumb_intervenido = get_thumb(autoridad)
itemlist.append(item.clone(action='', title="[COLOR yellow]" + clone_inter.capitalize() + ': [/COLOR]' + intervenido_judicial + '. Reportar el problema en el foro', thumbnail=thumb_intervenido)) itemlist.append(item.clone(action='', title="[COLOR yellow]" + clone_inter.capitalize() + ': [/COLOR]' + intervenido_judicial + '. Reportar el problema en el foro', thumbnail=thumb_intervenido))
return itemlist #Salimos return itemlist #Salimos
itemlist.append(item.clone(action="listado", title="Novedades", url=host)) #Menú principal películas itemlist.append(item.clone(action="listado", title="Novedades", url=host)) #Menú principal películas
for scrapedurl, scrapedtitle in matches: for scrapedurl, scrapedtitle in matches:
scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').encode('utf8').strip() scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').encode('utf8').strip()
if not "películas" in scrapedtitle.lower(): #Evita la entrada de ayudas y demás if not "películas" in scrapedtitle.lower(): #Evita la entrada de ayudas y demás
continue continue
itemlist.append(item.clone(action="listado", title=scrapedtitle, url=scrapedurl)) #Menú películas itemlist.append(item.clone(action="listado", title=scrapedtitle, url=scrapedurl)) #Menú películas
else: #Tratamos Series else: #Tratamos Series
patron = '<li class="navigation-top-dcha">.*?<a href="(.*?)".*?class="series"> (.*?)\s?<\/a><\/li>' patron = '<li class="navigation-top-dcha">.*?<a href="(.*?)".*?class="series"> (.*?)\s?<\/a><\/li>'
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches: if not matches:
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
for clone_inter, autoridad in item.intervencion: for clone_inter, autoridad in item.intervencion:
thumb_intervenido = get_thumb(autoridad) thumb_intervenido = get_thumb(autoridad)
itemlist.append(item.clone(action='', title="[COLOR yellow]" + clone_inter.capitalize() + ': [/COLOR]' + intervenido_judicial + '. Reportar el problema en el foro', thumbnail=thumb_intervenido)) itemlist.append(item.clone(action='', title="[COLOR yellow]" + clone_inter.capitalize() + ': [/COLOR]' + intervenido_judicial + '. Reportar el problema en el foro', thumbnail=thumb_intervenido))
return itemlist #Salimos return itemlist #Salimos
for scrapedurl, scrapedtitle in matches: for scrapedurl, scrapedtitle in matches:
scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').encode('utf8').strip() scrapedtitle = re.sub('\r\n', '', scrapedtitle).decode('utf8').encode('utf8').strip()
@@ -117,22 +117,22 @@ def submenu(item):
def listado(item): def listado(item):
logger.info() logger.info()
itemlist = [] itemlist = []
cnt_tot = 40 # Poner el num. máximo de items por página cnt_tot = 40 # Poner el num. máximo de items por página
cnt_title = 0 # Contador de líneas insertadas en Itemlist cnt_title = 0 # Contador de líneas insertadas en Itemlist
result_mode = config.get_setting("result_mode", channel="search") # Búsquedas globales: listado completo o no result_mode = config.get_setting("result_mode", channel="search") # Búsquedas globales: listado completo o no
#Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios #Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios
title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas
if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada
title_lista = item.title_lista # Se usa la lista de páginas anteriores en Item title_lista = item.title_lista # Se usa la lista de páginas anteriores en Item
title_lista_alt = [] # Creamos otra lista para esta pasada title_lista_alt = [] # Creamos otra lista para esta pasada
for url in title_lista: for url in title_lista:
title_lista_alt += [url] #hacemos una copia no vinculada de title_lista title_lista_alt += [url] #hacemos una copia no vinculada de title_lista
matches = [] matches = []
cnt_next = 0 #num de página próxima cnt_next = 0 #num de página próxima
cnt_top = 10 #max. num de páginas web a leer antes de pintar cnt_top = 10 #max. num de páginas web a leer antes de pintar
total_pag = 1 total_pag = 1
post_num = 1 #num pagina actual post_num = 1 #num pagina actual
#Máximo num. de líneas permitidas por TMDB (40). Máx de 5 páginas por Itemlist para no degradar el rendimiento. #Máximo num. de líneas permitidas por TMDB (40). Máx de 5 páginas por Itemlist para no degradar el rendimiento.
#Si itemlist sigue vacío después de leer 5 páginas, se pueden llegar a leer hasta 10 páginas para encontrar algo #Si itemlist sigue vacío después de leer 5 páginas, se pueden llegar a leer hasta 10 páginas para encontrar algo
@@ -150,10 +150,15 @@ def listado(item):
pass pass
cnt_next += 1 cnt_next += 1
if not data: #Si la web está caída salimos sin dar error if not data: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + video_section) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + video_section)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Obtiene la dirección de la próxima página, si la hay #Obtiene la dirección de la próxima página, si la hay
try: try:
@@ -168,9 +173,9 @@ def listado(item):
except: except:
post = False post = False
cnt_next = 99 #No hay más páginas. Salir del bucle después de procesar ésta cnt_next = 99 #No hay más páginas. Salir del bucle después de procesar ésta
if post: #puntero a la siguiente página. Cada página de la web tiene 30 entradas if post: #puntero a la siguiente página. Cada página de la web tiene 30 entradas
if "page/" in item.post: if "page/" in item.post:
item.post = re.sub(r"page\/\d+\/", "page/%s/" % post, item.post) item.post = re.sub(r"page\/\d+\/", "page/%s/" % post, item.post)
else: else:
@@ -203,7 +208,12 @@ def listado(item):
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Ahora se hace una simulación para saber cuantas líneas podemos albergar en este Itemlist. #Ahora se hace una simulación para saber cuantas líneas podemos albergar en este Itemlist.
#Se controlará cuantas páginas web se tienen que leer para rellenar la lista, sin pasarse #Se controlará cuantas páginas web se tienen que leer para rellenar la lista, sin pasarse
@@ -258,20 +268,20 @@ def listado(item):
#El control de página ya se ha realizado más arriba #El control de página ya se ha realizado más arriba
scrapedurl_alt = scrapedurl scrapedurl_alt = scrapedurl
if modo_serie_temp == 1: #si está en modo Serie agrupamos todos los episodios en una línea if modo_serie_temp == 1: #si está en modo Serie agrupamos todos los episodios en una línea
scrapedurl_alt = re.sub(r'-temporada.*?-\d+.*', '/', scrapedurl_alt) scrapedurl_alt = re.sub(r'-temporada.*?-\d+.*', '/', scrapedurl_alt)
scrapedurl_alt = re.sub(r'-?\d+x\d+.*', '/', scrapedurl_alt) #quita los datos de Temporada/episodio scrapedurl_alt = re.sub(r'-?\d+x\d+.*', '/', scrapedurl_alt) #quita los datos de Temporada/episodio
else: #si es modo Temporada, se agrupan a una línea por Temporada else: #si es modo Temporada, se agrupan a una línea por Temporada
num_temp = scrapertools.find_single_match(scrapedurl_alt, '-?(\d+)x') #captura num de Temporada num_temp = scrapertools.find_single_match(scrapedurl_alt, '-?(\d+)x') #captura num de Temporada
scrapedurl_alt = re.sub(r'-?\d+x\d+.*', '-temporada-%s-completa' % num_temp, scrapedurl_alt) #epis. a Temporada scrapedurl_alt = re.sub(r'-?\d+x\d+.*', '-temporada-%s-completa' % num_temp, scrapedurl_alt) #epis. a Temporada
if scrapedurl_alt in title_lista: # si ya se ha tratado, pasamos al siguiente item if scrapedurl_alt in title_lista: # si ya se ha tratado, pasamos al siguiente item
continue # solo guardamos la url para series y docus continue # solo guardamos la url para series y docus
title_lista += [scrapedurl_alt] title_lista += [scrapedurl_alt]
cnt_title += 1 # Sería una línea real más para Itemlist cnt_title += 1 # Sería una línea real más para Itemlist
item_local = item.clone() #Creamos copia de Item para trabajar y limpiamos campos innecesarios item_local = item.clone() #Creamos copia de Item para trabajar y limpiamos campos innecesarios
if item_local.media: #Viene de Búsquedas if item_local.media: #Viene de Búsquedas
del item_local.media del item_local.media
if item_local.title_lista: if item_local.title_lista:
del item_local.title_lista del item_local.title_lista
@@ -339,8 +349,8 @@ def listado(item):
#Agrega el item local a la lista itemlist #Agrega el item local a la lista itemlist
itemlist.append(item_local.clone()) itemlist.append(item_local.clone())
#if not item.category and result_mode == 0: #Si este campo no existe, viene de la primera pasada de una búsqueda global #if not item.category and result_mode == 0: #Si este campo no existe, viene de la primera pasada de una búsqueda global
# return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorrar tiempo # return itemlist #Retornamos sin pasar por la fase de maquillaje para ahorrar tiempo
#Pasamos a TMDB la lista completa Itemlist #Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__) tmdb.set_infoLabels(itemlist, __modo_grafico__)
@@ -372,6 +382,8 @@ def findvideos(item):
logger.info() logger.info()
itemlist = [] itemlist = []
#logger.debug(item)
#Bajamos los datos de la página #Bajamos los datos de la página
data = '' data = ''
try: try:
@@ -382,13 +394,13 @@ def findvideos(item):
if not data: if not data:
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data) logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
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')) 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
data = unicode(data, "utf-8", errors="replace").encode("utf-8") data = unicode(data, "utf-8", errors="replace").encode("utf-8")
data = scrapertools.find_single_match(data, 'div id="Tokyo" [^>]+>(.*?)</div>') #Seleccionamos la zona de links data = scrapertools.find_single_match(data, 'div id="Tokyo" [^>]+>(.*?)</div>') #Seleccionamos la zona de links
patron = '\/icono_.*?png" title="(?P<lang>.*?)?" [^>]+><\/td><td>(?P<quality>.*?)?<?\/td>.*?<td>(?P<size>.*?)?<\/td><td><a class="link" href="(?P<url>.*?)?"' patron = '\/icono_.*?png" title="(?P<lang>.*?)?" [^>]+><\/td><td>(?P<quality>.*?)?<?\/td>.*?<td>(?P<size>.*?)?<\/td><td><a class="link" href="(?P<url>.*?)?"'
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches: #error if not matches: #error
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error
@@ -396,7 +408,7 @@ def findvideos(item):
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
@@ -454,19 +466,21 @@ def findvideos(item):
#Tratamos la calidad y tamaño de cada link #Tratamos la calidad y tamaño de cada link
if quality: if quality:
tiempo = '' item_local.quality = quality
if item_local.quality: else:
tiempo = scrapertools.find_single_match(item_local.quality, r'(\s\[.*?\])') item_local.quality = item.quality
item_local.quality = quality + tiempo
if "temporada" in temp_epi.lower(): if "temporada" in temp_epi.lower():
item_local.quality = '%s [Temporada]' % item_local.quality item_local.quality = '%s [Temporada]' % item_local.quality
#Añadimos la duración, que estará en item.quility #Añadimos la duración, que estará en item.quility
if scrapertools.find_single_match(item.quality, '(\[\d+:\d+)'): #si ya tiene la duración, la ponemos if scrapertools.find_single_match(item.quality, '(\[\d+:\d+)') and not scrapertools.find_single_match(item_local.quality, '(\[\d+:\d+)'):
item_local.quality = '%s [%s h]' % (item_local.quality, scrapertools.find_single_match(item.quality, '(\d+:\d+)')) item_local.quality = '%s [/COLOR][COLOR white][%s h]' % (item_local.quality, scrapertools.find_single_match(item.quality, '(\d+:\d+)'))
#if size and item_local.contentType != "episode": #if size and item_local.contentType != "episode":
if size: if size:
size = size.replace(".", ",").replace("B,", " B").replace("b,", " b") size = size.replace(".", ",").replace("B,", " B").replace("b,", " b")
item_local.quality = '%s [%s]' % (item_local.quality, size) if '[/COLOR][COLOR white]' in item_local.quality:
item_local.quality = '%s [%s]' % (item_local.quality, size)
else:
item_local.quality = '%s [/COLOR][COLOR white][%s]' % (item_local.quality, size)
if item_local.action == 'show_result': #Viene de una búsqueda global if item_local.action == 'show_result': #Viene de una búsqueda global
channel = item_local.channel.capitalize() channel = item_local.channel.capitalize()
if item_local.from_channel: if item_local.from_channel:
@@ -476,14 +490,14 @@ def findvideos(item):
#Salvamos la url del .torrent #Salvamos la url del .torrent
if scrapedurl: if scrapedurl:
item_local.url = scrapedurl item_local.url = scrapedurl
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 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
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Seridor Torrent item_local.server = "torrent" #Seridor Torrent
itemlist.append(item_local.clone()) #Pintar pantalla itemlist.append(item_local.clone()) #Pintar pantalla
#logger.debug("TORRENT: " + item_local.url + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality) #logger.debug("TORRENT: " + item_local.url + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality)
#logger.debug(item_local) #logger.debug(item_local)
@@ -549,12 +563,12 @@ def episodios(item):
elif max_temp >= item.infoLabels["number_of_seasons"]: #Si tenemos en .nfo igaual o más temporadas, investigar elif max_temp >= item.infoLabels["number_of_seasons"]: #Si tenemos en .nfo igaual o más temporadas, investigar
cnt_s = 0 cnt_s = 0
for s in item.library_playcounts: #Ver cuántas Temporadas hay en Videoteca for s in item.library_playcounts: #Ver cuántas Temporadas hay en Videoteca
if "season" in s: if "season" in s:
cnt_s += 1 cnt_s += 1
if cnt_s > 1: #hay más de 1 temporada en Videoteca, es Serie? if cnt_s > 1: #hay más de 1 temporada en Videoteca, es Serie?
if temp_actual_num > 1: #Temp. actual > 1, parece Temporada if temp_actual_num > 1: #Temp. actual > 1, parece Temporada
s = 1 s = 1
while s <= item.infoLabels["number_of_seasons"]: #Buscamos la primera Temporada de Videoteca while s <= item.infoLabels["number_of_seasons"]: #Buscamos la primera Temporada de Videoteca
if item.library_playcounts.has_key('season %d' % s): #Buscamos si la Temporada 1 existe if item.library_playcounts.has_key('season %d' % s): #Buscamos si la Temporada 1 existe
@@ -564,19 +578,19 @@ def episodios(item):
item.contentType = "tvshow" #No es Temporada 1, pero es más baja que la actual. Es Serie item.contentType = "tvshow" #No es Temporada 1, pero es más baja que la actual. Es Serie
break break
s += 1 s += 1
else: #Sí, es Serie else: #Sí, es Serie
item.contentType = "tvshow" item.contentType = "tvshow"
else: #Solo hay una temporada en la Videoteca else: #Solo hay una temporada en la Videoteca
if temp_actual_num > 1: #es Temporada la actual? if temp_actual_num > 1: #es Temporada la actual?
if item.contentSeason: if item.contentSeason:
item.contentType = "season" #Si está informado el num de Temp. se creó como Temporada item.contentType = "season" #Si está informado el num de Temp. se creó como Temporada
else: else:
item.contentType = "tvshow" #Si no, es Serie que no tiene Temp. 1 item.contentType = "tvshow" #Si no, es Serie que no tiene Temp. 1
else: #Si es Temp. 1, se procesa según el valor de configuración else: #Si es Temp. 1, se procesa según el valor de configuración
if modo_serie_temp == 0: #Es Temporada if modo_serie_temp == 0: #Es Temporada
item.contentType = "season" item.contentType = "season"
else: #Es Serie else: #Es Serie
item.contentType = "tvshow" item.contentType = "tvshow"
else: else:
item.contentType = "list" item.contentType = "list"
@@ -592,21 +606,21 @@ def episodios(item):
#Controla que no haya un bucle en la cadena de links entre temporadas #Controla que no haya un bucle en la cadena de links entre temporadas
if scrapertools.find_single_match(temp_actual, patron_actual_num) in temp_lista: if scrapertools.find_single_match(temp_actual, patron_actual_num) in temp_lista:
temp_bucle += 1 temp_bucle += 1
if temp_bucle > 5: #Si ha pasado por aquí más de 5 veces es que algo anda mal if temp_bucle > 5: #Si ha pasado por aquí más de 5 veces es que algo anda mal
logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data) logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log')) itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log'))
data = '' data = ''
return itemlist #Algo no funciona con los links, pintamos lo que tenemos break #Algo no funciona con los links, pintamos lo que tenemos
if temp_advance == "back": #Se salta una temporada hacia atrás if temp_advance == "back": #Se salta una temporada hacia atrás
logger.error("ERROR 05: EPISODIOS: Temporada duplicada. Link BACK erroneo: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / Bucle: " + str(temp_bucle) + " / DATA: " + data) logger.error("ERROR 05: EPISODIOS: Temporada duplicada. Link BACK erroneo: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / Bucle: " + str(temp_bucle) + " / DATA: " + data)
temp_actual = scrapertools.find_single_match(data, patron_previous) #url de temporada anterior temp_actual = scrapertools.find_single_match(data, patron_previous) #url de temporada anterior
data = '' data = ''
continue #volvemos a leer página con la url de la anterior continue #volvemos a leer página con la url de la anterior
if temp_advance == "forw": #Se salta una temporada hacia adelante if temp_advance == "forw": #Se salta una temporada hacia adelante
logger.error("ERROR 05: EPISODIOS: Temporada duplicada. Link FORW erroneo: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / Bucle: " + str(temp_bucle) + " / DATA: " + data) logger.error("ERROR 05: EPISODIOS: Temporada duplicada. Link FORW erroneo: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / Bucle: " + str(temp_bucle) + " / DATA: " + data)
temp_actual = scrapertools.find_single_match(data, patron_next) #url de temporada siguiente temp_actual = scrapertools.find_single_match(data, patron_next) #url de temporada siguiente
data = '' data = ''
continue #volvemos a leer página con la url de la siguiente continue #volvemos a leer página con la url de la siguiente
#Comprobamos si se ha saltado una Temporada #Comprobamos si se ha saltado una Temporada
if temp_advance == "back": #Avanza marcha atrás? if temp_advance == "back": #Avanza marcha atrás?
@@ -625,9 +639,9 @@ def episodios(item):
logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data) logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data)
data = '' data = ''
itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log')) itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log'))
return itemlist #Algo no funciona con los links, pintamos lo que tenemos break #Algo no funciona con los links, pintamos lo que tenemos
data = '' data = ''
continue #volvemos a leer página con la url de la siguiente continue #volvemos a leer página con la url de la siguiente
#Comprobamos si se ha saltado una Temporada #Comprobamos si se ha saltado una Temporada
if temp_advance == "forw": #Avanza marcha adelante? if temp_advance == "forw": #Avanza marcha adelante?
@@ -646,9 +660,9 @@ def episodios(item):
logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data) logger.error("ERROR 05: EPISODIOS: Los links entre temporadas están rotos y se está metiendo en un loop: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista temps: " + str(temp_lista) + " / DATA: " + data)
data = '' data = ''
itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log')) itemlist.append(item.clone(action='', title=item.channel + ': ERROR 05: EPISODIOS. Los links entre temporadas están rotos y se está metiendo en un loop. Reportar error con log'))
return itemlist #Algo no funciona con los links, pintamos lo que tenemos break #Algo no funciona con los links, pintamos lo que tenemos
data = '' data = ''
continue #volvemos a leer página con la url de la siguiente continue #volvemos a leer página con la url de la siguiente
temp_actual_num = scrapertools.find_single_match(temp_actual, patron_actual_num) #num de la temporada actual temp_actual_num = scrapertools.find_single_match(temp_actual, patron_actual_num) #num de la temporada actual
temp_actual_num = int(temp_actual_num) temp_actual_num = int(temp_actual_num)
@@ -660,7 +674,7 @@ def episodios(item):
except: #Error al leer o procesar la página actual? Salimos except: #Error al leer o procesar la página actual? Salimos
logger.error("ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / DATA: " + data) logger.error("ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea: " + temp_actual + " (" + str (temp_actual_num) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. 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 break #si no hay más datos, algo no funciona, pintamos lo que tenemos
if item.contentType == "season": if item.contentType == "season":
temp_advance = '' #Es la única temporada temp_advance = '' #Es la única temporada
@@ -700,7 +714,7 @@ def episodios(item):
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
@@ -752,7 +766,7 @@ def episodios(item):
item_local.contentSeason = temp_actual_num item_local.contentSeason = temp_actual_num
item_local.contentSeason = int(item_local.contentSeason) item_local.contentSeason = int(item_local.contentSeason)
item_local.contentEpisodeNumber = 1 item_local.contentEpisodeNumber = 1
else: #si es un episodio lo guardamos else: #si es un episodio lo guardamos
if scrapertools.find_single_match(temp_epi, r'(\d+)&#.*?;(\d+)'): if scrapertools.find_single_match(temp_epi, r'(\d+)&#.*?;(\d+)'):
item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(temp_epi, r'(\d+)&#.*?;(\d+)') item_local.contentSeason, item_local.contentEpisodeNumber = scrapertools.find_single_match(temp_epi, r'(\d+)&#.*?;(\d+)')
if not item_local.contentSeason: if not item_local.contentSeason:
@@ -766,32 +780,32 @@ def episodios(item):
item_local.contentEpisodeNumber = int(item_local.contentEpisodeNumber) item_local.contentEpisodeNumber = int(item_local.contentEpisodeNumber)
except: except:
logger.error("ERROR 07: EPISODIOS: Error en número de Temporada o Episodio: " + temp_epi) logger.error("ERROR 07: EPISODIOS: Error en número de Temporada o Episodio: " + temp_epi)
continue #si da un error pasamos del episodio continue #si da un error pasamos del episodio
if item_local.contentSeason != temp_actual_num: #A veces es diferente el num de Temp. de la URL y de if item_local.contentSeason != temp_actual_num: #A veces es diferente el num de Temp. de la URL y de
temp_actual_num = item_local.contentSeason #los episodios. Anatomia de Grey Temp. 14 temp_actual_num = item_local.contentSeason #los episodios. Anatomia de Grey Temp. 14
if "-" in temp_epi: #episodios múltiples if "-" in temp_epi: #episodios múltiples
episode2 = scrapertools.find_single_match(temp_epi, r'-(\d+)') episode2 = scrapertools.find_single_match(temp_epi, r'-(\d+)')
item_local.title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(episode2).zfill(2)) #Creamos un título con el rango de episodios item_local.title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(episode2).zfill(2)) #Creamos un título con el rango de episodios
elif "temporada" in temp_epi.lower() or "completa" in temp_epi.lower(): #Temporada completa elif "temporada" in temp_epi.lower() or "completa" in temp_epi.lower(): #Temporada completa
episode2 = 99 episode2 = 99
item_local.title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(episode2).zfill(2)) #Creamos un título con el rango ficticio de episodios item_local.title = "%sx%s al %s -" % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), str(episode2).zfill(2)) #Creamos un título con el rango ficticio de episodios
elif item_local.contentEpisodeNumber == 0: #episodio extraño elif item_local.contentEpisodeNumber == 0: #episodio extraño
item_local.title = '%sx%s - %s' % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), temp_epi) item_local.title = '%sx%s - %s' % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2), temp_epi)
else: #episodio normal else: #episodio normal
item_local.title = '%sx%s -' % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2)) item_local.title = '%sx%s -' % (item_local.contentSeason, str(item_local.contentEpisodeNumber).zfill(2))
if len(itemlist) > 0 and item_local.contentSeason == itemlist[-1].contentSeason and item_local.contentEpisodeNumber == itemlist[-1].contentEpisodeNumber and item_local.title == itemlist[-1].title and itemlist[-1].contentEpisodeNumber != 0: #solo guardamos un episodio ... if len(itemlist) > 0 and item_local.contentSeason == itemlist[-1].contentSeason and item_local.contentEpisodeNumber == itemlist[-1].contentEpisodeNumber and item_local.title == itemlist[-1].title and itemlist[-1].contentEpisodeNumber != 0: #solo guardamos un episodio ...
if itemlist[-1].quality: if itemlist[-1].quality:
itemlist[-1].quality += ", " + quality #... pero acumulamos las calidades itemlist[-1].quality += ", " + quality #... pero acumulamos las calidades
else: else:
itemlist[-1].quality = quality itemlist[-1].quality = quality
continue #ignoramos el episodio duplicado continue #ignoramos el episodio duplicado
else: else:
item_local.quality = quality item_local.quality = quality
itemlist.append(item_local.clone()) #guardamos el episodio itemlist.append(item_local.clone()) #guardamos el episodio
#logger.debug("EPISODIOS: " + temp_actual + " (" + str (item_local.contentSeason) + "x" + str (item_local.contentEpisodeNumber) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista Temps: " + str(temp_lista)) #logger.debug("EPISODIOS: " + temp_actual + " (" + str (item_local.contentSeason) + "x" + str (item_local.contentEpisodeNumber) + ") / Previa: " + temp_previous + " / o Siguiente: " + temp_next + " / Avance: " + temp_advance + " / Lista Temps: " + str(temp_lista))
#logger.debug(item_local) #logger.debug(item_local)
@@ -823,7 +837,7 @@ def episodios(item):
def actualizar_titulos(item): def actualizar_titulos(item):
logger.info() logger.info()
item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
#Volvemos a la siguiente acción en el canal #Volvemos a la siguiente acción en el canal
return item return item
@@ -835,7 +849,7 @@ def search(item, texto):
itemlist = [] itemlist = []
item.url = "%s?s=%s" % (item.url, texto) item.url = "%s?s=%s" % (item.url, texto)
item.media = "search" #Marcar para "Listado": igual comportamiento que "Categorías" item.media = "search" #Marcar para "Listado": igual comportamiento que "Categorías"
try: try:
if "series/" in item.url: if "series/" in item.url:
@@ -3,14 +3,15 @@
"name": "Mejor Torrent 1", "name": "Mejor Torrent 1",
"active": true, "active": true,
"adult": false, "adult": false,
"language": ["*"], "language": ["cast", "lat"],
"thumbnail": "mejortorrent.png", "thumbnail": "mejortorrent.png",
"banner": "mejortorrent.png", "banner": "mejortorrent.png",
"categories": [ "categories": [
"torrent", "torrent",
"movie", "movie",
"tvshow", "tvshow",
"documentary" "documentary",
"vos"
], ],
"settings": [ "settings": [
{ {
+141 -107
View File
@@ -117,13 +117,12 @@ def alfabeto(item):
def listado(item): def listado(item):
logger.info() logger.info()
itemlist = [] itemlist = []
url_next_page ='' # Control de paginación url_next_page ='' # Control de paginación
cnt_tot = 30 # Poner el num. máximo de items por página cnt_tot = 30 # Poner el num. máximo de items por página
if item.category:
del item.category
if item.totalItems: if item.totalItems:
del item.totalItems del item.totalItems
item.category = item.channel.capitalize()
try: try:
data = '' data = ''
@@ -134,27 +133,27 @@ def listado(item):
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
if not data: #Si la web está caída salimos sin dar error if not data: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data) logger.error("ERROR 01: LISTADO: La Web no responde o ha cambiado de URL: " + item.url + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO:. 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
# En este canal las url's y los títulos tienen diferente formato dependiendo del contenido # En este canal las url's y los títulos tienen diferente formato dependiendo del contenido
if (item.extra == "peliculas" or item.extra == "varios") and item.tipo: #Desde Lista Alfabética if (item.extra == "peliculas" or item.extra == "varios") and item.tipo: #Desde Lista Alfabética
patron = '<a href="([^"]+)">([^<]+)?<\/a>' patron = '<a href="([^"]+)">([^<]+)?<\/a>'
patron_enlace = '\/\/.*?\/(.*?)\/$' patron_enlace = '\/\/.*?\/(.*?)\/$'
patron_title = '<a href="[^"]+">([^<]+)<\/a>(\s*<b>([^>]+)<\/b>)?' patron_title = '<a href="[^"]+">([^<]+)<\/a>(\s*<b>([^>]+)<\/b>)?'
item.action = "findvideos" item.action = "findvideos"
item.contentType = "movie" item.contentType = "movie"
pag = False #No hay paginación pag = False #No hay paginación
elif (item.extra == "peliculas" or item.extra == "varios") and not item.tipo: #Desde Menú principal elif (item.extra == "peliculas" or item.extra == "varios") and not item.tipo: #Desde Menú principal
patron = '<a href="([^"]+)">?<img src="([^"]+)"[^<]+<\/a>' patron = '<a href="([^"]+)">?<img src="([^"]+)"[^<]+<\/a>'
patron_enlace = '\/\/.*?\/(.*?)\/$' patron_enlace = '\/\/.*?\/(.*?)\/$'
patron_title = '<a href="[^"]+">([^<]+)<\/a>(\s*<b>([^>]+)<\/b>)?' patron_title = '<a href="[^"]+">([^<]+)<\/a>(\s*<b>([^>]+)<\/b>)?'
item.action = "findvideos" item.action = "findvideos"
item.contentType = "movie" item.contentType = "movie"
pag = True #Sí hay paginación pag = True #Sí hay paginación
cnt_tot = 20 # Poner el num. máximo de items por página. Parece que hay 18 cnt_tot = 20 # Poner el num. máximo de items por página. Parece que hay 18
item.next_page = 'b' item.next_page = 'b'
elif item.extra == "series" and item.tipo: elif item.extra == "series" and item.tipo:
patron = '<a href="([^"]+)">([^<]+)?<\/a>' patron = '<a href="([^"]+)">([^<]+)?<\/a>'
@@ -165,7 +164,7 @@ def listado(item):
item.action = "episodios" item.action = "episodios"
item.contentType = "season" item.contentType = "season"
pag = False pag = False
cnt_tot = 10 # Se reduce el numero de items por página porque es un proceso pesado cnt_tot = 10 # Se reduce el numero de items por página porque es un proceso pesado
elif item.extra == "series" and not item.tipo: elif item.extra == "series" and not item.tipo:
patron = '<a href="([^"]+)">?<img src="([^"]+)"[^<]+<\/a>' patron = '<a href="([^"]+)">?<img src="([^"]+)"[^<]+<\/a>'
patron_enlace = '\/\/.*?\/(.*?)-[temporada]?\d+[-|x]' patron_enlace = '\/\/.*?\/(.*?)-[temporada]?\d+[-|x]'
@@ -175,7 +174,7 @@ def listado(item):
item.action = "episodios" item.action = "episodios"
item.contentType = "season" item.contentType = "season"
pag = True pag = True
cnt_tot = 10 # Se reduce el numero de items por página porque es un proceso pesado cnt_tot = 10 # Se reduce el numero de items por página porque es un proceso pesado
elif item.extra == "documentales" and item.tipo: elif item.extra == "documentales" and item.tipo:
patron = '<a href="([^"]+)">([^<]+)?<\/a>' patron = '<a href="([^"]+)">([^<]+)?<\/a>'
patron_enlace = '\/\/.*?\/(.*?)-[temporada]?\d+[-|x]' patron_enlace = '\/\/.*?\/(.*?)-[temporada]?\d+[-|x]'
@@ -219,13 +218,13 @@ def listado(item):
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Capturamos el num. de la última página para informala a pié de página. Opción para páginas sin paginación #Capturamos el num. de la última página para informala a pié de página. Opción para páginas sin paginación
if pag == False: if pag == False:
item.last_page = (len(matches) / cnt_tot) + 1 item.last_page = (len(matches) / cnt_tot) + 1
if not item.last_page and pag: #Capturamos el num. de la última página para informala a pié de página if not item.last_page and pag: #Capturamos el num. de la última página para informala a pié de página
item.last_page = -1 item.last_page = -1
#patron_next_page = "<a href='([^']+)' class='paginar'> Siguiente >> <\/a>" #patron_next_page = "<a href='([^']+)' class='paginar'> Siguiente >> <\/a>"
if "/documentales" in item.url: if "/documentales" in item.url:
@@ -309,7 +308,7 @@ def listado(item):
item_local.thumbnail = scrapedthumbnail item_local.thumbnail = scrapedthumbnail
if "http" not in item_local.thumbnail: if "http" not in item_local.thumbnail:
item_local.thumbnail = '' item_local.thumbnail = ''
item_local.infoLabels['year'] = '-' # Al no saber el año, le ponemos "-" y TmDB lo calcula automáticamente item_local.infoLabels['year'] = '-' # Al no saber el año, le ponemos "-" y TmDB lo calcula automáticamente
# Para que el menú contextual muestre conrrectamente las opciones de añadir a Videoteca # Para que el menú contextual muestre conrrectamente las opciones de añadir a Videoteca
if item_local.extra == "series": if item_local.extra == "series":
@@ -327,15 +326,18 @@ def listado(item):
data_epi = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url).data) data_epi = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item_local.url).data)
url = scrapertools.find_single_match(data_epi, '<tr><td>.*<a href="([^"]+)" style="text-decoration:none;"><h1 style=') url = scrapertools.find_single_match(data_epi, '<tr><td>.*<a href="([^"]+)" style="text-decoration:none;"><h1 style=')
if not url: if not url:
url = scrapertools.find_single_match(data_epi, '<td><a href="(secciones.php\?sec\=descargas&ap=[^"]+)"') ### url = scrapertools.find_single_match(data_epi, '<td><a href="(secciones.php\?sec\=descargas&ap=[^"]+)"')
if not url: #No encuentro la Temporada. Lo dejo como capítulo suelto #Probamos si es una temporada completa, aunque no tenga raiz
if not url and scrapertools.find_single_match(data_epi, "(<form (?:style='[^']+'\s)?name='episodios' action='[^']+' method='post'>.*?)<\/form>"):
url = item_local.url #Salvamos la url original
if not url: #No encuentro la Temporada. Lo dejo como capítulo suelto
item_local.action = "findvideos" item_local.action = "findvideos"
item_local.contentEpisodeNumber = episodio item_local.contentEpisodeNumber = episodio
if not item_local.contentEpisodeNumber: if not item_local.contentEpisodeNumber:
item_local.contentEpisodeNumber = 1 item_local.contentEpisodeNumber = 1
logger.debug(item_local) logger.debug(item_local)
logger.debug(data_epi) logger.debug(data_epi)
else: #Busco la temporada. Salvo url de episodio por si acaso else: #Busco la temporada. Salvo url de episodio por si acaso
#item_local.url_ori = item_local.url #item_local.url_ori = item_local.url
item_local.url = url item_local.url = url
item_local.contentType = "season" item_local.contentType = "season"
@@ -386,7 +388,7 @@ def listado(item):
# Limpiamos títulos, Sacamos datos de calidad, audio y lenguaje # Limpiamos títulos, Sacamos datos de calidad, audio y lenguaje
scrapedtitle = re.sub('\r\n', '', scrapedtitle_alt).decode('utf8').encode('utf8').strip() scrapedtitle = re.sub('\r\n', '', scrapedtitle_alt).decode('utf8').encode('utf8').strip()
title = scrapedtitle title = scrapedtitle
title = title.replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u").replace("ü", "u").replace("�", "ñ").replace("ñ", "ñ") title = title.replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u").replace("ü", "u").replace("�", "ñ").replace("ñ", "ñ").replace("&#215;", "x")
title_subs = [] title_subs = []
@@ -400,10 +402,7 @@ def listado(item):
title = title.replace(" Latino", "").replace(" latino", "").replace(" Argentina", "").replace(" argentina", "") title = title.replace(" Latino", "").replace(" latino", "").replace(" Argentina", "").replace(" argentina", "")
title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "") title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "")
if "3d" in title.lower(): #Reservamos info para después de TMDB if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
item_local.quality += " 3D"
title = title.replace(" [3d]", "").replace(" 3d", "").replace(" [3D]", "").replace(" 3D", "")
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')] title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) title = re.sub(r'\[[a|A]udio.*?\]', '', title)
if "[dual" in title.lower(): if "[dual" in title.lower():
@@ -427,7 +426,7 @@ def listado(item):
# scrapedinfo tiene la calidad, pero solo en llamadas desde peliculas sin alfabeto # scrapedinfo tiene la calidad, pero solo en llamadas desde peliculas sin alfabeto
if item_local.extra == "series" or item_local.extra == "documentales": if item_local.extra == "series" or item_local.extra == "documentales":
if item_local.quality: if item_local.quality:
title = re.sub(r'[\[|\(]\d+.*?[\)|\]]', '', title) # Quitar la calidad del título title = re.sub(r'[\[|\(]\d+.*?[\)|\]]', '', title) # Quitar la calidad del título
info = "" info = ""
if not item_local.contentSerieName: if not item_local.contentSerieName:
item_local.contentSerieName = title.strip() item_local.contentSerieName = title.strip()
@@ -435,12 +434,20 @@ def listado(item):
item_local.contentSerieName = "SIN TITULO" item_local.contentSerieName = "SIN TITULO"
if item_local.infoLabels['title']: if item_local.infoLabels['title']:
del item_local.infoLabels['title'] del item_local.infoLabels['title']
if item_local.contentType == "episode":
title = re.sub(r'\d+x\d+(?: al \d+)?', '', title)
if info != "" and not item_local.quality: if info != "" and not item_local.quality:
item_local.quality = info item_local.quality = info
if not scrapertools.find_single_match(title, '[\[|\(](.*?)[\)|\]]') in item_local.quality:
if item_local.quality:
item_local.quality += ' '
item_local.quality = scrapertools.find_single_match(title, '[\[|\(](.*?)[\)|\]]')
if scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]') and not scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]') in item_local.quality:
item_local.quality += ' %s' % scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]')
title = re.sub(r'[\[|\(].*?[\)|\]]\s?[\[|\(].*?[\)|\]]', '', title)
title = re.sub(r'[\[|\(].*?[\)|\]]', '', title)
if "(hdrip" in title.lower() or "(br" in title.lower() or "(vhsrip" in title.lower() or "(dvdrip" in title.lower() or "(fullb" in title.lower() or "(blu" in title.lower() or "(4k" in title.lower() or "(hevc" in title.lower() or "(imax" in title.lower() or "extendida" in title.lower() or "[720p]" in title.lower() or "[1080p]" in title.lower(): if "(hdrip" in title.lower() or "(br" in title.lower() or "(vhsrip" in title.lower() or "(dvdrip" in title.lower() or "(fullb" in title.lower() or "(blu" in title.lower() or "(4k" in title.lower() or "(hevc" in title.lower() or "(imax" in title.lower() or "extendida" in title.lower() or "[720p]" in title.lower() or "[1080p]" in title.lower():
if not item_local.quality:
item_local.quality = scrapertools.find_single_match(title, '[\[|\(](.*?)[\)|\]]')
title = re.sub(r'[\[|\(].*?[\)|\]]', '', title) title = re.sub(r'[\[|\(].*?[\)|\]]', '', title)
if not item_local.quality: if not item_local.quality:
if "fullbluray" in title.lower(): if "fullbluray" in title.lower():
@@ -450,12 +457,13 @@ def listado(item):
item_local.quality = "4K" item_local.quality = "4K"
title = title.replace("4k-hdr", "").replace("4K-HDR", "").replace("hdr", "").replace("HDR", "").replace("4k", "").replace("4K", "") title = title.replace("4k-hdr", "").replace("4K-HDR", "").replace("hdr", "").replace("HDR", "").replace("4k", "").replace("4K", "")
title = title.replace("(", "").replace(")", "").replace("[", "").replace("]", "").strip() title = title.replace("(", "").replace(")", "").replace("[", "").replace("]", "").strip()
if item_local.extra == "peliculas": if item_local.contentType == "movie":
item_local.title = title item_local.title = title
item_local.contentTitle = title item_local.contentTitle = title
elif item_local.contentType != "episode": elif item_local.contentType != "episode":
item_local.title = title item_local.title = title
item_local.title = item_local.contentSerieName item_local.title = item_local.contentSerieName
title = item_local.contentSerieName
item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título
if "saga" in item_local.contentTitle.lower() or "saga" in item_local.contentSerieName.lower(): if "saga" in item_local.contentTitle.lower() or "saga" in item_local.contentSerieName.lower():
@@ -505,14 +513,14 @@ def listado(item):
def listado_busqueda(item): def listado_busqueda(item):
logger.info() logger.info()
itemlist = [] itemlist = []
url_next_page ='' # Controlde paginación url_next_page ='' # Controlde paginación
cnt_tot = 39 # Poner el num. máximo de items por página. Dejamos que la web lo controle cnt_tot = 39 # 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_title = 0 # Contador de líneas insertadas en Itemlist
cnt_pag = 0 # Contador de líneas leídas de Matches cnt_pag = 0 # Contador de líneas leídas de Matches
cnt_next = 0 # Contador de páginas leidas antes de pintar la pantalla cnt_next = 0 # Contador de páginas leidas antes de pintar la pantalla
total_pag = 10 # Líneas por página de la web total_pag = 10 # Líneas por página de la web
curr_page_num = 1 # Página actual curr_page_num = 1 # Página actual
category = "" # Guarda la categoria que viene desde una busqueda global category = "" # Guarda la categoria que viene desde una busqueda global
matches = [] matches = []
if item.url_next_page: if item.url_next_page:
@@ -523,7 +531,7 @@ def listado_busqueda(item):
#Máximo num. de líneas permitidas por TMDB. Máx de 5 páginas por Itemlist para no degradar el rendimiento #Máximo num. de líneas permitidas por TMDB. Máx de 5 páginas por Itemlist para no degradar el rendimiento
while cnt_title <= cnt_tot and cnt_next < 5: while cnt_title <= cnt_tot and cnt_next < 5:
status = False # Calidad de los datos leídos status = False # Calidad de los datos leídos
data = '' data = ''
try: try:
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(url_next_page, post=item.post).data) data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(url_next_page, post=item.post).data)
@@ -532,10 +540,20 @@ def listado_busqueda(item):
except: except:
logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item.url + item.post + " / DATA: " + data) logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item.url + item.post + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO_BUSQUEDA:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO_BUSQUEDA:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log'))
if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
if not data: #Si la web está caída salimos sin dar error if not data: #Si la web está caída salimos sin dar error
logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item.url + item.post + " / DATA: " + data) logger.error("ERROR 01: LISTADO_BUSQUEDA: La Web no responde o ha cambiado de URL: " + item.url + item.post + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO_BUSQUEDA:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: LISTADO_BUSQUEDA:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log'))
if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
cnt_next += 1 cnt_next += 1
@@ -561,7 +579,11 @@ def listado_busqueda(item):
logger.error("ERROR 02: LISTADO_BUSQUEDA: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO_BUSQUEDA: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: LISTADO_BUSQUEDA: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': 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) #Llamamos al método para el pintado del error if len(itemlist) > 1:
#Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Capturamos el num. de la última página para informala a pié de página #Capturamos el num. de la última página para informala a pié de página
@@ -591,7 +613,7 @@ def listado_busqueda(item):
item_local = item.clone() item_local = item.clone()
if item_local.category: if item_local.category:
category = item.category category = item.category
del item_local.category item_local.category = item_local.channel.capitalize()
item_local.tipo = True item_local.tipo = True
del item_local.tipo del item_local.tipo
if item_local.totalItems: if item_local.totalItems:
@@ -624,9 +646,6 @@ def listado_busqueda(item):
title = title.replace(" Latino", "").replace(" latino", "").replace(" Argentina", "").replace(" argentina", "") title = title.replace(" Latino", "").replace(" latino", "").replace(" Argentina", "").replace(" argentina", "")
title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "") title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "")
if "3d" in title or "3D" in title: #Reservamos info para después de TMDB
item_local.quality += " 3D"
title = title.replace(" [3d]", "").replace(" 3d", "").replace(" [3D]", "").replace(" 3D", "")
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')] title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) title = re.sub(r'\[[a|A]udio.*?\]', '', title)
@@ -645,7 +664,8 @@ def listado_busqueda(item):
title = scrapertools.remove_htmltags(title) title = scrapertools.remove_htmltags(title)
# Ahora preparamos el título y la calidad tanto para series como para documentales y películas # Ahora preparamos el título y la calidad tanto para series como para documentales y películas
if item.extra == "novedades" and ("Series" in scrapedtype or "Documentales" in scrapedtype): #if item.extra == "novedades" and ("Series" in scrapedtype or "Documentales" in scrapedtype):
if item.extra == "novedades":
item_local.quality = scrapertools.find_single_match(scrapedtitle, '.*?\[(.*?)\]') item_local.quality = scrapertools.find_single_match(scrapedtitle, '.*?\[(.*?)\]')
else: else:
item_local.quality = scrapertools.remove_htmltags(scrapedquality).decode('utf8').encode('utf8') item_local.quality = scrapertools.remove_htmltags(scrapedquality).decode('utf8').encode('utf8')
@@ -660,8 +680,8 @@ def listado_busqueda(item):
item_local.extra = "documentales" item_local.extra = "documentales"
item_local.contentType = "season" item_local.contentType = "season"
title = re.sub(r'\[\d+.*?\]', '', title) # Quitar la calidad del título title = re.sub(r'\[\d+.*?\]', '', title) # Quitar la calidad del título
item_local.contentSerieName = scrapertools.find_single_match(title, '(.*?) Temporada \d+\s?').strip() item_local.contentSerieName = scrapertools.find_single_match(title, '(.*?) Temporada\s?(?:\d+)?\s?').strip()
if not item_local.contentSerieName: if not item_local.contentSerieName:
item_local.contentSerieName = title.strip() item_local.contentSerieName = title.strip()
if item_local.infoLabels['title']: if item_local.infoLabels['title']:
@@ -673,12 +693,17 @@ def listado_busqueda(item):
item_local.contentSeason = scrapertools.find_single_match(scrapedurl, 'temporada-?(?:\d+p-)?(\d{1,2})[-|\/]') item_local.contentSeason = scrapertools.find_single_match(scrapedurl, 'temporada-?(?:\d+p-)?(\d{1,2})[-|\/]')
if not item_local.contentSeason: if not item_local.contentSeason:
item_local.contentSeason = 1 item_local.contentSeason = 1
title = title.replace('Temporada', '').replace('temporada', '')
if not scrapertools.find_single_match(title, '[\[|\(](.*?)[\)|\]]') in item_local.quality:
if item_local.quality:
item_local.quality += ' '
item_local.quality += scrapertools.find_single_match(title, '[\[|\(](.*?)[\)|\]]')
if scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]') and not scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]') in item_local.quality:
item_local.quality += ' %s' % scrapertools.find_single_match(title, '[\[|\(].*?[\)|\]]\s?[\[|\(](.*?)[\)|\]]')
title = re.sub(r'[\[|\(].*?[\)|\]]\s?[\[|\(].*?[\)|\]]', '', title)
title = re.sub(r'[\[|\(].*?[\)|\]]', '', title)
if "(hdrip" in title.lower() or "(br" in title.lower() or "(vhsrip" in title.lower() or "(dvdrip" in title.lower() or "(fullb" in title.lower() or "(blu" in title.lower() or "(4k" in title.lower() or "(hevc" in title.lower() or "(imax" in title.lower() or "extendida" in title.lower() or "[720p]" in title.lower() or "[1080p]" in title.lower(): if "(hdrip" in title.lower() or "(br" in title.lower() or "(vhsrip" in title.lower() or "(dvdrip" in title.lower() or "(fullb" in title.lower() or "(blu" in title.lower() or "(4k" in title.lower() or "(hevc" in title.lower() or "(imax" in title.lower() or "extendida" in title.lower() or "[720p]" in title.lower() or "[1080p]" in title.lower():
if not item_local.quality:
item_local.quality = scrapertools.find_single_match(title, r'\(.*?\)?\(.*?\)')
if not item_local.quality:
item_local.quality = scrapertools.find_single_match(title, r'[\[|\(](.*?)[\)|\]]')
title = re.sub(r'\(.*?\)?\(.*?\)', '', title) title = re.sub(r'\(.*?\)?\(.*?\)', '', title)
title = re.sub(r'[\[|\(].*?[\)|\]]', '', title) title = re.sub(r'[\[|\(].*?[\)|\]]', '', title)
if not item_local.quality: if not item_local.quality:
@@ -744,9 +769,11 @@ def findvideos(item):
logger.info() logger.info()
itemlist = [] itemlist = []
#logger.debug(item)
data = '' data = ''
torrent_data = '' torrent_data = ''
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Referer': item.url} #Necesario para el Post del .Torrent headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Referer': item.url} #Necesario para el Post del .Torrent
#Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB #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) item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
@@ -781,7 +808,7 @@ def findvideos(item):
#logger.debug(matches) #logger.debug(matches)
#logger.debug(data) #logger.debug(data)
for scrapedurl, name1, value1, value2, name2 in matches: for scrapedurl, name1, value1, value2, name2 in matches: #Hacemos el FOR aunque solo habrá un item
#Generamos una copia de Item para trabajar sobre ella #Generamos una copia de Item para trabajar sobre ella
item_local = item.clone() item_local = item.clone()
url = scrapedurl url = scrapedurl
@@ -790,11 +817,11 @@ def findvideos(item):
post = '%s=%s&%s=%s' % (name1, value1, name2, value2) post = '%s=%s&%s=%s' % (name1, value1, name2, value2)
try: try:
torrent_data = httptools.downloadpage(url, post=post, headers=headers, follow_redirects=False) torrent_data = httptools.downloadpage(url, post=post, headers=headers, follow_redirects=False)
except: #error except: #error
pass pass
else: else:
#Generamos una copia de Item para trabajar sobre ella #Viene de SERIES y DOCUMENTALES. Generamos una copia de Item para trabajar sobre ella
item_local = item.clone() item_local = item.clone()
try: #Localiza el .torrent en el siguiente link con Post. Viene de Documentales y Varios try: #Localiza el .torrent en el siguiente link con Post. Viene de Documentales y Varios
url = item.url_post url = item.url_post
@@ -802,7 +829,6 @@ def findvideos(item):
except: except:
pass pass
#logger.debug(torrent_data.headers)
if not torrent_data: if not torrent_data:
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
@@ -813,7 +839,8 @@ def findvideos(item):
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web. Verificar en la Web y reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
item_local.url = torrent_data.headers['location'] #Capturamos la url del .torrent desde el Header #Capturamos la url del .torrent desde el Header
item_local.url = torrent_data.headers['location'] if 'location' in torrent_data.headers else item.url_post
item_local.url = item_local.url.replace(" ", "%20") #Quitamos espacios item_local.url = item_local.url.replace(" ", "%20") #Quitamos espacios
# Poner la calidad, si es necesario # Poner la calidad, si es necesario
@@ -838,14 +865,14 @@ def findvideos(item):
#Ahora pintamos el link del Torrent, si lo hay #Ahora pintamos el link del Torrent, si lo hay
if item_local.url: # Hay Torrent ? if item_local.url: # Hay Torrent ?
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 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
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title) #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title) #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
item_local.action = "play" #Visualizar vídeo item_local.action = "play" #Visualizar vídeo
item_local.server = "torrent" #Seridor Torrent item_local.server = "torrent" #Seridor Torrent
itemlist.append(item_local.clone()) #Pintar pantalla itemlist.append(item_local.clone()) #Pintar pantalla
#logger.debug("title=[" + item.title + "], torrent=[ " + item_local.url + " ], url=[ " + url + " ], post=[" + item.post + "], thumbnail=[ " + item.thumbnail + " ]" + " size: " + size) #logger.debug("title=[" + item.title + "], torrent=[ " + item_local.url + " ], url=[ " + url + " ], post=[" + item.post + "], thumbnail=[ " + item.thumbnail + " ]" + " size: " + size)
#logger.debug(item_local) #logger.debug(item_local)
@@ -862,28 +889,38 @@ def episodios(item):
tmdb.set_infoLabels(item, True) tmdb.set_infoLabels(item, True)
# Carga la página # Carga la página
data = '' data_ini = ''
try: try:
data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url).data) data_ini = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url).data)
data = data.replace('"', "'") data_ini = data_ini.replace('"', "'")
except: #Algún error de proceso, salimos except: #Algún error de proceso, salimos
pass pass
if not data: if not data_ini:
logger.error("ERROR 01: EPISODIOS: La Web no responde o la URL es erronea" + item.url) logger.error("ERROR 01: EPISODIOS: La Web no responde o la URL es erronea" + item.url)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist return itemlist
# Selecciona en tramo que nos interesa # Selecciona en tramo que nos interesa
data = scrapertools.find_single_match(data, "(<form (?:style='[^']+'\s)?name='episodios' action='[^']+' method='post'>.*?)<\/form>") data = scrapertools.find_single_match(data_ini, "(<form (?:style='[^']+'\s)?name='episodios' action='[^']+' method='post'>.*?)<\/form>")
# Prepara el patrón de búsqueda # Prepara el patrón de búsqueda
if item.extra == "documentales": patron = "<form (?:style='[^']+'\s)?name='episodios' action='([^']+)'"
patron = "<form (?:style='[^']+'\s)?name='episodios' action='([^']+)'.*?<input type='hidden' value='([^']+)' name='([^']+)'>" url = scrapertools.find_single_match(data, patron) #Salvamos la url de descarga
url, value2, name2 = scrapertools.find_single_match(data, patron) url = url.replace('descargar_series.php', 'descargar.php') #ESTA DESCARGARÍA EL TORRENT EN VEZ DEL ENLACE
patron = "<input type='\w+' name='([^']+)' value='([^']+)'>" patron = "<form (?:style='[^']+'\s)?name='episodios' action='[^']+'.*?<input type='hidden' value='([^']+)' name='([^']+)'>"
else: value2 = '' #Patrón general para Documentales (1)
patron = "<td bgcolor='[^>]+><a href='([^']+)'>[^<]+<\/a><\/td><td[^>]+><div[^>]+>([^<]+)?<\/div><\/td>" name2 = ''
if scrapertools.find_single_match(data, patron):
value2, name2 = scrapertools.find_single_match(data, patron) #extraemos valores para el Post
patron = "<td bgcolor='[^>]+><a href='([^']+)'>[^<]+<\/a><\/td><td[^>]+><div[^>]+>[^<]+?<\/div><\/td>.*?<input type='\w+'\s?name='([^']+)'\s?value='([^']+)'>\s?<\/td><\/tr>" #Patrón para series con Post
if not scrapertools.find_single_match(data, patron):
patron = "<form name='episodios' action='([^']+)'.*?<input type='\w+' name='([^']+)' value='([^']+)'>"
if not scrapertools.find_single_match(data, patron): #Patrón para documentales (2)
#Si no han funcionado los anteriores, usamos el tradicional para series sin Post
patron = "<td bgcolor='[^>]+><a href='([^']+)'>[^<]+<\/a><\/td><td[^>]+><div([^>]+)>([^<]+)?<\/div><\/td>"
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
if not matches: #error if not matches: #error
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
@@ -891,16 +928,16 @@ def episodios(item):
item, itemlist = generictools.post_tmdb_episodios(item, itemlist) #Llamamos al método para el pintado del error item, itemlist = generictools.post_tmdb_episodios(item, itemlist) #Llamamos al método para el pintado del error
return itemlist #Salimos return itemlist #Salimos
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA_INI: " + data_ini + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("PATRON: " + patron) #logger.debug("PATRON: " + patron)
#logger.debug(matches) #logger.debug(matches)
#logger.debug(data) #logger.debug(data)
# Recorremos todos los episodios generando un Item local por cada uno en Itemlist # Recorremos todos los episodios generando un Item local por cada uno en Itemlist
for scrapedurl, year in matches: for scrapedurl, name1, value1 in matches:
item_local = item.clone() item_local = item.clone()
item_local.action = "findvideos" item_local.action = "findvideos"
item_local.contentType = "episode" item_local.contentType = "episode"
@@ -922,43 +959,40 @@ def episodios(item):
item_local.context = "['buscar_trailer']" item_local.context = "['buscar_trailer']"
item_local.url = scrapedurl item_local.url = scrapedurl
if item.extra == "documentales": #llamada con post if name1 and value1: #llamada con post
name1 = scrapedurl item_local.url = item.url #Dejamos la url de la Temporada como Refer
value1 = year item_local.url_post = url #Ponemos la url de Descarga (retocado)
item_local.url = item.url item_local.post = '%s=%s' % (name1, value1) #Ponemos la primera pareja de valores
item_local.url_post = url if not name2 and not value2: #Si no hay segunda pareja...
item_local.post = '%s=%s&%s=%s' % (name1, value1, name2, value2) item_local.post = '%s=0&id_post=%s' % (name1, value1) #... adaptamos el formato final
if name2 and value2: #Si hay segunda pareja, la añadimos
if item_local.post:
item_local.post += '&'
item_local.post += '%s=%s' % (name2, value2)
scrapedtemp = ''
scrapedepi = ''
if scrapertools.find_single_match(scrapedurl, "\/.*?-(\d{1,2})x(\d{1,2})[-|\/]"):
scrapedtemp, scrapedepi = scrapertools.find_single_match(scrapedurl, "\/.*?-(\d{1,2})x(\d{1,2})[-|\/]")
scrapedepi2 = scrapertools.find_single_match(scrapedurl, "\/.*?-\d{1,2}x\d{1,2}-al-\d{1,2}x(\d{1,2})[-|\/]")
try:
item_local.contentSeason = int(scrapedtemp)
except:
item_local.contentSeason = 1 item_local.contentSeason = 1
try: try:
item_local.contentEpisodeNumber = int(value1) + 1 item_local.contentEpisodeNumber = int(scrapedepi)
except: except:
item_local.contentEpisodeNumber = 1 item_local.contentEpisodeNumber = 1
try:
scrapedepi2 = int(scrapedepi2)
except:
scrapedepi2 = ''
if scrapedepi2:
item_local.title = '%sx%s al %s -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2), str(scrapedepi2).zfill(2))
#item_local.infoLabels['episodio_titulo'] = 'al %s' % scrapedepi2
else: else:
scrapedtemp, scrapedepi = scrapertools.find_single_match(item_local.url, "\/.*?-(\d{1,2})x(\d{1,2})[-|\/]") item_local.title = '%sx%s -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber).zfill(2))
scrapedepi2 = scrapertools.find_single_match(item_local.url, "\/.*?-\d{1,2}x\d{1,2}-al-\d{1,2}x(\d{1,2})[-|\/]")
item_local.title = '%sx%s -' % (scrapedtemp, str(scrapedepi).zfill(2))
try:
item_local.contentSeason = int(scrapedtemp)
except:
item_local.contentSeason = 1
try:
item_local.contentEpisodeNumber = int(scrapedepi)
except:
item_local.contentEpisodeNumber = 1
try:
scrapedepi2 = int(scrapedepi2)
except:
scrapedepi2 = ''
if scrapedepi2:
item_local.title = '%sx%s al %s -' % (scrapedtemp, str(scrapedepi).zfill(2), str(scrapedepi2).zfill(2))
#item_local.infoLabels['episodio_titulo'] = 'al %s' % scrapedepi2
else:
item_local.title = '%sx%s -' % (scrapedtemp, str(scrapedepi).zfill(2))
if year:
item_local.infoLabels['year'] = scrapertools.find_single_match(year, r"(\d{4})")
itemlist.append(item_local.clone()) itemlist.append(item_local.clone())
+4 -3
View File
@@ -3,7 +3,7 @@
"name": "Newpct1", "name": "Newpct1",
"active": true, "active": true,
"adult": false, "adult": false,
"language": ["*"], "language": ["cast", "lat"],
"thumbnail": "newpct1.png", "thumbnail": "newpct1.png",
"banner": "newpct1.png", "banner": "newpct1.png",
"categories": [ "categories": [
@@ -44,6 +44,7 @@
"Tumejortorrent", "Tumejortorrent",
"Torrentlocura", "Torrentlocura",
"Tvsinpagar", "Tvsinpagar",
"Planetatorrent",
"Descargas2020", "Descargas2020",
"Mispelisyseries" "Mispelisyseries"
] ]
@@ -52,7 +53,7 @@
"id": "clonenewpct1_channels_list", "id": "clonenewpct1_channels_list",
"type": "text", "type": "text",
"label": "Lista de clones de NewPct1 y orden de uso", "label": "Lista de clones de NewPct1 y orden de uso",
"default": "('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', 'serie_episodios'), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('1', 'torrentlocura', 'http://torrentlocura.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')", "default": "('1', 'torrentrapid', 'http://torrentrapid.com/', 'movie, tvshow, season, episode', 'serie_episodios'), ('1', 'tumejortorrent', 'http://tumejortorrent.com/', 'movie, tvshow, season, episode', ''), ('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', 'descargas2020', 'http://descargas2020.com/', 'movie, tvshow, season, episode', ''), ('1', 'mispelisyseries', 'http://mispelisyseries.com/', 'movie', 'search, listado_busqueda')",
"enabled": true, "enabled": true,
"visible": false "visible": false
}, },
@@ -60,7 +61,7 @@
"id": "intervenidos_channels_list", "id": "intervenidos_channels_list",
"type": "text", "type": "text",
"label": "Lista de canales y clones de NewPct1 intervenidos y orden de sustitución de URLs", "label": "Lista de canales y clones de NewPct1 intervenidos y orden de sustitución de URLs",
"default": "('0', 'canal_org', 'canal_des', 'url_org', 'url_des', 'patron1', 'patron2', 'patron3', 'patron4', 'patron5', 'content_inc', 'content_exc', 'ow_force'), ('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)([^0-9]+-)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-\\d+-(Temporada-).html', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-(\\d+)-', '', 'tvshow, season', '', 'force'), ('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-([^.]+).html', '', '', '', 'movie', '', 'force'), ('1', 'newpct1', '', '', '', '', '', '', '', '', '*', '', 'del'), ('1', 'videolibrary', '', '', '', '', '', '', '', '', '*', '', 'del')", "default": "('0', 'canal_org', 'canal_des', 'url_org', 'url_des', 'patron1', 'patron2', 'patron3', 'patron4', 'patron5', 'content_inc', 'content_exc', 'ow_force'), ('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)([^0-9]+-)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-\\d+-(Temporada-).html', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-(?:[^-]+-)[^0-9]+-(\\d+)-', '', 'tvshow, season', '', 'force'), ('1', 'mejortorrent', 'mejortorrent1', 'http://www.mejortorrent.com/', 'https://mejortorrent1.com/', '(http.?:\/\/.*?\/)', 'http.?:\/\/.*?\/.*?-torrent.?-[^-]+-([^.]+).html', '', '', '', 'movie', '', 'force')",
"enabled": true, "enabled": true,
"visible": false "visible": false
}, },
+209 -171
View File
@@ -64,7 +64,7 @@ episodio_serie = config.get_setting('clonenewpct1_serie_episodio_novedades', cha
#Temporal, sólo para actualizar newpct1_data.json con otro valor por defecto #Temporal, sólo para actualizar newpct1_data.json con otro valor por defecto
#channel_banned = config.get_setting('clonenewpct1_excluir1_enlaces_veronline', channel_py) #1eer Canal baneado #channel_banned = config.get_setting('clonenewpct1_excluir1_enlaces_veronline', channel_py) #1eer Canal baneado
#if channel_banned == 9: #if channel_banned == 9:
# config.set_setting('clonenewpct1_excluir1_enlaces_veronline', 22, channel_py) #se pone el nuevo valor por defecto # config.set_setting('clonenewpct1_excluir1_enlaces_veronline', 22, channel_py) #se pone el nuevo valor por defecto
def mainlist(item): def mainlist(item):
@@ -148,7 +148,7 @@ def submenu(item):
if not data: #Si no ha logrado encontrar nada, salimos 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="[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')) 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 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 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.category + '[/COLOR] [ALT ] en uso'))
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible'))
@@ -165,7 +165,7 @@ def submenu(item):
if not data: if not data:
logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
patron = '<li><a.*?href="([^"]+)"\s?.itle="[^"]+"\s?>([^>]+)<\/a><\/li>' patron = '<li><a.*?href="([^"]+)"\s?.itle="[^"]+"\s?>([^>]+)<\/a><\/li>'
matches = re.compile(patron, re.DOTALL).findall(data) matches = re.compile(patron, re.DOTALL).findall(data)
@@ -173,7 +173,7 @@ def submenu(item):
if not matches: if not matches:
logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: SUBMENU: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: SUBMENU: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
for scrapedurl, scrapedtitle in matches: for scrapedurl, scrapedtitle in matches:
title = scrapedtitle.strip() title = scrapedtitle.strip()
@@ -208,7 +208,7 @@ def submenu_novedades(item):
if channel_clone_name == "*** DOWN ***": #Ningún clones activo !!! if channel_clone_name == "*** DOWN ***": #Ningún clones activo !!!
itemlist.append(item.clone(action='', title="[COLOR yellow]Ningún canal NewPct1 activo[/COLOR]")) itemlist.append(item.clone(action='', title="[COLOR yellow]Ningún canal NewPct1 activo[/COLOR]"))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos y salimos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos y salimos
try: try:
data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout_search).data) data = re.sub(r"\n|\r|\t|\s{2,}", "", httptools.downloadpage(item.url, timeout=timeout_search).data)
@@ -232,7 +232,7 @@ def submenu_novedades(item):
if not data: #Si no ha logrado encontrar nada, salimos 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="[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')) 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 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 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.category + '[/COLOR] [ALT ] en uso'))
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible'))
@@ -307,7 +307,7 @@ def alfabeto(item):
if not data: #Si no ha logrado encontrar nada, salimos 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="[COLOR yellow]" + item.category + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: ALFABETO: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: ALFABETO: 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 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 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.category + '[/COLOR] [ALT ] en uso'))
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel_alt.capitalize() + '[/COLOR] inaccesible'))
@@ -323,7 +323,7 @@ def alfabeto(item):
if not matches: if not matches:
logger.error("ERROR 02: ALFABETO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: ALFABETO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: ALFABETO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: ALFABETO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
for scrapedurl, scrapedtitle in matches: for scrapedurl, scrapedtitle in matches:
title = scrapedtitle.upper() title = scrapedtitle.upper()
@@ -336,9 +336,9 @@ def alfabeto(item):
def listado(item): def listado(item):
logger.info() logger.info()
itemlist = [] itemlist = []
clase = "pelilist" # etiqueta para localizar zona de listado de contenidos clase = "pelilist" # etiqueta para localizar zona de listado de contenidos
url_next_page ='' # Control de paginación url_next_page ='' # Control de paginación
cnt_tot = 30 # Poner el num. máximo de items por página cnt_tot = 30 # Poner el num. máximo de items por página
if item.totalItems: if item.totalItems:
del item.totalItems del item.totalItems
@@ -363,7 +363,7 @@ def listado(item):
if not data: #Si no ha logrado encontrar nada, salimos if not data: #Si no ha logrado encontrar nada, salimos
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: LISTADO: La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: LISTADO: 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 return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Establecemos los valores básicos en función del tipo de contenido #Establecemos los valores básicos en función del tipo de contenido
if item.extra == "peliculas": if item.extra == "peliculas":
@@ -387,7 +387,7 @@ def listado(item):
if not fichas and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data: #error if not fichas and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data: #error
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
elif '<h3><strong>( 0 ) Resultados encontrados </strong>' in data: #no hay vídeos elif '<h3><strong>( 0 ) Resultados encontrados </strong>' in data: #no hay vídeos
return itemlist return itemlist
else: else:
@@ -395,16 +395,16 @@ def listado(item):
page_extra = clase page_extra = clase
#Scrapea los datos de cada vídeo. Título alternativo se mantiene, aunque no se usa de momento #Scrapea los datos de cada vídeo. Título alternativo se mantiene, aunque no se usa de momento
patron = '<a href="([^"]+).*?' # la url patron = '<a href="([^"]+).*?' # la url
patron += 'title="([^"]+).*?' # el titulo patron += 'title="([^"]+).*?' # el titulo
patron += '<img.*?src="([^"]+)"[^>]+>.*?' # el thumbnail patron += '<img.*?src="([^"]+)"[^>]+>.*?' # el thumbnail
patron += '<h2.*?>(.*?)?<\/h2>' # titulo alternativo. Se trunca en títulos largos patron += '<h2.*?>(.*?)?<\/h2>' # titulo alternativo. Se trunca en títulos largos
patron += '<span>([^<].*?)?<' # la calidad patron += '<span>([^<].*?)?<' # la calidad
matches = re.compile(patron, re.DOTALL).findall(fichas) matches = re.compile(patron, re.DOTALL).findall(fichas)
if not matches: #error if not matches: #error
logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + fichas) logger.error("ERROR 02: LISTADO: Ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + fichas)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: LISTADO: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("MATCHES: " + str(len(matches))) #logger.debug("MATCHES: " + str(len(matches)))
#logger.debug(matches) #logger.debug(matches)
@@ -513,16 +513,18 @@ def listado(item):
title = title.replace("(2D)", "").replace("(2d)", "").replace("2D", "").replace("2d", "") title = title.replace("(2D)", "").replace("(2d)", "").replace("2D", "").replace("2d", "")
title_subs += ["[2D]"] title_subs += ["[2D]"]
#Extraemos info adicional del título y la guardamos para después de TMDB if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie":
if "temp" in title.lower() or "cap" in title.lower(): #Eliminamos Temporada, solo nos interesa la serie completa #Eliminamos Temporada de Series, solo nos interesa la serie completa
title = re.sub(r' - [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title) title = re.sub(r'-? [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r' - [t|T]emp\w+ \d+x\d+', '', title) title = re.sub(r'-? [t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r' - [t|T]emp\w+ \d+', '', title) title = re.sub(r'-? [t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r' - [t|T]emp\w+.*?\d+', '', title) title = re.sub(r'-? [t|T]emp\w+ \d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+x\d+', '', title) title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title) title = re.sub(r' [t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+', '', title) title = re.sub(r' [c|C]ap.*?\d+', '', title)
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')] title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) title = re.sub(r'\[[a|A]udio.*?\]', '', title)
if "[dual" in title.lower() or "multileng" in title.lower() or "multileng" in item_local.quality.lower() or (("espa" in title.lower() or "spani" in title.lower()) and "VOS" in item_local.language): if "[dual" in title.lower() or "multileng" in title.lower() or "multileng" in item_local.quality.lower() or (("espa" in title.lower() or "spani" in title.lower()) and "VOS" in item_local.language):
@@ -536,9 +538,9 @@ def listado(item):
if "trilog" in title.lower(): if "trilog" in title.lower():
title_subs += ["[Saga]"] title_subs += ["[Saga]"]
title = title.replace(" Trilogia", "").replace(" trilogia", "").replace(" Trilog", "").replace(" trilog", "") title = title.replace(" Trilogia", "").replace(" trilogia", "").replace(" Trilog", "").replace(" trilog", "")
if "extendida" in title.lower(): if "extendida" in title.lower() or "v.e." in title.lower()or "v e " in title.lower():
title_subs += ["[V. Extendida]"] title_subs += ["[V. Extendida]"]
title = title.replace(" Version Extendida", "").replace(" (Version Extendida)", "").replace(" V. Extendida", "").replace(" VExtendida", "").replace(" V Extendida", "") title = title.replace("Version Extendida", "").replace("(Version Extendida)", "").replace("V. Extendida", "").replace("VExtendida", "").replace("V Extendida", "").replace("V.Extendida", "").replace("V Extendida", "").replace("V.E.", "").replace("V E ", "")
if "saga" in title.lower(): if "saga" in title.lower():
title = title.replace(" Saga Completa", "").replace(" saga sompleta", "").replace(" Saga", "").replace(" saga", "") title = title.replace(" Saga Completa", "").replace(" saga sompleta", "").replace(" Saga", "").replace(" saga", "")
title_subs += ["[Saga]"] title_subs += ["[Saga]"]
@@ -549,21 +551,22 @@ def listado(item):
title_subs += ["[Miniserie]"] title_subs += ["[Miniserie]"]
#Limpiamos restos en título #Limpiamos restos en título
title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "") title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "").replace("Spanish", "")
title_alt = title_alt.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "") title_alt = title_alt.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "").replace("Spanish", "")
#Limpiamos cabeceras y colas del título #Limpiamos cabeceras y colas del título
title = re.sub(r'Descargar\s\w+\-\w+', '', title) title = re.sub(r'Descargar\s\w+\-\w+', '', title)
title = re.sub(r'\(COMPLE.*?\)', '', title) title = re.sub(r'\(COMPLE.*?\)', '', title)
title = title.replace("Ver online Serie", "").replace("Ver online ", "").replace("Descarga Serie HD ", "").replace("Descargar Serie HD ", "").replace("Descarga Serie ", "").replace("Descargar Serie ", "").replace("Ver en linea ", "").replace("Ver en linea", "").replace("en Full HD", "").replace("en hd ", "").replace("en HD ", "").replace("MicroHD", "").replace("HD ", "").replace("(Proper)", "").replace("HDTV", "").replace("RatDVD", "").replace("DVDRiP", "").replace("DVDRIP", "").replace("DVDRip", "").replace("DVDR", "").replace("DVD9", "").replace("DVD", "").replace("DVBRIP", "").replace("DVB", "").replace("LINE", "").replace("calidad", " ").replace("- ES ", "").replace("ES ", "").replace("COMPLETA", "").replace("Serie Animada", " ").replace("(", "-").replace(")", "-").replace(".", " ").strip()
title = title.replace("Descargar torrent ", "").replace("Descarga Gratis", "").replace("Descarga gratis", "").replace("Descargar Gratis", "").replace("Descargar gratis", "").replace("en gratis", "").replace("gratis gratis", "").replace("Gratisgratis", "").replace("Descargar Estreno ", "").replace("Descargar Estrenos ", "").replace("Pelicula en latino ", "").replace("Descargar Pelicula ", "").replace("Descargar pelicula ", "").replace("Descargar Peliculas ", "").replace("Descargar peliculas ", "").replace("Descargar Todas ", "").replace("Descargar Otras ", "").replace("Descargar ", "").replace("Descarga ", "").replace("Descargar ", "").replace("Decargar ", "").replace("Bajar ", "").replace("HDRIP ", "").replace("HDRiP ", "").replace("HDRip ", "").replace("RIP ", "").replace("Rip", "").replace("RiP", "").replace("XviD", "").replace("AC3 5.1", "").replace("AC3", "").replace("1080p ", "").replace("720p ", "").replace("DVD-Screener ", "").replace("TS-Screener ", "").replace("Screener ", "").replace("BdRemux ", "").replace("BR ", "").replace("4K UHDrip", "").replace("BDremux", "").replace("FULL UHD4K", "").replace("4KULTRA", "").replace("FULLBluRay", "").replace("FullBluRay", "").replace("en BluRay", "").replace("BluRay en", "").replace("Bluray en", "").replace("BluRay", "").replace("Bonus Disc", "").replace("de Cine ", "").replace("TeleCine ", "").replace("latino", "").replace("Latino", "").replace("argentina", "").replace("Argentina", "").replace("++Sub", "").replace("+-+Sub", "").strip()
title = re.sub(r'\(\d{4}\)$', '', title) title = re.sub(r'\(\d{4}\)$', '', title)
if re.sub(r'\d{4}$', '', title).strip(): if re.sub(r'\d{4}$', '', title).strip():
title = re.sub(r'\d{4}$', '', title) title = re.sub(r'\d{4}$', '', title)
title = re.sub(r' \d+x\d+', '', title) title = re.sub(r'\d+x\d+', '', title)
title = re.sub(r' x\d+', '', title) title = re.sub(r'x\d+', '', title).strip()
title = title.replace("Ver online ", "").replace("Descarga Serie HD ", "").replace("Descargar Serie HD ", "").replace("Descarga Serie ", "").replace("Descargar Serie ", "").replace("Ver en linea ", "").replace("Ver en linea", "").replace("en Full HD", "").replace("en hd ", "").replace("en HD ", "").replace("HD ", "").replace("(Proper)", "").replace("RatDVD", "").replace("DVDRiP", "").replace("DVDRIP", "").replace("DVDRip", "").replace("DVDR", "").replace("DVD9", "").replace("DVD", "").replace("DVBRIP", "").replace("DVB", "").replace("LINE", "").replace("calidad", " ").replace("- ES ", "").replace("ES ", "").replace("COMPLETA", "").replace("(", "-").replace(")", "-").replace(".", " ").strip()
title = title.replace("Descargar torrent ", "").replace("Descarga Gratis", "").replace("Descarga gratis", "").replace("Descargar Gratis", "").replace("Descargar gratis", "").replace("en gratis", "").replace("gratis gratis", "").replace("Gratisgratis", "").replace("Descargar Estreno ", "").replace("Descargar Estrenos ", "").replace("Pelicula en latino ", "").replace("Descargar Pelicula ", "").replace("Descargar pelicula ", "").replace("Descargar Peliculas ", "").replace("Descargar peliculas ", "").replace("Descargar Todas ", "").replace("Descargar Otras ", "").replace("Descargar ", "").replace("Descarga ", "").replace("Descargar ", "").replace("Decargar ", "").replace("Bajar ", "").replace("HDRIP ", "").replace("HDRiP ", "").replace("HDRip ", "").replace("RIP ", "").replace("Rip", "").replace("RiP", "").replace("XviD", "").replace("AC3 5.1", "").replace("AC3", "").replace("1080p ", "").replace("720p ", "").replace("DVD-Screener ", "").replace("TS-Screener ", "").replace("Screener ", "").replace("BdRemux ", "").replace("BR ", "").replace("4KULTRA", "").replace("FULLBluRay", "").replace("FullBluRay", "").replace("en BluRay", "").replace("BluRay en", "").replace("Bluray en", "").replace("BluRay", "").replace("Bonus Disc", "").replace("de Cine ", "").replace("TeleCine ", "").replace("latino", "").replace("Latino", "").replace("argentina", "").replace("Argentina", "").replace("++Sub", "").replace("+-+Sub", "").strip()
if title.endswith("torrent gratis"): title = title[:-15] if title.endswith("torrent gratis"): title = title[:-15]
if title.endswith("gratis"): title = title[:-7] if title.endswith("gratis"): title = title[:-7]
@@ -590,7 +593,7 @@ def listado(item):
#Limpieza final del título y guardado en las variables según su tipo de contenido #Limpieza final del título y guardado en las variables según su tipo de contenido
title = scrapertools.remove_htmltags(title) title = scrapertools.remove_htmltags(title)
item_local.title = title item_local.title = title
item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título
if item_local.contentType == "movie": if item_local.contentType == "movie":
item_local.contentTitle = title item_local.contentTitle = title
else: else:
@@ -649,10 +652,10 @@ def listado_busqueda(item):
if channel_clone_name == "*** DOWN ***": #Ningún clones activo !!! if channel_clone_name == "*** DOWN ***": #Ningún clones activo !!!
itemlist.append(item.clone(action='', title="[COLOR yellow]Ningún canal NewPct1 activo[/COLOR]")) itemlist.append(item.clone(action='', title="[COLOR yellow]Ningún canal NewPct1 activo[/COLOR]"))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos y salimos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos y salimos
itemlist = [] itemlist = []
cnt_tot = 40 # Poner el num. máximo de items por página. Dejamos que la web lo controle 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_title = 0 # Contador de líneas insertadas en Itemlist
cnt_pag = 0 # Contador de líneas leídas de Matches 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
@@ -671,8 +674,8 @@ def listado_busqueda(item):
del item.text_color del item.text_color
#Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios #Sistema de paginado para evitar páginas vacías o semi-vacías en casos de búsquedas con series con muchos episodios
title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas title_lista = [] # Guarda la lista de series que ya están en Itemlist, para no duplicar lineas
if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada if item.title_lista: # Si viene de una pasada anterior, la lista ya estará guardada
title_lista = item.title_lista # Se usa la lista de páginas anteriores en Item title_lista = item.title_lista # Se usa la lista de páginas anteriores en Item
title_lista_alt = [] title_lista_alt = []
for url in title_lista: for url in title_lista:
@@ -692,10 +695,11 @@ def listado_busqueda(item):
pass pass
cnt_next += 1 cnt_next += 1
#seleccionamos el bloque que nos interesa
if item.extra == "novedades": if item.extra == "novedades":
pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->' #seleccionamos el bloque que nos interesa pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->'
else: else:
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa pattern = '<ul class="%s">(.*?)</ul>' % item.pattern
if not data or (not scrapertools.find_single_match(data, pattern) and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data): if not data or (not scrapertools.find_single_match(data, pattern) and not '<h3><strong>( 0 ) Resultados encontrados </strong>' in data):
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
@@ -709,34 +713,40 @@ def listado_busqueda(item):
if not data: #Si no ha logrado encontrar nada, salimos if not data: #Si no ha logrado encontrar nada, salimos
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: LISTADO_BUSQUEDA:. La Web no responde o ha cambiado de URL. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: LISTADO_BUSQUEDA:. 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 if len(itemlist) > 2:
elif item.channel_alt: #Si ha habido fail-over, lo comento #Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
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
host = host.replace(item.channel_alt, item.channel) host = host.replace(item.channel_alt, item.channel)
#Obtiene la dirección de la próxima página, si la hay #Obtiene la dirección de la próxima página, si la hay
try: try:
post_actual = item.post #Guardamos el post actual por si hay overflow de Itemlist y hay que hechar marcha atrás post_actual = item.post #Guardamos el post actual por si hay overflow de Itemlist y hay que hechar marcha atrás
#Probamos si es Novedades o Planetatorrent, sino, el resto
if item.extra == "novedades": if scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+pg[\/|=])(\d+)">Next<\/a>.*?<a\s*href="[^"]+pg[\/|=](\d+)">Last<\/a>'):
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>') 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: else:
get, post, total_pag = scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+)"(?:\s*onClick=".*?\(\'([^"]+)\'\);">Next<\/a>.*?onClick=".*?\(\'([^"]+)\'\);">Last<\/a>)') get, post, total_pag = scrapertools.find_single_match(data, '<ul class="pagination">.*?<a\s*href="([^"]+)"(?:\s*onClick=".*?\(\'([^"]+)\'\);">Next<\/a>.*?onClick=".*?\(\'([^"]+)\'\);">Last<\/a>)')
except: except:
post = False post = False
cnt_next = 99 #No hay más páginas. Salir del bucle después de procesar ésta cnt_next = 99 #No hay más páginas. Salir del bucle después de procesar ésta
if post: #puntero a la siguiente página. Cada página de la web tiene 30 entradas if post: #puntero a la siguiente página. Cada página de la web tiene 30 entradas
if "pg" in item.post: if "pg" in item.post:
item.post = re.sub(r"pg=(\d+)", "pg=%s" % post, item.post) item.post = re.sub(r"pg=(\d+)", "pg=%s" % post, item.post)
else: else:
item.post += "&pg=%s" % post item.post += "&pg=%s" % post
post_num = int(post)-1 #Guardo página actual post_num = int(post)-1 #Guardo página actual
# Preparamos un patron que pretence recoger todos los datos significativos del video # Preparamos un patron que pretence recoger todos los datos significativos del video
#seleccionamos el bloque que nos interesa
if item.extra == "novedades": if item.extra == "novedades":
pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->' #seleccionamos el bloque que nos interesa pattern = '<div class="content">.*?<ul class="noticias(.*?)<\/div><!-- end .content -->'
else: else:
pattern = '<ul class="%s">(.*?)</ul>' % item.pattern #seleccionamos el bloque que nos interesa pattern = '<ul class="%s">(.*?)</ul>' % item.pattern
data_alt = data data_alt = data
data = scrapertools.get_match(data, pattern) data = scrapertools.get_match(data, pattern)
if item.extra == "novedades": if item.extra == "novedades":
@@ -758,29 +768,33 @@ def listado_busqueda(item):
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 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) 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')) 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 if len(itemlist) > 1:
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos #Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__)
#Llamamos al método para el maquillaje de los títulos obtenidos desde TMDB
item, itemlist = generictools.post_tmdb_listado(item, itemlist)
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
#Ahora se hace una simulación para saber cuantas líneas podemos albergar en este Itemlist. #Ahora se hace una simulación para saber cuantas líneas podemos albergar en este Itemlist.
#Se controlará cuantas páginas web se tienen que leer para rellenar la lista, sin pasarse #Se controlará cuantas páginas web se tienen que leer para rellenar la lista, sin pasarse
title_lista_alt_for = [] #usamos está lista de urls para el FOR, luego la integramos en la del WHILE title_lista_alt_for = [] #usamos está lista de urls para el FOR, luego la integramos en la del WHILE
for scrapedurl, scrapedtitle, scrapedthumbnail, calidad, year, size in matches_alt: for scrapedurl, scrapedtitle, scrapedthumbnail, calidad, year, size in matches_alt:
#Realiza un control de las series que se añaden, ya que el buscador devuelve episodios y no las series completas #Realiza un control de las series que se añaden, ya que el buscador devuelve episodios y no las series completas
#Se analiza si la url de la serie ya se ha listado antes. Si es así, esa entrada se ignora #Se analiza si la url de la serie ya se ha listado antes. Si es así, esa entrada se ignora
#Cuando llega al num. máximo de entradas por página, la pinta y guarda los contadores y la lista de series #Cuando llega al num. máximo de entradas por página, la pinta y guarda los contadores y la lista de series
scrapedurl_alt = scrapedurl scrapedurl_alt = scrapedurl
if "pelisyseries.com" in host: #Excepción para mispelisyseries.com. if "pelisyseries.com" in host: #Excepción para mispelisyseries.com.
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+-al-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+-al-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/\d{5,7}', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/\d{5,7}', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
if scrapedurl_alt in title_lista_alt: # si ya se ha tratado, pasamos al siguiente item if scrapedurl_alt in title_lista_alt: # si ya se ha tratado, pasamos al siguiente item
continue # solo guardamos la url para series y docus continue # solo guardamos la url para series y docus
if scrapedurl_alt in title_lista_alt or scrapedurl_alt in title_lista_alt_for or scrapedthumbnail in title_lista_alt or scrapedthumbnail in title_lista_alt_for: # si ya se ha tratado, pasamos al siguiente item if scrapedurl_alt in title_lista_alt or scrapedurl_alt in title_lista_alt_for or scrapedthumbnail in title_lista_alt or scrapedthumbnail in title_lista_alt_for: # si ya se ha tratado, pasamos al siguiente item
continue # solo guardamos la url para series y docus continue # solo guardamos la url para series y docus
if ".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl or "varios/" in scrapedurl: if ".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl or "varios/" in scrapedurl:
title_lista_alt_for += [scrapedurl_alt] title_lista_alt_for += [scrapedurl_alt]
@@ -791,16 +805,16 @@ def listado_busqueda(item):
cnt_title += 1 # Sería una línea real más para Itemlist cnt_title += 1 # Sería una línea real más para Itemlist
#Control de página #Control de página
if cnt_title > cnt_tot*0.65: #si se acerca al máximo num. de lineas por pagina, tratamos lo que tenemos if cnt_title > cnt_tot*0.65: #si se acerca al máximo num. de lineas por pagina, tratamos lo que tenemos
cnt_next = 99 #Casi completo, no sobrepasar con la siguiente página cnt_next = 99 #Casi completo, no sobrepasar con la siguiente página
if cnt_title > cnt_tot: if cnt_title > cnt_tot:
cnt_title = 99 #Sobrepasado el máximo. Ignoro página actual cnt_title = 99 #Sobrepasado el máximo. Ignoro página actual
item.post = post_actual #Restauro puntero "next" a la página actual, para releearla en otra pasada item.post = post_actual #Restauro puntero "next" a la página actual, para releearla en otra pasada
post_num -= 1 #Restauro puntero a la página actual en el pie de página post_num -= 1 #Restauro puntero a la página actual en el pie de página
break break
if cnt_title <= cnt_tot: if cnt_title <= cnt_tot:
matches.extend(matches_alt) #Acumulamos las entradas a tratar. Si nos hemos pasado ignoro última página matches.extend(matches_alt) #Acumulamos las entradas a tratar. Si nos hemos pasado ignoro última página
title_lista_alt.extend(title_lista_alt_for) title_lista_alt.extend(title_lista_alt_for)
#logger.debug("PATRON: " + pattern) #logger.debug("PATRON: " + pattern)
@@ -817,15 +831,15 @@ def listado_busqueda(item):
#El control de página ya se ha realizado más arriba #El control de página ya se ha realizado más arriba
if "pelisyseries.com" in host: #Excepción para mispelisyseries.com. if "pelisyseries.com" in host: #Excepción para mispelisyseries.com.
scrapedurl_alt = scrapedurl scrapedurl_alt = scrapedurl
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+-al-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+-al-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-\d+', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/[c|C]ap.*?-', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
scrapedurl_alt = re.sub(r'\/\d{5,7}', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie scrapedurl_alt = re.sub(r'\/\d{5,7}', '', scrapedurl_alt) #Scrapeo el capítulo para hacerlo serie
if scrapedurl_alt in title_lista: # si ya se ha tratado, pasamos al siguiente item if scrapedurl_alt in title_lista: # si ya se ha tratado, pasamos al siguiente item
continue # solo guardamos la url para series y docus continue # solo guardamos la url para series y docus
if scrapedurl in title_lista or scrapedthumbnail in title_lista: # si ya se ha tratado, pasamos al siguiente item if scrapedurl in title_lista or scrapedthumbnail in title_lista: # si ya se ha tratado, pasamos al siguiente item
continue # solo guardamos la url para series y docus continue # solo guardamos la url para series y docus
if ".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl or "varios/" in scrapedurl: if ".com/serie" in scrapedurl or "/serie" in scrapedurl or "-serie" in scrapedurl or "varios/" in scrapedurl:
if "pelisyseries.com" in host: if "pelisyseries.com" in host:
@@ -836,7 +850,7 @@ def listado_busqueda(item):
if ("juego/" in scrapedurl or "xbox" in scrapedurl.lower()) and not "/serie" in scrapedurl or "xbox" in scrapedtitle.lower() or "windows" in scrapedtitle.lower() or "windows" in calidad.lower() or "nintendo" in scrapedtitle.lower() or "xbox" in calidad.lower() or "epub" in calidad.lower() or "pdf" in calidad.lower() or "pcdvd" in calidad.lower() or "crack" in calidad.lower(): # no mostramos lo que no sean videos if ("juego/" in scrapedurl or "xbox" in scrapedurl.lower()) and not "/serie" in scrapedurl or "xbox" in scrapedtitle.lower() or "windows" in scrapedtitle.lower() or "windows" in calidad.lower() or "nintendo" in scrapedtitle.lower() or "xbox" in calidad.lower() or "epub" in calidad.lower() or "pdf" in calidad.lower() or "pcdvd" in calidad.lower() or "crack" in calidad.lower(): # no mostramos lo que no sean videos
continue continue
cnt_title += 1 # Sería una línea real más para Itemlist cnt_title += 1 # Sería una línea real más para Itemlist
#Creamos una copia de Item para cada contenido #Creamos una copia de Item para cada contenido
item_local = item.clone() item_local = item.clone()
@@ -868,8 +882,8 @@ def listado_busqueda(item):
#Si son episodios sueltos de Series que vienen de Novedades, se busca la url de la Serie #Si son episodios sueltos de Series que vienen de Novedades, se busca la url de la Serie
if item.extra == "novedades" and "/serie" in url and episodio_serie == 1: if item.extra == "novedades" and "/serie" in url and episodio_serie == 1:
item_local.url = url item_local.url = url
item_local.extra2 = 'serie_episodios' #Creamos acción temporal excluyente para otros clones 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 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 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 #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) item_local, data_serie = generictools.fail_over_newpct1(item_local, pattern)
@@ -885,7 +899,7 @@ def listado_busqueda(item):
#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 #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) item_local, data_serie = generictools.fail_over_newpct1(item_local, pattern)
if not data_serie: #Si no ha logrado encontrar nada, salimos if not data_serie: #Si no ha logrado encontrar nada, salimos
title_subs += ["ERR"] title_subs += ["ERR"]
elif item_local.channel_alt: #Si ha habido fail-over, lo comento elif item_local.channel_alt: #Si ha habido fail-over, lo comento
@@ -895,9 +909,16 @@ def listado_busqueda(item):
try: try:
pattern = '<div class="content">.*?<h1>.*?<a href="([^"]+)"' #Patron para Serie completa pattern = '<div class="content">.*?<h1>.*?<a href="([^"]+)"' #Patron para Serie completa
item_local.url = scrapertools.find_single_match(data_serie, pattern) 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 url: #Son series VO mal formadas? #Son series VO mal formadas?
if (item.post and '775' in item.post and 'vo/' not in item_local.url) or 'vo/' in url:
item_local.url = item_local.url.replace('/series/', '/series-vo/') 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.
#Son series HD formada como series estándar?
#if (scrapertools.find_single_match(item_local.quality, '\d{3, 4}p')) and '/series/' in item_local.url:
if 'hd/' in url:
item_local.url = item_local.url.replace('/series/', '/series-hd/')
#item_local.url = re.sub(r'\/\d+$', '/', item_local.url) #Quitamos el ID de la serie por compatib.
if item_local.url: if item_local.url:
title_subs += ["Episodio %sx%s" % (scrapertools.find_single_match(url, '\/temp.*?-(\d+)-?\/cap.*?-(\d+(?:-al-\d+)?)-?\/'))] title_subs += ["Episodio %sx%s" % (scrapertools.find_single_match(url, '\/temp.*?-(\d+)-?\/cap.*?-(\d+(?:-al-\d+)?)-?\/'))]
url = item_local.url url = item_local.url
@@ -965,15 +986,16 @@ def listado_busqueda(item):
#Extraemos info adicional del título y la guardamos para después de TMDB #Extraemos info adicional del título y la guardamos para después de TMDB
if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie": if ("temp" in title.lower() or "cap" in title.lower()) and item_local.contentType != "movie":
#Eliminamos Temporada de Series, solo nos interesa la serie completa #Eliminamos Temporada de Series, solo nos interesa la serie completa
title = re.sub(r' - [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title) title = re.sub(r'-? [t|T]emp\w+ \d+ Comp\w+\d+[x|X]\d+', ' Completa', title)
title = re.sub(r' - [t|T]emp\w+ \d+[x|X]\d+', '', title) title = re.sub(r'-? [t|T]emp\w+.?\d+.?[c|C]ap\w+.?\d+.?(?:al|Al|y).?\d+', '', title)
title = re.sub(r' - [t|T]emp\w+ \d+', '', title) title = re.sub(r'-? [t|T]emp\w+ \d+x\d+', '', title)
title = re.sub(r' - [t|T]emp\w+.*?\d+', '', title) title = re.sub(r'-? [t|T]emp\w+ \d+', '', title)
title = re.sub(r'-? [t|T]emp\w+.*?\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title) title = re.sub(r' [t|T]emp.*?\d+[x|X]\d+', '', title)
title = re.sub(r' [t|T]emp.*?\d+', '', title) title = re.sub(r' [t|T]emp.*?\d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title) title = re.sub(r' [c|C]ap.*?\d+ al \d+', '', title)
title = re.sub(r' [c|C]ap.*?\d+', '', title) title = re.sub(r' [c|C]ap.*?\d+', '', title)
if "audio" in title.lower(): #Reservamos info de audio para después de TMDB if "audio" in title.lower(): #Reservamos info de audio para después de TMDB
title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')] title_subs += ['[%s]' % scrapertools.find_single_match(title, r'(\[[a|A]udio.*?\])')]
title = re.sub(r'\[[a|A]udio.*?\]', '', title) title = re.sub(r'\[[a|A]udio.*?\]', '', title)
if "[dual" in title.lower() or "multileng" in title.lower() or "multileng" in item_local.quality.lower() or (("espa" in title.lower() or "spani" in title.lower()) and "VOS" in item_local.language): if "[dual" in title.lower() or "multileng" in title.lower() or "multileng" in item_local.quality.lower() or (("espa" in title.lower() or "spani" in title.lower()) and "VOS" in item_local.language):
@@ -987,9 +1009,9 @@ def listado_busqueda(item):
if "trilog" in title.lower(): if "trilog" in title.lower():
title_subs += ["[Saga]"] title_subs += ["[Saga]"]
title = title.replace(" Trilogia", "").replace(" trilogia", "").replace(" Trilog", "").replace(" trilog", "") title = title.replace(" Trilogia", "").replace(" trilogia", "").replace(" Trilog", "").replace(" trilog", "")
if "extendida" in title.lower(): if "extendida" in title.lower() or "v.e." in title.lower()or "v e " in title.lower():
title_subs += ["[V. Extendida]"] title_subs += ["[V. Extendida]"]
title = title.replace(" Version Extendida", "").replace(" (Version Extendida)", "").replace(" V. Extendida", "").replace(" VExtendida", "").replace(" V Extendida", "") title = title.replace("Version Extendida", "").replace("(Version Extendida)", "").replace("V. Extendida", "").replace("VExtendida", "").replace("V Extendida", "").replace("V.Extendida", "").replace("V Extendida", "").replace("V.E.", "").replace("V E ", "")
if "saga" in title.lower(): if "saga" in title.lower():
title = title.replace(" Saga Completa", "").replace(" saga completa", "").replace(" Saga", "").replace(" saga", "") title = title.replace(" Saga Completa", "").replace(" saga completa", "").replace(" Saga", "").replace(" saga", "")
title_subs += ["[Saga]"] title_subs += ["[Saga]"]
@@ -1001,20 +1023,21 @@ def listado_busqueda(item):
title_subs += ["[Miniserie]"] title_subs += ["[Miniserie]"]
#Limpiamos restos en título #Limpiamos restos en título
title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "") title = title.replace("Castellano", "").replace("castellano", "").replace("inglés", "").replace("ingles", "").replace("Inglés", "").replace("Ingles", "").replace("Ingl", "").replace("Engl", "").replace("Calidad", "").replace("de la Serie", "").replace("Spanish", "")
#Limpiamos cabeceras y colas del título #Limpiamos cabeceras y colas del título
title = re.sub(r'Descargar\s\w+\-\w+', '', title) title = re.sub(r'Descargar\s\w+\-\w+', '', title)
title = re.sub(r'\(COMPLE.*?\)', '', title) title = re.sub(r'\(COMPLE.*?\)', '', title)
title = title.replace("Ver online Serie", "").replace("Ver online ", "").replace("Descarga Serie HD ", "").replace("Descargar Serie HD ", "").replace("Descarga Serie ", "").replace("Descargar Serie ", "").replace("Ver en linea ", "").replace("Ver en linea", "").replace("en Full HD", "").replace("en hd ", "").replace("en HD ", "").replace("MicroHD", "").replace("HD ", "").replace("(Proper)", "").replace("HDTV", "").replace("RatDVD", "").replace("DVDRiP", "").replace("DVDRIP", "").replace("DVDRip", "").replace("DVDR", "").replace("DVD9", "").replace("DVD", "").replace("DVBRIP", "").replace("DVB", "").replace("LINE", "").replace("calidad", " ").replace("- ES ", "").replace("ES ", "").replace("COMPLETA", "").replace("Serie Animada", " ").replace("(", "-").replace(")", "-").replace(".", " ").strip()
title = title.replace("Descargar torrent ", "").replace("Descarga Gratis", "").replace("Descarga gratis", "").replace("Descargar Gratis", "").replace("Descargar gratis", "").replace("en gratis", "").replace("gratis gratis", "").replace("Gratisgratis", "").replace("Descargar Estreno ", "").replace("Descargar Estrenos ", "").replace("Pelicula en latino ", "").replace("Descargar Pelicula ", "").replace("Descargar pelicula ", "").replace("Descargar Peliculas ", "").replace("Descargar peliculas ", "").replace("Descargar Todas ", "").replace("Descargar Otras ", "").replace("Descargar ", "").replace("Descarga ", "").replace("Descargar ", "").replace("Decargar ", "").replace("Bajar ", "").replace("HDRIP ", "").replace("HDRiP ", "").replace("HDRip ", "").replace("RIP ", "").replace("Rip", "").replace("RiP", "").replace("XviD", "").replace("AC3 5.1", "").replace("AC3", "").replace("1080p ", "").replace("720p ", "").replace("DVD-Screener ", "").replace("TS-Screener ", "").replace("Screener ", "").replace("BdRemux ", "").replace("BR ", "").replace("4K UHDrip", "").replace("BDremux", "").replace("FULL UHD4K", "").replace("4KULTRA", "").replace("FULLBluRay", "").replace("FullBluRay", "").replace("en BluRay", "").replace("BluRay en", "").replace("Bluray en", "").replace("BluRay", "").replace("Bonus Disc", "").replace("de Cine ", "").replace("TeleCine ", "").replace("latino", "").replace("Latino", "").replace("argentina", "").replace("Argentina", "").replace("++Sub", "").replace("+-+Sub", "").strip()
title = re.sub(r'\(\d{4}\)$', '', title) title = re.sub(r'\(\d{4}\)$', '', title)
if re.sub(r'\d{4}$', '', title).strip(): if re.sub(r'\d{4}$', '', title).strip():
title = re.sub(r'\d{4}$', '', title) title = re.sub(r'\d{4}$', '', title)
title = re.sub(r' \d+x\d+', '', title) title = re.sub(r'\d+x\d+', '', title)
title = re.sub(r' x\d+', '', title) title = re.sub(r'x\d+', '', title).strip()
title = title.replace("Ver online ", "").replace("Descarga Serie HD ", "").replace("Descargar Serie HD ", "").replace("Descarga Serie ", "").replace("Descargar Serie ", "").replace("Ver en linea ", "").replace("Ver en linea", "").replace("en Full HD", "").replace("en hd ", "").replace("en HD ", "").replace("HD ", "").replace("(Proper)", "").replace("RatDVD", "").replace("DVDRiP", "").replace("DVDRIP", "").replace("DVDRip", "").replace("DVDR", "").replace("DVD9", "").replace("DVD", "").replace("DVBRIP", "").replace("DVB", "").replace("LINE", "").replace("calidad", " ").replace("- ES ", "").replace("ES ", "").replace("COMPLETA", "").replace("(", "-").replace(")", "-").replace(".", " ").strip()
title = title.replace("Descargar torrent ", "").replace("Descarga Gratis", "").replace("Descarga gratis", "").replace("Descargar Gratis", "").replace("Descargar gratis", "").replace("en gratis", "").replace("gratis gratis", "").replace("Gratisgratis", "").replace("Descargar Estreno ", "").replace("Descargar Estrenos ", "").replace("Pelicula en latino ", "").replace("Descargar Pelicula ", "").replace("Descargar pelicula ", "").replace("Descargar Peliculas ", "").replace("Descargar peliculas ", "").replace("Descargar Todas ", "").replace("Descargar Otras ", "").replace("Descargar ", "").replace("Descarga ", "").replace("Descargar ", "").replace("Decargar ", "").replace("Bajar ", "").replace("HDRIP ", "").replace("HDRiP ", "").replace("HDRip ", "").replace("RIP ", "").replace("Rip", "").replace("RiP", "").replace("XviD", "").replace("AC3 5.1", "").replace("AC3", "").replace("1080p ", "").replace("720p ", "").replace("DVD-Screener ", "").replace("TS-Screener ", "").replace("Screener ", "").replace("BdRemux ", "").replace("BR ", "").replace("4KULTRA", "").replace("FULLBluRay", "").replace("FullBluRay", "").replace("en BluRay", "").replace("BluRay en", "").replace("Bluray en", "").replace("BluRay", "").replace("Bonus Disc", "").replace("de Cine ", "").replace("TeleCine ", "").replace("latino", "").replace("Latino", "").replace("argentina", "").replace("Argentina", "").replace("++Sub", "").replace("+-+Sub", "").strip()
if "pelisyseries.com" in host and item_local.contentType == "tvshow": if "pelisyseries.com" in host and item_local.contentType == "tvshow":
titulo = '' titulo = ''
@@ -1061,7 +1084,7 @@ def listado_busqueda(item):
#Limpieza final del título y guardado en las variables según su tipo de contenido #Limpieza final del título y guardado en las variables según su tipo de contenido
item_local.title = title item_local.title = title
item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título item_local.from_title = title #Guardamos esta etiqueta para posible desambiguación de título
if item_local.contentType == "movie": if item_local.contentType == "movie":
item_local.contentTitle = title item_local.contentTitle = title
size = scrapedsize.replace(".", ",") size = scrapedsize.replace(".", ",")
@@ -1135,18 +1158,20 @@ def listado_busqueda(item):
else: else:
item_local.url = url_tvshow #Cambiamos url de episodio por el de serie item_local.url = url_tvshow #Cambiamos url de episodio por el de serie
else: else:
item_local.url = url_id #Cambiamos url de episodio por el de serie item_local.url = url_id #Cambiamos url de episodio por el de serie
#logger.debug("url: " + item_local.url + " / title o/n: " + item_local.title + " / " + real_title_mps + " / calidad_mps : " + calidad_mps + " / contentType : " + item_local.contentType) #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.replace('-', ' ').title().strip() #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 item_local.contentSerieName = item_local.title
#Agrega el item local a la lista itemlist #Agrega el item local a la lista itemlist
itemlist.append(item_local.clone()) itemlist.append(item_local.clone())
#if not item.category_new: #Si este campo no existe es que viene de la primera pasada de una búsqueda global #logger.debug(item_local)
# 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 #Pasamos a TMDB la lista completa Itemlist
tmdb.set_infoLabels(itemlist, __modo_grafico__) tmdb.set_infoLabels(itemlist, __modo_grafico__)
@@ -1172,7 +1197,7 @@ def findvideos(item):
item.channel_host = host item.channel_host = host
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize() item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
verify_fo = True #Verificamos si el clone a usar está activo verify_fo = True #Verificamos si el clone a usar está activo
item, data = generictools.fail_over_newpct1(item, verify_fo) item, data = generictools.fail_over_newpct1(item, verify_fo)
# Cualquiera de las tres opciones son válidas # Cualquiera de las tres opciones son válidas
@@ -1185,14 +1210,14 @@ def findvideos(item):
#Inicializamos las variables por si hay un error en medio del proceso #Inicializamos las variables por si hay un error en medio del proceso
channel_exclude = [] channel_exclude = []
ver_enlaces = [] ver_enlaces = []
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?" verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?" verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
#Leemos las opciones de permitir Servidores para Ver Online y Descargas #Leemos las opciones de permitir Servidores para Ver Online y Descargas
#Cargamos en .json del canal para ver las listas de valores en settings #Cargamos en .json del canal para ver las listas de valores en settings
@@ -1207,16 +1232,16 @@ def findvideos(item):
#Primer loop para enlaces de Ver Online. #Primer loop para enlaces de Ver Online.
#Carga la variable de ver #Carga la variable de ver
ver_enlaces_veronline = int(config.get_setting("clonenewpct1_ver_enlaces_veronline", item.channel)) ver_enlaces_veronline = int(config.get_setting("clonenewpct1_ver_enlaces_veronline", item.channel))
if ver_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0 if ver_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_veronline = -1 ver_enlaces_veronline = -1
if ver_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista if ver_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_veronline = int(ver_enlaces[ver_enlaces_veronline]) ver_enlaces_veronline = int(ver_enlaces[ver_enlaces_veronline])
#Carga la variable de verificar #Carga la variable de verificar
verificar_enlaces_veronline = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline", item.channel)) verificar_enlaces_veronline = int(config.get_setting("clonenewpct1_verificar_enlaces_veronline", item.channel))
if verificar_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0 if verificar_enlaces_veronline == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_veronline = -1 verificar_enlaces_veronline = -1
if verificar_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista if verificar_enlaces_veronline > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_veronline = int(ver_enlaces[verificar_enlaces_veronline]) verificar_enlaces_veronline = int(ver_enlaces[verificar_enlaces_veronline])
#Carga la variable de contar sólo los servidores verificados #Carga la variable de contar sólo los servidores verificados
@@ -1224,26 +1249,26 @@ def findvideos(item):
#Carga la variable de lista de servidores excluidos #Carga la variable de lista de servidores excluidos
x = 1 x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_veronline" % x, item.channel)) valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_veronline" % x, item.channel))
valor = int(valor) valor = int(valor)
if valor > 0: #Evitamos "No" if valor > 0: #Evitamos "No"
excluir_enlaces_veronline += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista excluir_enlaces_veronline += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1 x += 1
#Segundo loop para enlaces de Descargar. #Segundo loop para enlaces de Descargar.
#Carga la variable de ver #Carga la variable de ver
ver_enlaces_descargas = int(config.get_setting("clonenewpct1_ver_enlaces_descargas", item.channel)) ver_enlaces_descargas = int(config.get_setting("clonenewpct1_ver_enlaces_descargas", item.channel))
if ver_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0 if ver_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
ver_enlaces_descargas = -1 ver_enlaces_descargas = -1
if ver_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista if ver_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
ver_enlaces_descargas = int(ver_enlaces[ver_enlaces_descargas]) ver_enlaces_descargas = int(ver_enlaces[ver_enlaces_descargas])
#Carga la variable de verificar #Carga la variable de verificar
verificar_enlaces_descargas = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas", item.channel)) verificar_enlaces_descargas = int(config.get_setting("clonenewpct1_verificar_enlaces_descargas", item.channel))
if verificar_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0 if verificar_enlaces_descargas == 1: #a "Todos" le damos valor -1. Para "No" dejamos 0
verificar_enlaces_descargas = -1 verificar_enlaces_descargas = -1
if verificar_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista if verificar_enlaces_descargas > 1: #para los demás valores, tomamos los de la lista
verificar_enlaces_descargas = int(ver_enlaces[verificar_enlaces_descargas]) verificar_enlaces_descargas = int(ver_enlaces[verificar_enlaces_descargas])
#Carga la variable de contar sólo los servidores verificados #Carga la variable de contar sólo los servidores verificados
@@ -1251,14 +1276,14 @@ def findvideos(item):
#Carga la variable de lista de servidores excluidos #Carga la variable de lista de servidores excluidos
x = 1 x = 1
for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos for x in range(1, max_excl+1): #recorremos todas las opciones de canales exluidos
valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_descargas" % x, item.channel)) valor = str(config.get_setting("clonenewpct1_excluir%s_enlaces_descargas" % x, item.channel))
valor = int(valor) valor = int(valor)
if valor > 0: #Evitamos "No" if valor > 0: #Evitamos "No"
excluir_enlaces_descargas += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista excluir_enlaces_descargas += [channel_exclude[valor]] #Añadimos el nombre de servidor excluido a la lista
x += 1 x += 1
except Exception, ex: #En caso de error, lo mostramos y reseteamos todas las variables except Exception, ex: #En caso de error, lo mostramos y reseteamos todas las variables
logger.error("Error en la lectura de parámentros del .json del canal: " + item.channel + " \n%s" % ex) logger.error("Error en la lectura de parámentros del .json del canal: " + item.channel + " \n%s" % ex)
#Mostrar los errores #Mostrar los errores
logger.error(ver_enlaces_veronline) logger.error(ver_enlaces_veronline)
@@ -1270,14 +1295,14 @@ def findvideos(item):
logger.error(verificar_enlaces_descargas_validos) logger.error(verificar_enlaces_descargas_validos)
logger.error(excluir_enlaces_descargas) logger.error(excluir_enlaces_descargas)
#Resetear las variables a sus valores por defecto #Resetear las variables a sus valores por defecto
ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online ver_enlaces_veronline = -1 #Ver todos los enlaces Ver Online
verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online verificar_enlaces_veronline = -1 #Verificar todos los enlaces Ver Online
verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?" verificar_enlaces_veronline_validos = True #"¿Contar sólo enlaces 'verificados' en Ver Online?"
excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online excluir_enlaces_veronline = [] #Lista vacía de servidores excluidos en Ver Online
ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar ver_enlaces_descargas = 0 #Ver todos los enlaces Descargar
verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar verificar_enlaces_descargas = -1 #Verificar todos los enlaces Descargar
verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?" verificar_enlaces_descargas_validos = True #"¿Contar sólo enlaces 'verificados' en Descargar?"
excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar excluir_enlaces_descargas = [] #Lista vacía de servidores excluidos en Descargar
# Descarga la página # Descarga la página
data = '' data = ''
@@ -1286,16 +1311,18 @@ def findvideos(item):
data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures") data = data.replace("$!", "#!").replace("'", "\"").replace("ñ", "ñ").replace("//pictures", "/pictures")
url_servidores = item.url url_servidores = item.url
category_servidores = item.category category_servidores = item.category
data_servidores = data #salvamos data para verificar servidores, si es necesario data_servidores = data #salvamos data para verificar servidores, si es necesario
except: except:
pass pass
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not scrapertools.find_single_match(data, patron):
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
#Verificamos si se ha cargado una página, y si además tiene la estructura correcta #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): if not data or not scrapertools.find_single_match(data, patron):
item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada item = generictools.web_intervenida(item, data) #Verificamos que no haya sido clausurada
if item.intervencion: #Sí ha sido clausurada judicialmente if item.intervencion: #Sí ha sido clausurada judicialmente
item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error item, itemlist = generictools.post_tmdb_findvideos(item, itemlist) #Llamamos al método para el pintado del error
return itemlist #Salimos return itemlist #Salimos
logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data) logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
@@ -1315,8 +1342,8 @@ def findvideos(item):
enlaces_ver = re.compile(patron, re.DOTALL).findall(data_servidores) enlaces_ver = re.compile(patron, re.DOTALL).findall(data_servidores)
enlaces_descargar = enlaces_ver enlaces_descargar = enlaces_ver
for logo, servidor, idioma, calidad, enlace, title in enlaces_ver: #buscamos enlaces de servidores de ver-online for logo, servidor, idioma, calidad, enlace, title in enlaces_ver: #buscamos enlaces de servidores de ver-online
if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque
break break
if "ver" in title.lower(): if "ver" in title.lower():
cnt_servidores += 1 cnt_servidores += 1
@@ -1328,7 +1355,7 @@ def findvideos(item):
if not data_servidores: #Si no ha logrado encontrar nada nos vamos if not data_servidores: #Si no ha logrado encontrar nada nos vamos
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: FINDVIDEOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: FINDVIDEOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos
data = data_servidores #restauramos los datos data = data_servidores #restauramos los datos
@@ -1337,6 +1364,8 @@ def findvideos(item):
#Añadimos el tamaño para todos #Añadimos el tamaño para todos
size = scrapertools.find_single_match(data, '<div class="entry-left".*?><a href=".*?span class=.*?>Size:<\/strong>?\s(\d+?\.?\d*?\s\w[b|B])<\/span>') size = scrapertools.find_single_match(data, '<div class="entry-left".*?><a href=".*?span class=.*?>Size:<\/strong>?\s(\d+?\.?\d*?\s\w[b|B])<\/span>')
if not size: #Para planetatorrent
size = scrapertools.find_single_match(data, '<div class="fichas-box"><div class="entry-right"><div style="[^"]+"><span class="[^"]+"><strong>Size:<\/strong>?\s(\d+?\.?\d*?\s\w[b|B])<\/span>')
size = size.replace(".", ",") #sustituimos . por , porque Unify lo borra size = size.replace(".", ",") #sustituimos . por , porque Unify lo borra
if not size: if not size:
size = scrapertools.find_single_match(item.quality, '\s\[(\d+,?\d*?\s\w[b|B])\]') size = scrapertools.find_single_match(item.quality, '\s\[(\d+,?\d*?\s\w[b|B])\]')
@@ -1354,10 +1383,12 @@ def findvideos(item):
# obtenemos la url torrent # obtenemos la url torrent
patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent patron = 'class="btn-torrent">.*?window.location.href = "(.*?)";' #Patron para .torrent
if not scrapertools.find_single_match(data, patron):
patron = '<a href="([^"]+)"\s?title="[^"]+"\s?class="btn-torrent"' #Patron para .torrent (planetatorrent)
item_local.url = scrapertools.find_single_match(data, patron) item_local.url = scrapertools.find_single_match(data, patron)
if not item_local.url: #error if not item_local.url: #error
logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data) logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron + " / DATA: " + data)
item_local.url = item_local.url.replace(" ", "%20") #sustituimos espacios por %20, por si acaso item_local.url = item_local.url.replace(" ", "%20") #sustituimos espacios por %20, por si acaso
#logger.debug("Patron: " + patron + " url: " + item_local.url) #logger.debug("Patron: " + patron + " url: " + item_local.url)
#logger.debug(data) #logger.debug(data)
@@ -1367,7 +1398,7 @@ def findvideos(item):
quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título quality = '%s [%s]' % (item_local.quality, size) #Agregamos size al final del título
else: else:
quality = item_local.quality quality = item_local.quality
item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (quality, str(item_local.language)) #Preparamos título de Torrent
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos etiquetas vacías item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos etiquetas vacías
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos colores vacíos item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip() #Quitamos colores vacíos
item_local.alive = "??" #Calidad del link sin verificar item_local.alive = "??" #Calidad del link sin verificar
@@ -1400,15 +1431,15 @@ def findvideos(item):
cnt_enl_ver = 1 cnt_enl_ver = 1
cnt_enl_verif = 1 cnt_enl_verif = 1
for logo, servidor, idioma, calidad, enlace, title in enlaces_ver: for logo, servidor, idioma, calidad, enlace, title in enlaces_ver:
if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque if ver_enlaces_veronline == 0: #Si no se quiere Ver Online, se sale del bloque
break break
if "ver" in title.lower(): if "ver" in title.lower():
servidor = servidor.replace("streamin", "streaminto") servidor = servidor.replace("streamin", "streaminto")
if servidor.capitalize() in excluir_enlaces_veronline: #Servidor excluido, pasamos al siguiente if servidor.capitalize() in excluir_enlaces_veronline: #Servidor excluido, pasamos al siguiente
continue continue
mostrar_server = True mostrar_server = True
if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran
mostrar_server = servertools.is_server_enabled(servidor) mostrar_server = servertools.is_server_enabled(servidor)
#logger.debug("VER: url: " + enlace + " / title: " + title + " / servidor: " + servidor + " / idioma: " + idioma) #logger.debug("VER: url: " + enlace + " / title: " + title + " / servidor: " + servidor + " / idioma: " + idioma)
@@ -1421,7 +1452,7 @@ def findvideos(item):
if verificar_enlaces_veronline == 0: if verificar_enlaces_veronline == 0:
cnt_enl_ver += 1 cnt_enl_ver += 1
else: else:
break #Si se ha agotado el contador de verificación, se sale de Ver Online break #Si se ha agotado el contador de verificación, se sale de Ver Online
if devuelve: #Hay link if devuelve: #Hay link
enlace = devuelve[0][1] #Se guarda el link enlace = devuelve[0][1] #Se guarda el link
@@ -1430,15 +1461,15 @@ def findvideos(item):
if cnt_enl_verif <= verificar_enlaces_veronline or verificar_enlaces_veronline == -1: #contador? if cnt_enl_verif <= verificar_enlaces_veronline or verificar_enlaces_veronline == -1: #contador?
#Llama a la subfunción de check_list_links(itemlist) para cada link de servidor #Llama a la subfunción de check_list_links(itemlist) para cada link de servidor
item_local.alive = servertools.check_video_link(enlace, servidor, timeout=timeout) #activo el link ? item_local.alive = servertools.check_video_link(enlace, servidor, timeout=timeout) #activo el link ?
if verificar_enlaces_veronline_validos: #Los links tienen que ser válidos para contarlos? if verificar_enlaces_veronline_validos: #Los links tienen que ser válidos para contarlos?
if item_local.alive == "Ok": #Sí if item_local.alive == "Ok": #Sí
cnt_enl_verif += 1 #Movemos los contadores cnt_enl_verif += 1 #Movemos los contadores
cnt_enl_ver += 1 #Movemos los contadores cnt_enl_ver += 1 #Movemos los contadores
else: #Si no es necesario que sean links válidos, sumamos else: #Si no es necesario que sean links válidos, sumamos
cnt_enl_verif += 1 #Movemos los contadores cnt_enl_verif += 1 #Movemos los contadores
cnt_enl_ver += 1 #Movemos los contadores cnt_enl_ver += 1 #Movemos los contadores
else: else:
break #Si se ha agotado el contador de verificación, se sale de Ver Online break #Si se ha agotado el contador de verificación, se sale de Ver Online
#Si el link no está activo se ignora #Si el link no está activo se ignora
if "??" in item_local.alive: #dudoso if "??" in item_local.alive: #dudoso
@@ -1458,6 +1489,7 @@ def findvideos(item):
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip()
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip() item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title).strip()
itemlist.append(item_local.clone()) itemlist.append(item_local.clone())
except: except:
logger.error('ERROR al procesar enlaces VER DIRECTOS: ' + servidor + ' / ' + enlace) logger.error('ERROR al procesar enlaces VER DIRECTOS: ' + servidor + ' / ' + enlace)
@@ -1480,7 +1512,7 @@ def findvideos(item):
if "Ver" not in title: if "Ver" not in title:
servidor = servidor.replace("uploaded", "uploadedto") servidor = servidor.replace("uploaded", "uploadedto")
partes = enlace.split(" ") #Partimos el enlace en cada link de las partes partes = enlace.split(" ") #Partimos el enlace en cada link de las partes
title = "Descarga" #Usamos la palabra reservada de Unify para que no formatee el título title = "Descarga" #Usamos la palabra reservada de Unify para que no formatee el título
if servidor.capitalize() in excluir_enlaces_descargas: #Servidor excluido, pasamos al siguiente if servidor.capitalize() in excluir_enlaces_descargas: #Servidor excluido, pasamos al siguiente
continue continue
@@ -1490,10 +1522,12 @@ def findvideos(item):
#Recorremos cada una de las partes. Vemos si el primer link está activo. Si no lo está ignoramos todo el enlace #Recorremos cada una de las partes. Vemos si el primer link está activo. Si no lo está ignoramos todo el enlace
p = 1 p = 1
for enlace in partes: for enlace in partes:
if not item.unify: #Si titles Inteligentes NO seleccionados: if not item.unify: #Si titles Inteligentes NO seleccionados:
parte_title = "[COLOR yellow][%s][/COLOR] %s (%s/%s) [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]" % (servidor.capitalize(), title, p, len(partes), item_local.quality, str(item_local.language)) parte_title = "[COLOR yellow][%s][/COLOR] %s (%s/%s) [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]" % (servidor.capitalize(), title, p, len(partes), item_local.quality, str(item_local.language))
else: else:
parte_title = "[COLOR yellow]%s-[/COLOR] %s %s/%s [COLOR limegreen]-%s[/COLOR] [COLOR red]-%s[/COLOR]" % (servidor.capitalize(), title, p, len(partes), item_local.quality, str(item_local.language)) title = title.replace('Descarga', 'Descarg.')
item_local.quality = '[/COLOR][COLOR white] %s (%s/%s) [/COLOR][COLOR limegreen][%s] ' % (title, p, len(partes), item.quality)
parte_title = "[COLOR yellow][%s]%s[/COLOR] [COLOR red][%s][/COLOR]" % (servidor.capitalize(), item_local.quality, str(item_local.language))
p += 1 p += 1
mostrar_server = True mostrar_server = True
if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran if config.get_setting("hidepremium"): #Si no se aceptan servidore premium, se ignoran
@@ -1508,7 +1542,7 @@ def findvideos(item):
cnt_enl_ver += 1 cnt_enl_ver += 1
else: else:
ver_enlaces_descargas = 0 #FORZAR SALIR de DESCARGAS ver_enlaces_descargas = 0 #FORZAR SALIR de DESCARGAS
break #Si se ha agotado el contador de verificación, se sale de "Enlace" break #Si se ha agotado el contador de verificación, se sale de "Enlace"
if devuelve: if devuelve:
enlace = devuelve[0][1] enlace = devuelve[0][1]
@@ -1524,12 +1558,12 @@ def findvideos(item):
if item_local.alive == "Ok": #Sí if item_local.alive == "Ok": #Sí
cnt_enl_verif += 1 #Movemos los contadores cnt_enl_verif += 1 #Movemos los contadores
cnt_enl_ver += 1 #Movemos los contadores cnt_enl_ver += 1 #Movemos los contadores
else: #Si no es necesario que sean links válidos, sumamos else: #Si no es necesario que sean links válidos, sumamos
cnt_enl_verif += 1 #Movemos los contadores cnt_enl_verif += 1 #Movemos los contadores
cnt_enl_ver += 1 #Movemos los contadores cnt_enl_ver += 1 #Movemos los contadores
else: else:
ver_enlaces_descargas = 0 #FORZAR SALIR de DESCARGAS ver_enlaces_descargas = 0 #FORZAR SALIR de DESCARGAS
break #Si se ha agotado el contador de verificación, se sale de "Enlace" break #Si se ha agotado el contador de verificación, se sale de "Enlace"
if "??" in item_local.alive: #dudoso if "??" in item_local.alive: #dudoso
if not item.unify: #Si titles Inteligentes NO seleccionados: if not item.unify: #Si titles Inteligentes NO seleccionados:
@@ -1552,6 +1586,7 @@ def findvideos(item):
item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip() item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title).strip()
item_local.title = re.sub(r'\[COLOR \w+\]-\[\/COLOR\]', '', item_local.title).strip() item_local.title = re.sub(r'\[COLOR \w+\]-\[\/COLOR\]', '', item_local.title).strip()
itemlist.append(item_local.clone()) itemlist.append(item_local.clone())
except: except:
logger.error('ERROR al procesar enlaces DESCARGAR DIRECTOS: ' + servidor + ' / ' + enlace) logger.error('ERROR al procesar enlaces DESCARGAR DIRECTOS: ' + servidor + ' / ' + enlace)
@@ -1599,7 +1634,7 @@ def episodios(item):
pass pass
modo_ultima_temp_alt = modo_ultima_temp 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 modo_ultima_temp_alt = False
max_temp = 1 max_temp = 1
@@ -1644,7 +1679,7 @@ def episodios(item):
#Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el vídeo #Si no hay datos consistentes, llamamos al método de fail_over para que encuentre un canal que esté activo y pueda gestionar el vídeo
item, data = generictools.fail_over_newpct1(item, patron, pattern) item, data = generictools.fail_over_newpct1(item, patron, pattern)
if not data: #No se ha encontrado ningún canal activo para este vídeo if not data: #No se ha encontrado ningún canal activo para este vídeo
itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo')) itemlist.append(item.clone(action='', title="[COLOR yellow]" + item.channel.capitalize() + '[/COLOR]: Ningún canal NewPct1 activo'))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 01: EPISODIOS:. La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
return itemlist return itemlist
@@ -1686,13 +1721,14 @@ def episodios(item):
data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8") data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
data = data.replace("chapters", "buscar-list") #Compatibilidad con mispelisy.series.com data = data.replace("chapters", "buscar-list") #Compatibilidad con mispelisy.series.com
pattern = '<ul class="%s">(.*?)</ul>' % "buscar-list" # item.pattern pattern = '<ul class="%s">(.*?)</ul>' % "buscar-list" # item.pattern
data = scrapertools.get_match(data, pattern) data_sector = scrapertools.get_match(data, pattern)
if not data: if not data_sector:
raise raise
data = data_sector
except: except:
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / " + str(list_pages) + " / DATA: " + str(data)) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / " + str(list_pages) + " / DATA: " + str(data))
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
if "pelisyseries.com" in item.url: if "pelisyseries.com" in item.url:
pattern = '<li[^>]*><div class.*?src="(?P<thumb>[^"]+)?".*?<a class.*?href="(?P<url>[^"]+).*?<h3[^>]+>(?P<info>.*?)?<\/h3>.*?<\/li>' pattern = '<li[^>]*><div class.*?src="(?P<thumb>[^"]+)?".*?<a class.*?href="(?P<url>[^"]+).*?<h3[^>]+>(?P<info>.*?)?<\/h3>.*?<\/li>'
@@ -1702,7 +1738,7 @@ def episodios(item):
if not matches: #error if not matches: #error
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / DATA: " + data) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / DATA: " + data)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
#logger.debug("patron: " + pattern) #logger.debug("patron: " + pattern)
#logger.debug(matches) #logger.debug(matches)
@@ -1736,7 +1772,7 @@ def episodios(item):
logger.debug(item_local.url) logger.debug(item_local.url)
info = '><strong>%sTemporada %s Capitulo 0</strong> - <span >Español Castellano</span> Calidad <span >[%s]</span>' % (item_local.contentSerieName, season, item_local.quality) info = '><strong>%sTemporada %s Capitulo 0</strong> - <span >Español Castellano</span> Calidad <span >[%s]</span>' % (item_local.contentSerieName, season, item_local.quality)
else: # old style. Se intenta buscar un patrón que encaje con los diversos formatos antiguos. Si no, se crea else: # old style. Se intenta buscar un patrón que encaje con los diversos formatos antiguos. Si no, se crea
pattern = '\[(?P<quality>.*?)\]\[Cap.(?P<season>\d).*?(?P<episode>\d{2})(?:_(?P<season2>\d+)(?P<episode2>\d{2}))?\].*?(?P<lang>.*)?' #Patrón básico por defecto pattern = '\[(?P<quality>.*?)\]\[Cap.(?P<season>\d).*?(?P<episode>\d{2})(?:_(?P<season2>\d+)(?P<episode2>\d{2}))?\].*?(?P<lang>.*)?' #Patrón básico por defecto
if scrapertools.find_single_match(info, '\[\d{3}\]'): if scrapertools.find_single_match(info, '\[\d{3}\]'):
@@ -1774,12 +1810,13 @@ def episodios(item):
r = re.compile(pattern) r = re.compile(pattern)
match = [m.groupdict() for m in r.finditer(info)][0] match = [m.groupdict() for m in r.finditer(info)][0]
if not match: #error if not match: #error
logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / DATA: " + info) logger.error("ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web " + " / PATRON: " + pattern + " / DATA: " + info)
itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log')) itemlist.append(item.clone(action='', title=item.category + ': ERROR 02: EPISODIOS: Ha cambiado la estructura de la Web. Reportar el error con el log'))
return itemlist #si no hay más datos, algo no funciona, pintamos lo que tenemos break #si no hay más datos, algo no funciona, pintamos lo que tenemos
if match['season'] is None: match['season'] = season #Si no se encuentran valores, pero poner lo básico #Si no se encuentran valores, pero poner lo básico
if match['season'] is None or match['season'] == "0" or not match['season']: match['season'] = season
if match['episode'] is None: match['episode'] = "0" if match['episode'] is None: match['episode'] = "0"
try: try:
match['season'] = int(match['season']) match['season'] = int(match['season'])
@@ -1814,11 +1851,11 @@ def episodios(item):
item_local.contentEpisodeNumber = match['episode'] item_local.contentEpisodeNumber = match['episode']
if match["episode2"]: #Hay episodio dos? es una entrada múltiple? if match["episode2"]: #Hay episodio dos? es una entrada múltiple?
item_local.title = "%sx%s al %s -" % (str(match["season"]), str(match["episode"]).zfill(2), str(match["episode2"]).zfill(2)) #Creamos un título con el rango de episodios item_local.title = "%sx%s al %s -" % (str(match["season"]), str(match["episode"]).zfill(2), str(match["episode2"]).zfill(2)) #Creamos un título con el rango de episodios
else: #Si es un solo episodio, se formatea ya else: #Si es un solo episodio, se formatea ya
item_local.title = "%sx%s -" % (match["season"], str(match["episode"]).zfill(2)) item_local.title = "%sx%s -" % (match["season"], str(match["episode"]).zfill(2))
if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca if modo_ultima_temp_alt and item.library_playcounts: #Si solo se actualiza la última temporada de Videoteca
if item_local.contentSeason < max_temp: if item_local.contentSeason < max_temp:
list_pages = [] #Sale del bucle de leer páginas list_pages = [] #Sale del bucle de leer páginas
break #Sale del bucle actual del FOR de episodios por página break #Sale del bucle actual del FOR de episodios por página
@@ -1829,6 +1866,7 @@ def episodios(item):
if item_local.contentSeason > season_display: if item_local.contentSeason > season_display:
continue continue
elif item_local.contentSeason < season_display: elif item_local.contentSeason < season_display:
list_pages = [] #Sale del bucle de leer páginas
break break
if item_local.active: if item_local.active:
@@ -1851,7 +1889,7 @@ def episodios(item):
if len(itemlist) > 1: if len(itemlist) > 1:
itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) #clasificamos
if item.season_colapse and not item.add_videolibrary: #Si viene de listado, mostramos solo Temporadas if item.season_colapse and not item.add_videolibrary: #Si viene de listado, mostramos solo Temporadas
item, itemlist = generictools.post_tmdb_seasons(item, itemlist) item, itemlist = generictools.post_tmdb_seasons(item, itemlist)
if not item.season_colapse: #Si no es pantalla de Temporadas, pintamos todo if not item.season_colapse: #Si no es pantalla de Temporadas, pintamos todo
+160 -143
View File
@@ -182,9 +182,9 @@ def update_title(item):
item.title = item.title.replace("[" + str(rating_old) + "]", "[" + str(rating_new) + "]") item.title = item.title.replace("[" + str(rating_old) + "]", "[" + str(rating_new) + "]")
except: except:
pass pass
if item.wanted: #Actualizamos Wanted, si existe if item.wanted: #Actualizamos Wanted, si existe
item.wanted = item.contentTitle item.wanted = item.contentTitle
if new_item.contentSeason: #Restauramos el núm. de Temporada después de TMDB if new_item.contentSeason: #Restauramos el núm. de Temporada después de TMDB
item.contentSeason = new_item.contentSeason item.contentSeason = new_item.contentSeason
if item.from_update: if item.from_update:
@@ -194,12 +194,12 @@ def update_title(item):
#Para evitar el "efecto memoria" de TMDB, se le llama con un título ficticio para que resetee los buffers #Para evitar el "efecto memoria" de TMDB, se le llama con un título ficticio para que resetee los buffers
if item.contentSerieName: if item.contentSerieName:
new_item.infoLabels['tmdb_id'] = '289' #una serie no ambigua new_item.infoLabels['tmdb_id'] = '289' #una serie no ambigua
else: else:
new_item.infoLabels['tmdb_id'] = '111' #una peli no ambigua new_item.infoLabels['tmdb_id'] = '111' #una peli no ambigua
new_item.infoLabels['year'] = '-' new_item.infoLabels['year'] = '-'
if new_item.contentSeason: if new_item.contentSeason:
del new_item.infoLabels['season'] #Funciona mal con num. de Temporada del new_item.infoLabels['season'] #Funciona mal con num. de Temporada
scraper_return = scraper.find_and_set_infoLabels(new_item) scraper_return = scraper.find_and_set_infoLabels(new_item)
#logger.debug(item) #logger.debug(item)
@@ -268,7 +268,7 @@ def post_tmdb_listado(item, itemlist):
title_add = ' ' title_add = ' '
if item_local.title_subs: if item_local.title_subs:
for title_subs in item_local.title_subs: for title_subs in item_local.title_subs:
if "audio" in title_subs.lower(): #se restaura info de Audio if "audio" in title_subs.lower(): #se restaura info de Audio
title_add += scrapertools.find_single_match(title_subs, r'[a|A]udio (.*?)') title_add += scrapertools.find_single_match(title_subs, r'[a|A]udio (.*?)')
continue continue
if scrapertools.find_single_match(title_subs, r'(\d{4})'): #Se restaura el año, s no lo ha dado TMDB if scrapertools.find_single_match(title_subs, r'(\d{4})'): #Se restaura el año, s no lo ha dado TMDB
@@ -277,7 +277,7 @@ def post_tmdb_listado(item, itemlist):
continue continue
title_add = title_add.rstrip() 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 = [] item_local.title_subs = []
del item_local.title_subs del item_local.title_subs
@@ -299,15 +299,15 @@ def post_tmdb_listado(item, itemlist):
# Si TMDB no ha encontrado nada y hemos usado el año de la web, lo intentamos sin año # Si TMDB no ha encontrado nada y hemos usado el año de la web, lo intentamos sin año
if not item_local.infoLabels['tmdb_id']: if not item_local.infoLabels['tmdb_id']:
if item_local.infoLabels['year']: #lo intentamos de nuevo solo si había año, puede que erroneo if item_local.infoLabels['year']: #lo intentamos de nuevo solo si había año, puede que erroneo
year = item_local.infoLabels['year'] #salvamos el año por si no tiene éxito la nueva búsqueda year = item_local.infoLabels['year'] #salvamos el año por si no tiene éxito la nueva búsqueda
item_local.infoLabels['year'] = "-" #reseteo el año item_local.infoLabels['year'] = "-" #reseteo el año
try: try:
tmdb.set_infoLabels(item_local, True) #pasamos otra vez por TMDB tmdb.set_infoLabels(item_local, True) #pasamos otra vez por TMDB
except: except:
pass pass
if not item_local.infoLabels['tmdb_id']: #ha tenido éxito? if not item_local.infoLabels['tmdb_id']: #ha tenido éxito?
item_local.infoLabels['year'] = year #no, restauramos el año y lo dejamos ya item_local.infoLabels['year'] = year #no, restauramos el año y lo dejamos ya
# Para Episodios, tomo el año de exposición y no el de inicio de la serie # Para Episodios, tomo el año de exposición y no el de inicio de la serie
if item_local.infoLabels['aired']: if item_local.infoLabels['aired']:
@@ -322,22 +322,31 @@ def post_tmdb_listado(item, itemlist):
if item_local.contentType == 'season': if item_local.contentType == 'season':
item_local.title = item_local.from_title item_local.title = item_local.from_title
#Limpiamos calidad de títulos originales que se hayan podido colar
if item_local.infoLabels['originaltitle'].lower() in item_local.quality.lower():
item_local.quality = re.sub(item_local.infoLabels['originaltitle'], '', item_local.quality, flags=re.IGNORECASE)
# Preparamos el título para series, con los núm. de temporadas, si las hay # 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.contentType in ['season', 'tvshow', 'episode']:
if item_local.contentType == "episode": if item_local.contentType == "episode":
if "Temporada" in title: #Compatibilizamos "Temporada" con Unify
#Si no está el título del episodio, pero sí está en "title", lo rescatamos
if not item_local.infoLabels['episodio_titulo'] and item_local.infoLabels['title'].lower() != item_local.infoLabels['tvshowtitle'].lower():
item_local.infoLabels['episodio_titulo'] = item_local.infoLabels['title']
if "Temporada" in title: #Compatibilizamos "Temporada" con Unify
title = '%sx%s al 99 -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber)) title = '%sx%s al 99 -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber))
if " al " in title: #Si son episodios múltiples, ponemos nombre de serie if " al " in title: #Si son episodios múltiples, ponemos nombre de serie
if " al 99" in title.lower(): #Temporada completa. Buscamos num total de episodios if " al 99" in title.lower(): #Temporada completa. Buscamos num total de episodios
title = title.replace("99", str(item_local.infoLabels['temporada_num_episodios'])) title = title.replace("99", str(item_local.infoLabels['temporada_num_episodios']))
title = '%s %s' % (title, item_local.contentSerieName) title = '%s %s' % (title, item_local.contentSerieName)
item_local.infoLabels['episodio_titulo'] = '%s - %s [%s] [%s]' % (scrapertools.find_single_match(title, r'(al \d+)'), item_local.contentSerieName, item_local.infoLabels['year'], rating) item_local.infoLabels['episodio_titulo'] = '%s - %s [%s] [%s]' % (scrapertools.find_single_match(title, r'(al \d+)'), item_local.contentSerieName, item_local.infoLabels['year'], rating)
elif item_local.infoLabels['episodio_titulo']: elif item_local.infoLabels['episodio_titulo']:
title = '%s %s, %s' % (title, item_local.infoLabels['episodio_titulo'], item_local.contentSerieName) title = '%s %s, %s' % (title, item_local.infoLabels['episodio_titulo'], item_local.contentSerieName)
item_local.infoLabels['episodio_titulo'] = '%s- %s [%s] [%s]' % (item_local.infoLabels['episodio_titulo'], item_local.contentSerieName, item_local.infoLabels['year'], rating) 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 else: #Si no hay título de episodio, ponermos el nombre de la serie
if item_local.contentSerieName not in title: if item_local.contentSerieName not in title:
title = '%s %s' % (title, item_local.contentSerieName) title = '%s %s' % (title, item_local.contentSerieName)
item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.contentSerieName, item_local.infoLabels['year'], rating) item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.contentSerieName, item_local.infoLabels['year'], rating)
@@ -367,7 +376,7 @@ def post_tmdb_listado(item, itemlist):
title += " -Varios-" title += " -Varios-"
item_local.contentTitle += " -Varios-" item_local.contentTitle += " -Varios-"
title += title_add #Se añaden etiquetas adicionales, si las hay title += title_add #Se añaden etiquetas adicionales, si las hay
#Ahora maquillamos un poco los titulos dependiendo de si se han seleccionado títulos inteleigentes o no #Ahora maquillamos un poco los titulos dependiendo de si se han seleccionado títulos inteleigentes o no
if not config.get_setting("unify"): #Si Titulos Inteligentes NO seleccionados: if not config.get_setting("unify"): #Si Titulos Inteligentes NO seleccionados:
@@ -383,7 +392,7 @@ 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()
title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', title).strip() title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', title).strip()
if item.category_new == "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() title += ' -%s-' % scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
if item_local.contentType == "movie": if item_local.contentType == "movie":
item_local.contentTitle += ' -%s-' % scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize() item_local.contentTitle += ' -%s-' % scrapertools.find_single_match(item_local.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').capitalize()
@@ -465,18 +474,18 @@ def post_tmdb_seasons(item, itemlist):
# Primero creamos un título para TODAS las Temporadas # Primero creamos un título para TODAS las Temporadas
# Pasada por TMDB a Serie, para datos adicionales # Pasada por TMDB a Serie, para datos adicionales
try: try:
tmdb.set_infoLabels(item, True) #TMDB de cada Temp tmdb.set_infoLabels(item, True) #TMDB de cada Temp
except: except:
pass pass
item_season = item.clone() item_season = item.clone()
if item_season.season_colapse: #Quitamos el indicador de listado por Temporadas if item_season.season_colapse: #Quitamos el indicador de listado por Temporadas
del item_season.season_colapse del item_season.season_colapse
title = '** Todas las Temporadas' #Agregamos título de TODAS las Temporadas (modo tradicional) title = '** Todas las Temporadas' #Agregamos título de TODAS las Temporadas (modo tradicional)
if item_season.infoLabels['number_of_episodes']: #Ponemos el núm de episodios de la Serie if item_season.infoLabels['number_of_episodes']: #Ponemos el núm de episodios de la Serie
title += ' [%s epi]' % str(item_season.infoLabels['number_of_episodes']) title += ' [%s epi]' % str(item_season.infoLabels['number_of_episodes'])
rating = '' #Ponemos el rating, si es diferente del de la Serie rating = '' #Ponemos el rating, si es diferente del de la Serie
if item_season.infoLabels['rating'] and item_season.infoLabels['rating'] != 0.0: if item_season.infoLabels['rating'] and item_season.infoLabels['rating'] != 0.0:
try: try:
rating = float(item_season.infoLabels['rating']) rating = float(item_season.infoLabels['rating'])
@@ -486,9 +495,9 @@ def post_tmdb_seasons(item, itemlist):
if rating and rating == 0.0: if rating and rating == 0.0:
rating = '' rating = ''
if not config.get_setting("unify"): #Si Titulos Inteligentes NO seleccionados: if not config.get_setting("unify"): #Si Titulos Inteligentes NO seleccionados:
title = '%s [COLOR yellow][%s][/COLOR] [%s] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (title, str(item_season.infoLabels['year']), rating, item_season.quality, str(item_season.language)) title = '%s [COLOR yellow][%s][/COLOR] [%s] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (title, str(item_season.infoLabels['year']), rating, item_season.quality, str(item_season.language))
else: #Lo arreglamos un poco para Unify else: #Lo arreglamos un poco para Unify
title = title.replace('[', '-').replace(']', '-').replace('.', ',').strip() title = title.replace('[', '-').replace(']', '-').replace('.', ',').strip()
title = title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip() title = title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
@@ -539,7 +548,7 @@ def post_tmdb_seasons(item, itemlist):
#logger.debug(item_local) #logger.debug(item_local)
else: #Si hay más de una temporada se sigue, si no se devuelve el Itemlist original else: #Si hay más de una temporada se sigue, si no se devuelve el Itemlist original
if item.season_colapse: if item.season_colapse:
del item.season_colapse del item.season_colapse
return (item, itemlist) return (item, itemlist)
@@ -646,7 +655,7 @@ def post_tmdb_episodios(item, itemlist):
if item.from_channel: if item.from_channel:
del item.from_channel del item.from_channel
for item_local in itemlist: #Recorremos el Itemlist generado por el canal for item_local in itemlist: #Recorremos el Itemlist generado por el canal
if item_local.add_videolibrary: if item_local.add_videolibrary:
del item_local.add_videolibrary del item_local.add_videolibrary
if item_local.add_menu: if item_local.add_menu:
@@ -750,6 +759,14 @@ def post_tmdb_episodios(item, itemlist):
elif item_local.infoLabels['aired']: elif item_local.infoLabels['aired']:
item_local.infoLabels['year'] = scrapertools.find_single_match(str(item_local.infoLabels['aired']), r'\/(\d{4})') item_local.infoLabels['year'] = scrapertools.find_single_match(str(item_local.infoLabels['aired']), r'\/(\d{4})')
#Limpiamos calidad de títulos originales que se hayan podido colar
if item_local.infoLabels['originaltitle'].lower() in item_local.quality.lower():
item_local.quality = re.sub(item_local.infoLabels['originaltitle'], '', item_local.quality, flags=re.IGNORECASE)
#Si no está el título del episodio, pero sí está en "title", lo rescatamos
if not item_local.infoLabels['episodio_titulo'] and item_local.infoLabels['title'].lower() != item_local.infoLabels['tvshowtitle'].lower():
item_local.infoLabels['episodio_titulo'] = item_local.infoLabels['title']
#Preparamos el título para que sea compatible con Añadir Serie a Videoteca #Preparamos el título para que sea compatible con Añadir Serie a Videoteca
if "Temporada" in item_local.title: #Compatibilizamos "Temporada" con Unify if "Temporada" in item_local.title: #Compatibilizamos "Temporada" con Unify
item_local.title = '%sx%s al 99 -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber)) item_local.title = '%sx%s al 99 -' % (str(item_local.contentSeason), str(item_local.contentEpisodeNumber))
@@ -763,7 +780,7 @@ def post_tmdb_episodios(item, itemlist):
item_local.title = '%s %s' % (item_local.title, item_local.infoLabels['episodio_titulo']) item_local.title = '%s %s' % (item_local.title, item_local.infoLabels['episodio_titulo'])
item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.infoLabels['episodio_titulo'], item_local.infoLabels['year'], rating) item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.infoLabels['episodio_titulo'], item_local.infoLabels['year'], rating)
else: #Si no hay título de episodio, ponermos el nombre de la serie else: #Si no hay título de episodio, ponermos el nombre de la serie
item_local.title = '%s %s' % (item_local.title, item_local.contentSerieName) item_local.title = '%s %s' % (item_local.title, item_local.contentSerieName)
item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.contentSerieName, item_local.infoLabels['year'], rating) item_local.infoLabels['episodio_titulo'] = '%s [%s] [%s]' % (item_local.contentSerieName, item_local.infoLabels['year'], rating)
@@ -812,8 +829,8 @@ def post_tmdb_episodios(item, itemlist):
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)) 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))
#Borro num. Temporada si no viene de menú de Añadir a Videoteca y no está actualizando la Videoteca #Borro num. Temporada si no viene de menú de Añadir a Videoteca y no está actualizando la Videoteca
if not item.library_playcounts: #si no está actualizando la Videoteca if not item.library_playcounts: #si no está actualizando la Videoteca
if modo_serie_temp != '': #y puede cambiara a serie-temporada if modo_serie_temp != '': #y puede cambiara a serie-temporada
if item.contentSeason and not item.add_menu: if item.contentSeason and not item.add_menu:
del item.infoLabels['season'] #La decisión de ponerlo o no se toma en la zona de menús del item.infoLabels['season'] #La decisión de ponerlo o no se toma en la zona de menús
@@ -835,13 +852,13 @@ def post_tmdb_episodios(item, itemlist):
#Estamos en un canal que puede seleccionar entre gestionar Series completas o por Temporadas #Estamos en un canal que puede seleccionar entre gestionar Series completas o por Temporadas
#Tendrá una línea para Añadir la Serie completa y otra para Añadir sólo la Temporada actual #Tendrá una línea para Añadir la Serie completa y otra para Añadir sólo la Temporada actual
if item.action == 'get_seasons': #si es actualización desde videoteca, título estándar if item.action == 'get_seasons': #si es actualización desde videoteca, título estándar
#Si hay una nueva Temporada, se activa como la actual #Si hay una nueva Temporada, se activa como la actual
if item.library_urls[item.channel] != item.url and (item.contentType == "season" or modo_ultima_temp): if item.library_urls[item.channel] != item.url and (item.contentType == "season" or modo_ultima_temp):
item.library_urls[item.channel] = item.url #Se actualiza la url apuntando a la última Temporada item.library_urls[item.channel] = item.url #Se actualiza la url apuntando a la última Temporada
try: try:
from core import videolibrarytools #Se fuerza la actualización de la url en el .nfo from core import videolibrarytools #Se fuerza la actualización de la url en el .nfo
itemlist_fake = [] #Se crea un Itemlist vacio para actualizar solo el .nfo itemlist_fake = [] #Se crea un Itemlist vacio para actualizar solo el .nfo
videolibrarytools.save_tvshow(item, itemlist_fake) #Se actualiza el .nfo videolibrarytools.save_tvshow(item, itemlist_fake) #Se actualiza el .nfo
except: except:
logger.error("ERROR 08: EPISODIOS: No se ha podido actualizar la URL a la nueva Temporada") logger.error("ERROR 08: EPISODIOS: No se ha podido actualizar la URL a la nueva Temporada")
@@ -875,10 +892,10 @@ def post_tmdb_episodios(item, itemlist):
if len(itemlist_fo) > 0: if len(itemlist_fo) > 0:
itemlist = itemlist_fo + itemlist itemlist = itemlist_fo + itemlist
if item.add_videolibrary: #Estamos Añadiendo a la Videoteca. if item.add_videolibrary: #Estamos Añadiendo a la Videoteca.
del item.add_videolibrary #Borramos ya el indicador del item.add_videolibrary #Borramos ya el indicador
if item.add_menu: #Opción que avisa si se ha añadido a la Videoteca if item.add_menu: #Opción que avisa si se ha añadido a la Videoteca
del item.add_menu #desde la página de Episodios o desde Menú Contextual del item.add_menu #desde la página de Episodios o desde Menú Contextual
#logger.debug(item) #logger.debug(item)
@@ -917,7 +934,7 @@ def post_tmdb_findvideos(item, itemlist):
except: except:
item.unify = config.get_setting("unify") item.unify = config.get_setting("unify")
if item.contentSeason_save: #Restauramos el num. de Temporada if item.contentSeason_save: #Restauramos el num. de Temporada
item.contentSeason = item.contentSeason_save item.contentSeason = item.contentSeason_save
del item.contentSeason_save del item.contentSeason_save
@@ -932,7 +949,7 @@ def post_tmdb_findvideos(item, itemlist):
#elif (not item.infoLabels['tvdb_id'] and item.contentType == 'episode') or item.contentChannel == "videolibrary": #elif (not item.infoLabels['tvdb_id'] and item.contentType == 'episode') or item.contentChannel == "videolibrary":
# tmdb.set_infoLabels(item, True) # tmdb.set_infoLabels(item, True)
try: try:
tmdb.set_infoLabels(item, True) #TMDB de cada Temp tmdb.set_infoLabels(item, True) #TMDB de cada Temp
except: except:
pass pass
#Restauramos la información de max num. de episodios por temporada despues de TMDB #Restauramos la información de max num. de episodios por temporada despues de TMDB
@@ -980,7 +997,7 @@ def post_tmdb_findvideos(item, itemlist):
if item.infoLabels['duration']: if item.infoLabels['duration']:
tiempo = item.infoLabels['duration'] tiempo = item.infoLabels['duration']
elif item.contentChannel == 'videolibrary': #No hay, viene de la Videoteca? buscamos en la DB 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 #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
nun_records = 0 nun_records = 0
try: try:
@@ -995,14 +1012,14 @@ def post_tmdb_findvideos(item, itemlist):
for strFileName, field1 in records: for strFileName, field1 in records:
tiempo = field1 tiempo = field1
try: #calculamos el timepo en hh:mm try: #calculamos el timepo en hh:mm
tiempo_final = int(tiempo) #lo convierto a int, pero puede se null tiempo_final = int(tiempo) #lo convierto a int, pero puede se null
if tiempo_final > 0: #Si el tiempo está a 0, pasamos if tiempo_final > 0: #Si el tiempo está a 0, pasamos
if tiempo_final > 700: #Si está en segundos if tiempo_final > 700: #Si está en segundos
tiempo_final = tiempo_final / 60 #Lo transformo a minutos tiempo_final = tiempo_final / 60 #Lo transformo a minutos
horas = tiempo_final / 60 #Lo transformo a horas horas = tiempo_final / 60 #Lo transformo a horas
resto = tiempo_final - (horas * 60) #guardo el resto de minutos de la hora resto = tiempo_final - (horas * 60) #guardo el resto de minutos de la hora
if not scrapertools.find_single_match(item.quality, '(\[\d+:\d+)'): #si ya tiene la duración, pasamos 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 item.quality += ' [/COLOR][COLOR white][%s:%s h]' % (str(horas).zfill(2), str(resto).zfill(2)) #Lo agrego a Calidad del Servidor
except: except:
pass pass
@@ -1023,11 +1040,11 @@ def post_tmdb_findvideos(item, itemlist):
if (" al " in item.title or " Al " in item.title) and not "al " in item.infoLabels['episodio_titulo']: if (" al " in item.title or " Al " in item.title) and not "al " in item.infoLabels['episodio_titulo']:
title = '%s al %s - ' % (title, scrapertools.find_single_match(item.title, '[al|Al] (\d+)')) title = '%s al %s - ' % (title, scrapertools.find_single_match(item.title, '[al|Al] (\d+)'))
else: else:
title = '%s %s' % (title, item.infoLabels['episodio_titulo']) #Título Episodio title = '%s %s' % (title, item.infoLabels['episodio_titulo']) #Título Episodio
title_gen = '%s, ' % title title_gen = '%s, ' % title
if item.contentType == "episode" or item.contentType == "season": #Series o Temporadas if item.contentType == "episode" or item.contentType == "season": #Series o Temporadas
title_gen += '%s [COLOR yellow][%s][/COLOR] [%s] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] [%s]' % (item.contentSerieName, item.infoLabels['year'], rating, item.quality, str(item.language), scrapertools.find_single_match(item.title, '\s\[(\d+,?\d*?\s\w[b|B])\]')) #Rating, Calidad, Idioma, Tamaño title_gen += '%s [COLOR yellow][%s][/COLOR] [%s] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] [%s]' % (item.contentSerieName, item.infoLabels['year'], rating, item.quality, str(item.language), scrapertools.find_single_match(item.title, '\s\[(\d+,?\d*?\s\w[b|B])\]')) #Rating, Calidad, Idioma, Tamaño
if item.infoLabels['status'] and item.infoLabels['status'].lower() == "ended": if item.infoLabels['status'] and item.infoLabels['status'].lower() == "ended":
title_gen = '[TERM.] %s' % title_gen #Marca cuando la Serie está terminada y no va a haber más producción title_gen = '[TERM.] %s' % title_gen #Marca cuando la Serie está terminada y no va a haber más producción
item.title = title_gen item.title = title_gen
@@ -1042,9 +1059,9 @@ def post_tmdb_findvideos(item, itemlist):
title_gen = title_gen.replace(" []", "").strip() #Quitamos etiquetas vacías title_gen = title_gen.replace(" []", "").strip() #Quitamos etiquetas vacías
title_videoteca = title_gen #Salvamos el título para Videoteca title_videoteca = title_gen #Salvamos el título para Videoteca
if not item.unify: #Si Titulos Inteligentes NO seleccionados: if not item.unify: #Si Titulos Inteligentes NO seleccionados:
title_gen = '**- [COLOR gold]Enlaces Ver: [/COLOR]%s[COLOR gold] -**[/COLOR]' % (title_gen) title_gen = '**- [COLOR gold]Enlaces Ver: [/COLOR]%s[COLOR gold] -**[/COLOR]' % (title_gen)
else: #Si Titulos Inteligentes SÍ seleccionados: else: #Si Titulos Inteligentes SÍ seleccionados:
title_gen = '[COLOR gold]Enlaces Ver: [/COLOR]%s' % (title_gen) title_gen = '[COLOR gold]Enlaces Ver: [/COLOR]%s' % (title_gen)
if item.channel_alt: if item.channel_alt:
@@ -1107,7 +1124,7 @@ def get_field_from_kodi_DB(item, from_fields='*', files='file'):
VIDEOLIBRARY_PATH = config.get_videolibrary_config_path() VIDEOLIBRARY_PATH = config.get_videolibrary_config_path()
VIDEOLIBRARY_REAL_PATH = config.get_videolibrary_path() VIDEOLIBRARY_REAL_PATH = config.get_videolibrary_path()
if item.contentType == 'movie': #Agrego la carpeta correspondiente al path de la Videoteca if item.contentType == 'movie': #Agrego la carpeta correspondiente al path de la Videoteca
path = filetools.join(VIDEOLIBRARY_REAL_PATH, FOLDER_MOVIES) path = filetools.join(VIDEOLIBRARY_REAL_PATH, FOLDER_MOVIES)
path2 = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES) path2 = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES)
folder = FOLDER_MOVIES folder = FOLDER_MOVIES
@@ -1116,40 +1133,40 @@ def get_field_from_kodi_DB(item, from_fields='*', files='file'):
path2 = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS) path2 = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS)
folder = FOLDER_TVSHOWS folder = FOLDER_TVSHOWS
raiz, carpetas, ficheros = filetools.walk(path).next() #listo las series o películas en la Videoteca raiz, carpetas, ficheros = filetools.walk(path).next() #listo las series o películas en la Videoteca
carpetas = [filetools.join(path, f) for f in carpetas] #agrego la carpeta del contenido al path carpetas = [filetools.join(path, f) for f in carpetas] #agrego la carpeta del contenido al path
for carpeta in carpetas: #busco el contenido seleccionado en la lista de carpetas for carpeta in carpetas: #busco el contenido seleccionado en la lista de carpetas
if item.contentType == 'movie' and (item.contentTitle.lower() in carpeta or item.contentTitle in carpeta): #Películas? if item.contentType == 'movie' and (item.contentTitle.lower() in carpeta or item.contentTitle in carpeta): #Películas?
path = carpeta #Almacenamos la carpeta en el path path = carpeta #Almacenamos la carpeta en el path
break break
elif item.contentType in ['tvshow', 'season', 'episode'] and (item.contentSerieName.lower() in carpeta or item.contentSerieName in carpeta): #Series? elif item.contentType in ['tvshow', 'season', 'episode'] and (item.contentSerieName.lower() in carpeta or item.contentSerieName in carpeta): #Series?
path = carpeta #Almacenamos la carpeta en el path path = carpeta #Almacenamos la carpeta en el path
break break
path2 += '/%s/' % scrapertools.find_single_match(path, '%s.(.*?\s\[.*?\])' % folder) #Agregamos la carpeta de la Serie o Películas, formato Android path2 += '/%s/' % scrapertools.find_single_match(path, '%s.(.*?\s\[.*?\])' % folder) #Agregamos la carpeta de la Serie o Películas, formato Android
file_search = '%' #Por defecto busca todos los archivos de la carpeta file_search = '%' #Por defecto busca todos los archivos de la carpeta
if files == 'file': #Si se ha pedido son un archivo (defecto), se busca if files == 'file': #Si se ha pedido son un archivo (defecto), se busca
if item.contentType == 'episode': #Si es episodio, se pone el nombre, si no de deja % if item.contentType == 'episode': #Si es episodio, se pone el nombre, si no de deja %
file_search = '%sx%s.strm' % (item.contentSeason, str(item.contentEpisodeNumber).zfill(2)) #Nombre para episodios file_search = '%sx%s.strm' % (item.contentSeason, str(item.contentEpisodeNumber).zfill(2)) #Nombre para episodios
if "\\" in path: #Ajustamos los / en función de la plataforma if "\\" in path: #Ajustamos los / en función de la plataforma
path = path.replace("/", "\\") path = path.replace("/", "\\")
path += "\\" #Terminamos el path con un / path += "\\" #Terminamos el path con un /
else: else:
path += "/" path += "/"
if FOLDER_TVSHOWS in path: #Compruebo si es CINE o SERIE if FOLDER_TVSHOWS in path: #Compruebo si es CINE o SERIE
contentType = "episode_view" #Marco la tabla de BBDD de Kodi Video contentType = "episode_view" #Marco la tabla de BBDD de Kodi Video
else: else:
contentType = "movie_view" #Marco la tabla de BBDD de Kodi Video contentType = "movie_view" #Marco la tabla de BBDD de Kodi Video
path1 = path.replace("\\\\", "\\") #para la SQL solo necesito la carpeta path1 = path.replace("\\\\", "\\") #para la SQL solo necesito la carpeta
path2 = path2.replace("\\", "/") #Formato no Windows path2 = path2.replace("\\", "/") #Formato no Windows
#Ejecutmos la sentencia SQL #Ejecutmos la sentencia SQL
if not from_fields: if not from_fields:
from_fields = '*' from_fields = '*'
else: else:
from_fields = 'strFileName, %s' % from_fields #al menos dos campos, porque uno solo genera cosas raras from_fields = 'strFileName, %s' % from_fields #al menos dos campos, porque uno solo genera cosas raras
sql = 'select %s from %s where (strPath like "%s" or strPath like "%s") and strFileName like "%s"' % (from_fields, contentType, path1, path2, file_search) sql = 'select %s from %s where (strPath like "%s" or strPath like "%s") and strFileName like "%s"' % (from_fields, contentType, path1, path2, file_search)
nun_records = 0 nun_records = 0
records = None records = None
@@ -1233,7 +1250,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
return (item, data) #nos vamos, con el mismo clone, si está activo return (item, data) #nos vamos, con el mismo clone, si está activo
if (item.action == 'episodios' or item.action == 'findvideos') and item.contentType not in contentType: #soporta el fail_over de este contenido? if (item.action == 'episodios' or item.action == 'findvideos') and item.contentType not in contentType: #soporta el fail_over de este contenido?
logger.error("ERROR 99: " + item.action.upper() + ": Acción no soportada para Fail-Over en canal: " + item.url) 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 return (item, data) #no soporta el fail_over de este contenido, no podemos hacer nada
break break
if not channel_failed: if not channel_failed:
@@ -1263,7 +1280,7 @@ def fail_over_newpct1(item, patron, patron2=None, timeout=None):
#quitamos el código de series, porque puede variar entre webs #quitamos el código de series, porque puede variar entre webs
if item.action == "episodios" or item.action == "get_seasons": if item.action == "episodios" or item.action == "get_seasons":
item.url = re.sub(r'\/\d+\/?$', '', item.url) #parece que con el título solo ecuentra la serie, normalmente... item.url = re.sub(r'\/\d+\/?$', '', item.url) #parece que con el título solo ecuentra la serie, normalmente...
url_alt = [item.url] #salvamos la url para el bucle, pero de momento ignoramos la inicial con código de serie url_alt = [item.url] #salvamos la url para el bucle, pero de momento ignoramos la inicial con código de serie
#si es un episodio, generalizamos la url para que se pueda encontrar en otro clone. Quitamos la calidad del final de la url #si es un episodio, generalizamos la url para que se pueda encontrar en otro clone. Quitamos la calidad del final de la url
elif item.action == "findvideos" and item.contentType == "episode": elif item.action == "findvideos" and item.contentType == "episode":
@@ -1380,7 +1397,7 @@ def web_intervenida(item, data, desactivar=True):
category = item.category category = item.category
if not item.category: if not item.category:
category = item.channel category = item.channel
intervencion = (category, judicial) #Guardamos el nombre canal/categoría y el thumb judicial intervencion = (category, judicial) #Guardamos el nombre canal/categoría y el thumb judicial
if not item.intervencion: if not item.intervencion:
item.intervencion = [] #Si no existe el array, lo creamos item.intervencion = [] #Si no existe el array, lo creamos
item.intervencion += [intervencion] #Añadimos esta intervención al array item.intervencion += [intervencion] #Añadimos esta intervención al array
@@ -1416,10 +1433,10 @@ def web_intervenida(item, data, desactivar=True):
#Guardamos los cambios hechos en el .json #Guardamos los cambios hechos en el .json
try: try:
if item.channel != channel_py: if item.channel != channel_py:
disabled = config.set_setting('enabled', False, item.channel) #Desactivamos el canal disabled = config.set_setting('enabled', False, item.channel) #Desactivamos el canal
disabled = config.set_setting('include_in_global_search', False, item.channel) #Lo sacamos de las búquedas globales disabled = config.set_setting('include_in_global_search', False, item.channel) #Lo sacamos de las búquedas globales
channel_path = filetools.join(config.get_runtime_path(), "channels", item.channel + ".json") channel_path = filetools.join(config.get_runtime_path(), "channels", item.channel + ".json")
with open(channel_path, 'w') as outfile: #Grabamos el .json actualizado with open(channel_path, 'w') as outfile: #Grabamos el .json actualizado
json.dump(json_data, outfile, sort_keys = True, indent = 2, ensure_ascii = False) json.dump(json_data, outfile, sort_keys = True, indent = 2, ensure_ascii = False)
except: except:
logger.error("ERROR 98 al salvar el archivo: %s" % channel_path) logger.error("ERROR 98 al salvar el archivo: %s" % channel_path)
@@ -1526,96 +1543,96 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
return (item, it, overwrite) #... el canal/clone está listado return (item, it, overwrite) #... el canal/clone está listado
import ast import ast
intervencion_list = ast.literal_eval(intervencion) #Convertir a Array el string intervencion_list = ast.literal_eval(intervencion) #Convertir a Array el string
#logger.debug(intervencion_list) #logger.debug(intervencion_list)
if lookup == True: if lookup == True:
overwrite = False #Solo avisamos si hay cambios overwrite = False #Solo avisamos si hay cambios
for activo, canal_org, canal_des, url_org, url_des, patron1, patron2, patron3, patron4, patron5, content_inc, content_exc, ow_force in intervencion_list: for activo, canal_org, canal_des, url_org, url_des, patron1, patron2, patron3, patron4, patron5, content_inc, content_exc, ow_force in intervencion_list:
#Es esta nuestra entrada? #Es esta nuestra entrada?
if activo == '1' and (canal_org == channel_alt or canal_org == item.channel or channel_alt == 'videolibrary' or ow_force == 'del'): if activo == '1' and (canal_org == channel_alt or canal_org == item.channel or channel_alt == 'videolibrary' or ow_force == 'del'):
if ow_force == 'del': #Si es un borrado de estructuras erroneas, hacemos un proceso aparte if ow_force == 'del': #Si es un borrado de estructuras erroneas, hacemos un proceso aparte
canal_des_def = canal_des #Si hay canal de sustitución para item.library_urls, lo usamos canal_des_def = canal_des #Si hay canal de sustitución para item.library_urls, lo usamos
if not canal_des_def and canal_org in item.library_urls and len(item.library_urls) == 1: #Si no, lo extraemos de la url if not canal_des_def and canal_org in item.library_urls and len(item.library_urls) == 1: #Si no, lo extraemos de la url
canal_des_def = scrapertools.find_single_match(item.library_urls[canal_org], 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').lower() #salvamos la url actual de la estructura a borrar canal_des_def = scrapertools.find_single_match(item.library_urls[canal_org], 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').lower() #salvamos la url actual de la estructura a borrar
url_total = '' url_total = ''
if item.url: if item.url:
url_total = item.url #Si existe item.url, lo salvamos para futuro uso url_total = item.url #Si existe item.url, lo salvamos para futuro uso
if item.library_urls and canal_org in item.library_urls: #Si existe una entrada con el canal a borrar, lo procesamos if item.library_urls and canal_org in item.library_urls: #Si existe una entrada con el canal a borrar, lo procesamos
if lookup == True: #Queremos que el canal solo visualice sin migración? if lookup == True: #Queremos que el canal solo visualice sin migración?
overwrite = True #Avisamos que hay cambios overwrite = True #Avisamos que hay cambios
continue continue
logger.error('** REGLA: ' + canal_org + ', ' + canal_des+ ', ' + ow_force) logger.error('** REGLA: ' + canal_org + ', ' + canal_des+ ', ' + ow_force)
logger.error('item.library_urls PREVIA: ' + str(item.library_urls)) logger.error('item.library_urls PREVIA: ' + str(item.library_urls))
url_total = item.library_urls[canal_org] #salvamos la url actual de la estructura a borrar url_total = item.library_urls[canal_org] #salvamos la url actual de la estructura a borrar
url_total_status = False url_total_status = False
if len(item.library_urls) == 1 or canal_des: #si el nuevo canal no existe ya... if len(item.library_urls) == 1 or canal_des: #si el nuevo canal no existe ya...
item.library_urls.update({canal_des_def: url_total}) #restauramos la url con el nuevo canal item.library_urls.update({canal_des_def: url_total}) #restauramos la url con el nuevo canal
url_total_status = True #marcamos esta url como válida url_total_status = True #marcamos esta url como válida
overwrite = True #Le decimos que sobreescriba todos los .jsons overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas item.ow_force = '1' #Le decimos que revise todas las temporadas
if len(item.library_urls) > 1: if len(item.library_urls) > 1:
item.library_urls.pop(canal_org, None) #borramos la url del canal a borrar item.library_urls.pop(canal_org, None) #borramos la url del canal a borrar
overwrite = True #Le decimos que sobreescriba todos los .jsons overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas item.ow_force = '1' #Le decimos que revise todas las temporadas
if it.library_urls: if it.library_urls:
it.library_urls = item.library_urls #lo salvamos en el .nfo, si lo hay it.library_urls = item.library_urls #lo salvamos en el .nfo, si lo hay
if item.url and item.url == url_total and url_total_status == False: #si la url es la del canal borrado... if item.url and item.url == url_total and url_total_status == False: #si la url es la del canal borrado...
for canal_vid, url_vid in item.library_urls.items(): for canal_vid, url_vid in item.library_urls.items():
canal_vid_alt = "'%s'" % canal_vid canal_vid_alt = "'%s'" % canal_vid
if canal_vid_alt not in intervencion: #... la sustituimos por la primera válida if canal_vid_alt not in intervencion: #... la sustituimos por la primera válida
item.url = url_vid item.url = url_vid
break break
if canal_vid_alt in fail_over_list: #Si es un clone de Newpct1, salvamos la nueva categoría if canal_vid_alt in fail_over_list: #Si es un clone de Newpct1, salvamos la nueva categoría
item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').lower() #Salvamos categoría item.category = scrapertools.find_single_match(item.url, 'http.?\:\/\/(?:www.)?(\w+)\.\w+\/').lower() #Salvamos categoría
else: else:
item.category = canal_vid.capitalize() #si no, salvamos nueva categoría item.category = canal_vid.capitalize() #si no, salvamos nueva categoría
logger.error('item.library_urls ACTUALIZADA: ' + str(item.library_urls)) logger.error('item.library_urls ACTUALIZADA: ' + str(item.library_urls))
if lookup == False: #si es migración completa... if lookup == False: #si es migración completa...
delete_stat += 1 #Ya hemos actualizado algo, o habrá que hacerlo... delete_stat += 1 #Ya hemos actualizado algo, o habrá que hacerlo...
canal_org_des_list += [(canal_org, canal_des, url_total, ow_force)] #salvamos el resultado para su proceso canal_org_des_list += [(canal_org, canal_des, url_total, ow_force)] #salvamos el resultado para su proceso
else: else:
if channel_alt == 'videolibrary': #Viene de videolibrary.list_movies: IMPRESCINDIBLE if channel_alt == 'videolibrary': #Viene de videolibrary.list_movies: IMPRESCINDIBLE
for canal_vid, url_vid in item.library_urls.items(): for canal_vid, url_vid in item.library_urls.items():
if canal_org != canal_vid: #Miramos si canal_org de la regla está en item.library_urls if canal_org != canal_vid: #Miramos si canal_org de la regla está en item.library_urls
continue continue
else: else:
channel_alt = canal_org #Sí, ponermos el nombre del canal de origen channel_alt = canal_org #Sí, ponermos el nombre del canal de origen
channel_b = "'%s'" % canal_org channel_b = "'%s'" % canal_org
if channel_b in fail_over_list: #Si es un clone de Newpct1, se actualiza a newpct1 if channel_b in fail_over_list: #Si es un clone de Newpct1, se actualiza a newpct1
channel_alt = channel_py channel_alt = channel_py
if channel_alt == 'videolibrary': if channel_alt == 'videolibrary':
continue continue
if item.contentType == "list": #Si viene de Videolibrary, le cambiamos ya el canal if item.contentType == "list": #Si viene de Videolibrary, le cambiamos ya el canal
if item.channel != channel_py: if item.channel != channel_py:
item.channel = canal_des #Cambiamos el canal. Si es clone, lo hace el canal item.channel = canal_des #Cambiamos el canal. Si es clone, lo hace el canal
continue #Salimos sin hacer nada más. item está casi vacío continue #Salimos sin hacer nada más. item está casi vacío
if item.contentType not in content_inc and "*" not in content_inc: #Está el contenido el la lista de incluidos if item.contentType not in content_inc and "*" not in content_inc: #Está el contenido el la lista de incluidos
continue continue
if item.contentType in content_exc: #Está el contenido excluido? if item.contentType in content_exc: #Está el contenido excluido?
continue continue
if item.channel != channel_py: if item.channel != channel_py:
channel_enabled = channeltools.is_enabled(channel_alt) #Verificamos que el canal esté inactivo channel_enabled = channeltools.is_enabled(channel_alt) #Verificamos que el canal esté inactivo
channel_enabled_alt = config.get_setting('enabled', channel_alt) channel_enabled_alt = config.get_setting('enabled', channel_alt)
channel_enabled = channel_enabled * channel_enabled_alt #Si está inactivo en algún sitio, tomamos eso channel_enabled = channel_enabled * channel_enabled_alt #Si está inactivo en algún sitio, tomamos eso
if channel_enabled == 1 and canal_org != canal_des: #Si el canal está activo, puede ser solo... if channel_enabled == 1 and canal_org != canal_des: #Si el canal está activo, puede ser solo...
continue #... una intervención que afecte solo a una región continue #... una intervención que afecte solo a una región
if ow_force == 'no' and it.library_urls: #Esta regla solo vale para findvideos... if ow_force == 'no' and it.library_urls: #Esta regla solo vale para findvideos...
continue #... salidmos si estamos actualizando continue #... salidmos si estamos actualizando
if lookup == True: #Queremos que el canal solo visualice sin migración? if lookup == True: #Queremos que el canal solo visualice sin migración?
if ow_force != 'no': if ow_force != 'no':
overwrite = True #Avisamos que hay cambios overwrite = True #Avisamos que hay cambios
continue #Salimos sin tocar archivos continue #Salimos sin tocar archivos
url_total = '' url_total = ''
if item.url: if item.url:
url_total = item.url url_total = item.url
elif not item.url and item.library_urls: elif not item.url and item.library_urls:
url_total = item.library_urls[canal_org] url_total = item.library_urls[canal_org]
url_total = url_total.replace(url_org, url_des) #reemplazamos una parte de url url_total = url_total.replace(url_org, url_des) #reemplazamos una parte de url
url = '' url = ''
if patron1: #Hay expresión regex? if patron1: #Hay expresión regex?
url += scrapertools.find_single_match(url_total, patron1) #La aplicamos a url url += scrapertools.find_single_match(url_total, patron1) #La aplicamos a url
@@ -1665,39 +1682,39 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
# Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno # Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno
canal_erase_list = [] canal_erase_list = []
raiz, carpetas_series, ficheros = filetools.walk(path).next() raiz, carpetas_series, ficheros = filetools.walk(path).next()
ficheros = [filetools.join(path, f) for f in ficheros] #Almacenamos la lista de archivos de la carpeta ficheros = [filetools.join(path, f) for f in ficheros] #Almacenamos la lista de archivos de la carpeta
for archivo in ficheros: for archivo in ficheros:
for canal_org_def, canal_des_def, url_total, ow_force_def in canal_org_des_list: #pasamos por todas las "parejas" a borrar for canal_org_def, canal_des_def, url_total, ow_force_def in canal_org_des_list: #pasamos por todas las "parejas" a borrar
canal_erase = '[%s]' % canal_org_def canal_erase = '[%s]' % canal_org_def
canal_new = '[%s]' % canal_des_def canal_new = '[%s]' % canal_des_def
if canal_erase in archivo: #Borramos los .json que sean de los canal afectados if canal_erase in archivo: #Borramos los .json que sean de los canal afectados
if canal_des_def: if canal_des_def:
item_json = Item().fromjson(filetools.read(archivo)) #leemos el .json ante de borrarlo para salvar... item_json = Item().fromjson(filetools.read(archivo)) #leemos el .json ante de borrarlo para salvar...
title = item_json.title #... el título con su formato title = item_json.title #... el título con su formato
language = item_json.language #... los idiomas, que no están en el .nfo language = item_json.language #... los idiomas, que no están en el .nfo
wanted = item_json.wanted #... y wanted con el título original wanted = item_json.wanted #... y wanted con el título original
json_path = archivo.replace(canal_erase, canal_new) #Salvamos el path del .json para luego crearlo json_path = archivo.replace(canal_erase, canal_new) #Salvamos el path del .json para luego crearlo
json_path_list += [(canal_org_def, canal_des_def, url_total, json_path, title, language, wanted)] json_path_list += [(canal_org_def, canal_des_def, url_total, json_path, title, language, wanted)]
filetools.remove(archivo) #Borramos el .json filetools.remove(archivo) #Borramos el .json
logger.error('** BORRAMOS: ' + str(archivo)) logger.error('** BORRAMOS: ' + str(archivo))
if ow_force_def == 'del': #Si la función es 'del' ... if ow_force_def == 'del': #Si la función es 'del' ...
overwrite = True #Le decimos que sobreescriba todos los .jsons overwrite = True #Le decimos que sobreescriba todos los .jsons
item.ow_force = '1' #Le decimos que revise todas las temporadas item.ow_force = '1' #Le decimos que revise todas las temporadas
#Si se ha cambiado algo, se actualizan los .nfo #Si se ha cambiado algo, se actualizan los .nfo
if item.contentType == "movie" and ".nfo" in archivo: if item.contentType == "movie" and ".nfo" in archivo:
if it.ow_force: del it.ow_force if it.ow_force: del it.ow_force
filetools.write(archivo, head_nfo + it.tojson()) #escribo el .nfo de la peli por si aborta update filetools.write(archivo, head_nfo + it.tojson()) #escribo el .nfo de la peli por si aborta update
if item.contentType != "movie" and "tvshow.nfo" in archivo: if item.contentType != "movie" and "tvshow.nfo" in archivo:
filetools.write(archivo, head_nfo + it.tojson()) #escribo el tvshow.nfo por si aborta update filetools.write(archivo, head_nfo + it.tojson()) #escribo el tvshow.nfo por si aborta update
#Aquí convertimos las películas. Después de borrado el .json, dejamos que videolibrarytools lo regenere #Aquí convertimos las películas. Después de borrado el .json, dejamos que videolibrarytools lo regenere
if item.contentType == "movie": #Dejamos que regenere el archivo .json if item.contentType == "movie": #Dejamos que regenere el archivo .json
item_movie = item.clone() item_movie = item.clone()
if item_movie.ow_force: del item_movie.ow_force if item_movie.ow_force: del item_movie.ow_force
item_movie.update_last = '1' item_movie.update_last = '1'
del item_movie.update_last del item_movie.update_last
del item_movie.library_playcounts #Borramos lo que no es necesario en el .json del item_movie.library_playcounts #Borramos lo que no es necesario en el .json
del item_movie.library_urls del item_movie.library_urls
del item_movie.nfo del item_movie.nfo
del item_movie.path del item_movie.path
@@ -1710,14 +1727,14 @@ def redirect_clone_newpct1(item, head_nfo=None, it=None, path=False, overwrite=F
logger.error('** .json LIST: ' + str(json_path_list)) logger.error('** .json LIST: ' + str(json_path_list))
for canal_org_def, canal_des_def, url_total, json_path, title, language, wanted in json_path_list: #pasamos por todas canales for canal_org_def, canal_des_def, url_total, json_path, title, language, wanted in json_path_list: #pasamos por todas canales
logger.error('** ESCRIBIMOS: ' + json_path) logger.error('** ESCRIBIMOS: ' + json_path)
item_movie.channel = canal_des_def #mombre del canal migrado item_movie.channel = canal_des_def #mombre del canal migrado
if not item_movie.category: item_movie.category = canal_des_def.capitalize() #categoría if not item_movie.category: item_movie.category = canal_des_def.capitalize() #categoría
item_movie.url = url_total #url migrada item_movie.url = url_total #url migrada
if title: item_movie.title = title #restaurmos el título con formato if title: item_movie.title = title #restaurmos el título con formato
if language: item_movie.language = language #restaurmos los idiomas if language: item_movie.language = language #restaurmos los idiomas
if wanted: item_movie.wanted = wanted #restaurmos wanted if wanted: item_movie.wanted = wanted #restaurmos wanted
item_movie.added_replacing = canal_org_def #guardamos la traza del canal reemplazado item_movie.added_replacing = canal_org_def #guardamos la traza del canal reemplazado
filetools.write(json_path, item_movie.tojson()) #Salvamos el nuevo .json de la película filetools.write(json_path, item_movie.tojson()) #Salvamos el nuevo .json de la película
if (update_stat > 0 and path != False and ow_force_def in ['force', 'auto']) or item.ow_force == '1' or len(json_path_list) > 0: if (update_stat > 0 and path != False and ow_force_def in ['force', 'auto']) or item.ow_force == '1' or len(json_path_list) > 0:
logger.error('ITEM cambiado') logger.error('ITEM cambiado')
@@ -469,10 +469,11 @@ class SettingsWindow(xbmcgui.WindowXMLDialog):
self.ok_enabled = False self.ok_enabled = False
self.default_enabled = False self.default_enabled = False
if xbmcgui.__version__ == "1.2": if config.get_platform(True)['num_version'] < 18:
self.setCoordinateResolution(1) if xbmcgui.__version__ == "1.2":
else: self.setCoordinateResolution(1)
self.setCoordinateResolution(5) else:
self.setCoordinateResolution(5)
# Ponemos el título # Ponemos el título
self.getControl(10002).setLabel(self.caption) self.getControl(10002).setLabel(self.caption)