Mejora en reporting de errores

This commit is contained in:
Kingbox
2018-11-14 11:44:16 +01:00
parent 9a5bedf42a
commit e62bd5d6a2
4 changed files with 83 additions and 91 deletions
+14 -10
View File
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os, traceback
from channelselector import get_thumb from channelselector import get_thumb
from core import filetools from core import filetools
@@ -47,7 +47,7 @@ def list_movies(item, silent=False):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(nfo_path) xbmc_videolibrary.mark_content_as_watched_on_alfa(nfo_path)
except: except:
pass logger.error(traceback.format_exc())
head_nfo, new_item = videolibrarytools.read_nfo(nfo_path) head_nfo, new_item = videolibrarytools.read_nfo(nfo_path)
@@ -67,7 +67,7 @@ def list_movies(item, silent=False):
try: try:
new_item, new_item, overwrite = generictools.redirect_clone_newpct1(new_item, head_nfo, new_item, raiz) new_item, new_item, overwrite = generictools.redirect_clone_newpct1(new_item, head_nfo, new_item, raiz)
except: except:
pass logger.error(traceback.format_exc())
# Menu contextual: Marcar como visto/no visto # Menu contextual: Marcar como visto/no visto
visto = new_item.library_playcounts.get(os.path.splitext(f)[0], 0) visto = new_item.library_playcounts.get(os.path.splitext(f)[0], 0)
@@ -127,10 +127,10 @@ def list_tvshows(item):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_path) xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_path)
except: except:
pass logger.error(traceback.format_exc())
head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path) head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path)
try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing
item_tvshow.title = item_tvshow.contentTitle item_tvshow.title = item_tvshow.contentTitle
item_tvshow.path = raiz item_tvshow.path = raiz
item_tvshow.nfo = tvshow_path item_tvshow.nfo = tvshow_path
@@ -146,6 +146,7 @@ def list_tvshows(item):
except: except:
logger.error('No encuentra: ' + str(tvshow_path)) logger.error('No encuentra: ' + str(tvshow_path))
logger.error(traceback.format_exc())
continue continue
# Menu contextual: Buscar automáticamente nuevos episodios o no # Menu contextual: Buscar automáticamente nuevos episodios o no
@@ -368,7 +369,7 @@ def findvideos(item):
try: try:
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json) item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
except: except:
pass logger.error(traceback.format_exc())
item_json.contentChannel = "local" item_json.contentChannel = "local"
# Soporte para rutas relativas en descargas # Soporte para rutas relativas en descargas
if filetools.is_relative(item_json.url): if filetools.is_relative(item_json.url):
@@ -413,7 +414,7 @@ def findvideos(item):
try: try:
item_canal, it, overwrite = generictools.redirect_clone_newpct1(item_canal) item_canal, it, overwrite = generictools.redirect_clone_newpct1(item_canal)
except: except:
pass logger.error(traceback.format_exc())
nom_canal = item_canal.channel nom_canal = item_canal.channel
# Importamos el canal de la parte seleccionada # Importamos el canal de la parte seleccionada
@@ -427,7 +428,7 @@ def findvideos(item):
try: try:
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json) item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
except: except:
pass logger.error(traceback.format_exc())
list_servers = [] list_servers = []
try: try:
@@ -452,6 +453,7 @@ def findvideos(item):
template = "An exception of type %s occured. Arguments:\n%r" template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args) message = template % (type(ex).__name__, ex.args)
logger.error(message) logger.error(message)
logger.error(traceback.format_exc())
# Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
# las infoLabels y las imagenes del item si el server no tiene # las infoLabels y las imagenes del item si el server no tiene
@@ -778,7 +780,7 @@ def mark_tvshow_as_updatable(item):
def delete(item): def delete(item):
def delete_all(_item): def delete_all(_item):
for file in filetools.listdir(_item.path): for file in filetools.listdir(_item.path):
if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json"): if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json")or file.endswith(".torrent"):
filetools.remove(filetools.join(_item.path, file)) filetools.remove(filetools.join(_item.path, file))
raiz, carpeta_serie, ficheros = filetools.walk(_item.path).next() raiz, carpeta_serie, ficheros = filetools.walk(_item.path).next()
if ficheros == []: if ficheros == []:
@@ -822,7 +824,7 @@ def delete(item):
num_enlaces = 0 num_enlaces = 0
for fd in filetools.listdir(item.path): for fd in filetools.listdir(item.path):
if fd.endswith(canal + '].json'): if fd.endswith(canal + '].json') or scrapertools.find_single_match(fd, '%s]_\d+.torrent' % canal):
if filetools.remove(filetools.join(item.path, fd)): if filetools.remove(filetools.join(item.path, fd)):
num_enlaces += 1 num_enlaces += 1
@@ -830,6 +832,8 @@ def delete(item):
# Actualizar .nfo # Actualizar .nfo
head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo)
del item_nfo.library_urls[canal] del item_nfo.library_urls[canal]
if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False):
del item_nfo.emergency_urls[canal]
filetools.write(item.nfo, head_nfo + item_nfo.tojson()) filetools.write(item.nfo, head_nfo + item_nfo.tojson())
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal) msg_txt = config.get_localized_string(70087) % (num_enlaces, canal)
+61 -75
View File
@@ -5,6 +5,7 @@
import errno import errno
import math import math
import traceback
from core import filetools from core import filetools
from core import scraper from core import scraper
@@ -195,6 +196,7 @@ def save_movie(item):
item_nfo.emergency_urls.update({item.channel: True}) item_nfo.emergency_urls.update({item.channel: True})
except: except:
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % item.contentTitle) logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % item.contentTitle)
logger.error(traceback.format_exc())
if filetools.write(json_path, item.tojson()): if filetools.write(json_path, item.tojson()):
p_dialog.update(100, 'Añadiendo película...', item.contentTitle) p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
@@ -441,6 +443,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
except: except:
if e.contentType == 'episode': if e.contentType == 'episode':
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle) logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle)
logger.error(traceback.format_exc())
continue continue
# No hay lista de episodios, no hay nada que guardar # No hay lista de episodios, no hay nada que guardar
@@ -568,6 +571,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
except: except:
logger.error("Error al actualizar tvshow.nfo") logger.error("Error al actualizar tvshow.nfo")
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % tvshow_item.contentSerieName) logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % tvshow_item.contentSerieName)
logger.error(traceback.format_exc())
fallidos = -1 fallidos = -1
else: else:
# ... si ha sido correcto actualizamos la videoteca de Kodi # ... si ha sido correcto actualizamos la videoteca de Kodi
@@ -731,16 +735,18 @@ def emergency_urls(item, channel=None, path=None):
channel = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel]) channel = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel])
if hasattr(channel, 'findvideos'): #Si el canal tiene "findvideos"... if hasattr(channel, 'findvideos'): #Si el canal tiene "findvideos"...
item.videolibray_emergency_urls = True #... se marca como "lookup" item.videolibray_emergency_urls = True #... se marca como "lookup"
item_res = getattr(channel, 'findvideos')(item) #... se procesa channel_save = item.channel #... guarda el canal original por si hay fail-over en Newpct1
item_res = getattr(channel, 'findvideos')(item) #... se procesa Findvideos
item_res.channel = channel_save #... restaura el canal original por si hay fail-over en Newpct1
item_res.category = channel_save.capitalize() #... y la categoría
del item_res.videolibray_emergency_urls #... y se borra la marca de lookup del item_res.videolibray_emergency_urls #... y se borra la marca de lookup
except: except:
logger.error('ERROR al procesar el episodio') logger.error('ERROR al procesar el título en Findvideos del Canal: ' + item.channel + ' / ' + item.title)
logger.error(traceback.format_exc())
item_res = item.clone() #Si ha habido un error, se devuelve el Item original item_res = item.clone() #Si ha habido un error, se devuelve el Item original
#Si el usuario ha activado la opción "emergency_urls_torrents", se descargarán los archivos .torrent de cada título #Si el usuario ha activado la opción "emergency_urls_torrents", se descargarán los archivos .torrent de cada título
else: #Si se han cacheado con éxito los enlaces... else: #Si se han cacheado con éxito los enlaces...
logger.debug('HOLA')
logger.debug(item_res.emergency_urls)
try: try:
channel_bis = generictools.verify_channel(item.channel) channel_bis = generictools.verify_channel(item.channel)
if config.get_setting("emergency_urls_torrents", channel_bis) and item_res.emergency_urls and path != None: if config.get_setting("emergency_urls_torrents", channel_bis) and item_res.emergency_urls and path != None:
@@ -760,13 +766,15 @@ def emergency_urls(item, channel=None, path=None):
item_res.emergency_urls[0][i-1] = path_real.replace(videolibrary_path, '') #se guarda el "path" relativo item_res.emergency_urls[0][i-1] = path_real.replace(videolibrary_path, '') #se guarda el "path" relativo
i += 1 i += 1
except: except:
logger.error('ERROR al cachear el .torrent de: ' + item.channel + ' / ' + item.title)
logger.error(traceback.format_exc())
item_res = item.clone() #Si ha habido un error, se devuelve el Item original item_res = item.clone() #Si ha habido un error, se devuelve el Item original
#logger.debug(item_res.emergency_urls) #logger.debug(item_res.emergency_urls)
return item_res #Devolvemos el Item actualizado con los enlaces de emergencia return item_res #Devolvemos el Item actualizado con los enlaces de emergencia
def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, lookup=False): def caching_torrents(url, torrents_path=None, timeout=10, lookup=False, data_torrent=False):
if torrents_path != None: if torrents_path != None:
logger.info("path = " + torrents_path) logger.info("path = " + torrents_path)
else: else:
@@ -774,98 +782,80 @@ def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, loo
import urllib import urllib
import re import re
from core import httptools from core import httptools
torrent_file = ''
""" """
Descarga en el path recibido el .torrent de la url recibida, y pasa el decode Descarga en el path recibido el .torrent de la url recibida, y pasa el decode
Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito
""" """
def decode(text): if torrents_path == None:
try: videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
src = tokenize(text) if not videolibrary_path:
data = decode_item(src.next, src.next()) torrents_path = ''
for token in src: # look for more tokens if data_torrent:
raise SyntaxError("trailing junk") return (torrents_path, torrent_file)
except (AttributeError, ValueError, StopIteration): return torrents_path #Si hay un error, devolvemos el "path" vacío
try: torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path de descarga temporal
data = data if '.torrent' not in torrents_path:
except: torrents_path += '.torrent' #path para dejar el .torrent
data = src torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
return data if url.endswith(".rar"): #No es un archivo .torrent
logger.error('No es un archivo Torrent: ' + url)
def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match): torrents_path = ''
i = 0 if data_torrent:
while i < len(text): return (torrents_path, torrent_file)
m = match(text, i) return torrents_path #Si hay un error, devolvemos el "path" vacío
s = m.group(m.lastindex)
i = m.end()
if m.lastindex == 2:
yield "s"
yield text[i:i + int(s)]
i = i + int(s)
else:
yield s
def decode_item(next, token):
if token == "i":
# integer: "i" value "e"
data = int(next())
if next() != "e":
raise ValueError
elif token == "s":
# string: "s" value (virtual tokens)
data = next()
elif token == "l" or token == "d":
# container: "l" (or "d") values "e"
data = []
tok = next()
while tok != "e":
data.append(decode_item(next, tok))
tok = next()
if token == "d":
data = dict(zip(data[0::2], data[1::2]))
else:
raise ValueError
return data
#Módulo PRINCIPAL
try: try:
if lookup:
torrents_path = lookup
else:
if '.torrent' not in torrents_path:
torrents_path += '.torrent' #path para dejar el .torrent
torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
response = httptools.downloadpage(url, timeout=timeout) #Descargamos el .torrent response = httptools.downloadpage(url, timeout=timeout) #Descargamos el .torrent
if not response.sucess: if not response.sucess:
logger.error('Archivo .torrent no encontrado: ' + url) logger.error('Archivo .torrent no encontrado: ' + url)
torrents_path = '' torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío return torrents_path #Si hay un error, devolvemos el "path" vacío
torrent_file = response.data torrent_file = response.data
if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso
response = httptools.downloadpage("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(), timeout=timeout) response = httptools.downloadpage("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(), timeout=timeout)
if not response.sucess: if not response.sucess:
logger.error('Archivo .torrent no encontrado: ' + url) logger.error('Archivo .torrent no encontrado: ' + url)
torrents_path = '' torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío return torrents_path #Si hay un error, devolvemos el "path" vacío
torrent_file = response.data torrent_file = response.data
if decode_flag: if not scrapertools.find_single_match(torrent_file, '^d\d+:\w+\d+:'): #No es un archivo .torrent (RAR, ZIP, HTML,..., vacío)
torrent_file = decode(torrent_file) #decodificamos el .torrent logger.error('No es un archivo Torrent: ' + url)
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
if not lookup: if not lookup:
filetools.write(torrents_path_encode, torrent_file) #Salvamos el .torrent if not filetools.write(torrents_path_encode, torrent_file): #Salvamos el .torrent
logger.error('ERROR: Archivo .torrent no escrito: ' + torrents_path_encode)
torrents_path = '' #Si hay un error, devolvemos el "path" vacío
torrent_file = '' #... y el buffer del .torrent
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path
except: except:
torrents_path = '' #Si hay un error, devolvemos el "path" vacío torrents_path = '' #Si hay un error, devolvemos el "path" vacío
torrent_file = '' #... y el buffer del .torrent
logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode)
logger.error(traceback.format_exc())
#logger.debug(torrents_path) #logger.debug(torrents_path)
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path return torrents_path
def verify_url_torrent(url, decode_flag=False, timeout=5): def verify_url_torrent(url, timeout=5):
""" """
Verifica si el archivo .torrent al que apunta la url está disponible, descargándolo en un area temporal Verifica si el archivo .torrent al que apunta la url está disponible, descargándolo en un area temporal
Entrada: url Entrada: url
@@ -874,12 +864,8 @@ def verify_url_torrent(url, decode_flag=False, timeout=5):
if not url or url == 'javascript:;': #Si la url viene vacía... if not url or url == 'javascript:;': #Si la url viene vacía...
return False #... volvemos con error return False #... volvemos con error
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent
if torrents_path: #Si ha tenido éxito... if torrents_path: #Si ha tenido éxito...
return True return True
try: else:
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode return False
if torrents_path: #Si ha tenido éxito...
return True
except:
return False #en caso de error, False
@@ -6,6 +6,7 @@
import os import os
import time import time
import threading import threading
import traceback
from platformcode import config, logger, platformtools from platformcode import config, logger, platformtools
@@ -140,6 +141,7 @@ def check_addon_updates(verbose=False):
except: except:
logger.error('Error al comprobar actualizaciones del addon!') logger.error('Error al comprobar actualizaciones del addon!')
logger.error(traceback.format_exc())
if verbose: if verbose:
platformtools.dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones') platformtools.dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones')
return False return False
+6 -6
View File
@@ -3,7 +3,7 @@
# Service for updating new episodes on library series # Service for updating new episodes on library series
# ------------------------------------------------------------ # ------------------------------------------------------------
import datetime, imp, math, threading import datetime, imp, math, threading, traceback
from core import channeltools, filetools, videolibrarytools from core import channeltools, filetools, videolibrarytools
from platformcode import config, logger from platformcode import config, logger
@@ -32,7 +32,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
serie.category = category serie.category = category
serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite) serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite)
except: except:
pass logger.error(traceback.format_exc())
channel_enabled = channeltools.is_enabled(serie.channel) channel_enabled = channeltools.is_enabled(serie.channel)
@@ -89,7 +89,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo') xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
except: except:
pass logger.error(traceback.format_exc())
return insertados_total > 0 return insertados_total > 0
@@ -127,7 +127,7 @@ def check_for_update(overwrite=True):
try: try:
serie, serie, overwrite_forced = generictools.redirect_clone_newpct1(serie, head_nfo, serie, path, overwrite, lookup=True) serie, serie, overwrite_forced = generictools.redirect_clone_newpct1(serie, head_nfo, serie, path, overwrite, lookup=True)
except: except:
pass logger.error(traceback.format_exc())
if overwrite_forced == True: if overwrite_forced == True:
overwrite = True overwrite = True
serie.update_next = '' serie.update_next = ''
@@ -143,7 +143,7 @@ def check_for_update(overwrite=True):
if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora
serie, estado = videolibrary.verify_playcount_series(serie, path) #También se pasa si falta un PlayCount por completo serie, estado = videolibrary.verify_playcount_series(serie, path) #También se pasa si falta un PlayCount por completo
except: except:
pass logger.error(traceback.format_exc())
else: else:
if estado: #Si ha tenido éxito la actualización... if estado: #Si ha tenido éxito la actualización...
estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca
@@ -159,7 +159,7 @@ def check_for_update(overwrite=True):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo') xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
except: except:
pass logger.error(traceback.format_exc())
continue continue