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

View File

@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
import os
import os, traceback
from channelselector import get_thumb
from core import filetools
@@ -47,7 +47,7 @@ def list_movies(item, silent=False):
from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(nfo_path)
except:
pass
logger.error(traceback.format_exc())
head_nfo, new_item = videolibrarytools.read_nfo(nfo_path)
@@ -67,7 +67,7 @@ def list_movies(item, silent=False):
try:
new_item, new_item, overwrite = generictools.redirect_clone_newpct1(new_item, head_nfo, new_item, raiz)
except:
pass
logger.error(traceback.format_exc())
# Menu contextual: Marcar como visto/no visto
visto = new_item.library_playcounts.get(os.path.splitext(f)[0], 0)
@@ -127,10 +127,10 @@ def list_tvshows(item):
from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_path)
except:
pass
logger.error(traceback.format_exc())
head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path)
try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing
try: #A veces da errores aleatorios, por no encontrar el .nfo. Probablemente problemas de timing
item_tvshow.title = item_tvshow.contentTitle
item_tvshow.path = raiz
item_tvshow.nfo = tvshow_path
@@ -146,6 +146,7 @@ def list_tvshows(item):
except:
logger.error('No encuentra: ' + str(tvshow_path))
logger.error(traceback.format_exc())
continue
# Menu contextual: Buscar automáticamente nuevos episodios o no
@@ -368,7 +369,7 @@ def findvideos(item):
try:
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
except:
pass
logger.error(traceback.format_exc())
item_json.contentChannel = "local"
# Soporte para rutas relativas en descargas
if filetools.is_relative(item_json.url):
@@ -413,7 +414,7 @@ def findvideos(item):
try:
item_canal, it, overwrite = generictools.redirect_clone_newpct1(item_canal)
except:
pass
logger.error(traceback.format_exc())
nom_canal = item_canal.channel
# Importamos el canal de la parte seleccionada
@@ -427,7 +428,7 @@ def findvideos(item):
try:
item_json, it, overwrite = generictools.redirect_clone_newpct1(item_json)
except:
pass
logger.error(traceback.format_exc())
list_servers = []
try:
@@ -452,6 +453,7 @@ def findvideos(item):
template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args)
logger.error(message)
logger.error(traceback.format_exc())
# Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
# las infoLabels y las imagenes del item si el server no tiene
@@ -778,7 +780,7 @@ def mark_tvshow_as_updatable(item):
def delete(item):
def delete_all(_item):
for file in filetools.listdir(_item.path):
if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json"):
if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json")or file.endswith(".torrent"):
filetools.remove(filetools.join(_item.path, file))
raiz, carpeta_serie, ficheros = filetools.walk(_item.path).next()
if ficheros == []:
@@ -822,7 +824,7 @@ def delete(item):
num_enlaces = 0
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)):
num_enlaces += 1
@@ -830,6 +832,8 @@ def delete(item):
# Actualizar .nfo
head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo)
del item_nfo.library_urls[canal]
if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False):
del item_nfo.emergency_urls[canal]
filetools.write(item.nfo, head_nfo + item_nfo.tojson())
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal)

View File

@@ -5,6 +5,7 @@
import errno
import math
import traceback
from core import filetools
from core import scraper
@@ -195,6 +196,7 @@ def save_movie(item):
item_nfo.emergency_urls.update({item.channel: True})
except:
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % item.contentTitle)
logger.error(traceback.format_exc())
if filetools.write(json_path, item.tojson()):
p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
@@ -441,6 +443,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
except:
if e.contentType == 'episode':
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % e.contentTitle)
logger.error(traceback.format_exc())
continue
# No hay lista de episodios, no hay nada que guardar
@@ -568,6 +571,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
except:
logger.error("Error al actualizar tvshow.nfo")
logger.error("No se ha podido guardar las urls de emergencia de %s en la videoteca" % tvshow_item.contentSerieName)
logger.error(traceback.format_exc())
fallidos = -1
else:
# ... si ha sido correcto actualizamos la videoteca de Kodi
@@ -731,16 +735,18 @@ def emergency_urls(item, channel=None, path=None):
channel = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel])
if hasattr(channel, 'findvideos'): #Si el canal tiene "findvideos"...
item.videolibray_emergency_urls = True #... se marca como "lookup"
item_res = getattr(channel, 'findvideos')(item) #... se procesa
channel_save = item.channel #... guarda el canal original por si hay fail-over en Newpct1
item_res = getattr(channel, 'findvideos')(item) #... se procesa Findvideos
item_res.channel = channel_save #... restaura el canal original por si hay fail-over en Newpct1
item_res.category = channel_save.capitalize() #... y la categoría
del item_res.videolibray_emergency_urls #... y se borra la marca de lookup
except:
logger.error('ERROR al procesar el episodio')
logger.error('ERROR al procesar el título en Findvideos del Canal: ' + item.channel + ' / ' + item.title)
logger.error(traceback.format_exc())
item_res = item.clone() #Si ha habido un error, se devuelve el Item original
#Si el usuario ha activado la opción "emergency_urls_torrents", se descargarán los archivos .torrent de cada título
else: #Si se han cacheado con éxito los enlaces...
logger.debug('HOLA')
logger.debug(item_res.emergency_urls)
try:
channel_bis = generictools.verify_channel(item.channel)
if config.get_setting("emergency_urls_torrents", channel_bis) and item_res.emergency_urls and path != None:
@@ -760,13 +766,15 @@ def emergency_urls(item, channel=None, path=None):
item_res.emergency_urls[0][i-1] = path_real.replace(videolibrary_path, '') #se guarda el "path" relativo
i += 1
except:
logger.error('ERROR al cachear el .torrent de: ' + item.channel + ' / ' + item.title)
logger.error(traceback.format_exc())
item_res = item.clone() #Si ha habido un error, se devuelve el Item original
#logger.debug(item_res.emergency_urls)
return item_res #Devolvemos el Item actualizado con los enlaces de emergencia
def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, lookup=False):
def caching_torrents(url, torrents_path=None, timeout=10, lookup=False, data_torrent=False):
if torrents_path != None:
logger.info("path = " + torrents_path)
else:
@@ -774,98 +782,80 @@ def caching_torrents(url, torrents_path=None, decode_flag=False, timeout=10, loo
import urllib
import re
from core import httptools
torrent_file = ''
"""
Descarga en el path recibido el .torrent de la url recibida, y pasa el decode
Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito
"""
def decode(text):
try:
src = tokenize(text)
data = decode_item(src.next, src.next())
for token in src: # look for more tokens
raise SyntaxError("trailing junk")
except (AttributeError, ValueError, StopIteration):
try:
data = data
except:
data = src
return data
def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
i = 0
while i < len(text):
m = match(text, i)
s = m.group(m.lastindex)
i = m.end()
if m.lastindex == 2:
yield "s"
yield text[i:i + int(s)]
i = i + int(s)
else:
yield s
def decode_item(next, token):
if token == "i":
# integer: "i" value "e"
data = int(next())
if next() != "e":
raise ValueError
elif token == "s":
# string: "s" value (virtual tokens)
data = next()
elif token == "l" or token == "d":
# container: "l" (or "d") values "e"
data = []
tok = next()
while tok != "e":
data.append(decode_item(next, tok))
tok = next()
if token == "d":
data = dict(zip(data[0::2], data[1::2]))
else:
raise ValueError
return data
if torrents_path == None:
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
if not videolibrary_path:
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path de descarga temporal
if '.torrent' not in torrents_path:
torrents_path += '.torrent' #path para dejar el .torrent
torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
if url.endswith(".rar"): #No es un archivo .torrent
logger.error('No es un archivo Torrent: ' + url)
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
#Módulo PRINCIPAL
try:
if lookup:
torrents_path = lookup
else:
if '.torrent' not in torrents_path:
torrents_path += '.torrent' #path para dejar el .torrent
torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
response = httptools.downloadpage(url, timeout=timeout) #Descargamos el .torrent
if not response.sucess:
logger.error('Archivo .torrent no encontrado: ' + url)
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
torrent_file = response.data
if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso
response = httptools.downloadpage("http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(), timeout=timeout)
if not response.sucess:
logger.error('Archivo .torrent no encontrado: ' + url)
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
torrent_file = response.data
if decode_flag:
torrent_file = decode(torrent_file) #decodificamos el .torrent
if not scrapertools.find_single_match(torrent_file, '^d\d+:\w+\d+:'): #No es un archivo .torrent (RAR, ZIP, HTML,..., vacío)
logger.error('No es un archivo Torrent: ' + url)
torrents_path = ''
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío
if not lookup:
filetools.write(torrents_path_encode, torrent_file) #Salvamos el .torrent
if not filetools.write(torrents_path_encode, torrent_file): #Salvamos el .torrent
logger.error('ERROR: Archivo .torrent no escrito: ' + torrents_path_encode)
torrents_path = '' #Si hay un error, devolvemos el "path" vacío
torrent_file = '' #... y el buffer del .torrent
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path
except:
torrents_path = '' #Si hay un error, devolvemos el "path" vacío
torrent_file = '' #... y el buffer del .torrent
logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode)
logger.error(traceback.format_exc())
#logger.debug(torrents_path)
if data_torrent:
return (torrents_path, torrent_file)
return torrents_path
def verify_url_torrent(url, decode_flag=False, timeout=5):
def verify_url_torrent(url, timeout=5):
"""
Verifica si el archivo .torrent al que apunta la url está disponible, descargándolo en un area temporal
Entrada: url
@@ -874,12 +864,8 @@ def verify_url_torrent(url, decode_flag=False, timeout=5):
if not url or url == 'javascript:;': #Si la url viene vacía...
return False #... volvemos con error
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode
if torrents_path: #Si ha tenido éxito...
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent
if torrents_path: #Si ha tenido éxito...
return True
try:
torrents_path = caching_torrents(url, timeout=timeout, lookup=True) #Descargamos el .torrent, sin decode
if torrents_path: #Si ha tenido éxito...
return True
except:
return False #en caso de error, False
else:
return False

View File

@@ -6,6 +6,7 @@
import os
import time
import threading
import traceback
from platformcode import config, logger, platformtools
@@ -140,6 +141,7 @@ def check_addon_updates(verbose=False):
except:
logger.error('Error al comprobar actualizaciones del addon!')
logger.error(traceback.format_exc())
if verbose:
platformtools.dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones')
return False

View File

@@ -3,7 +3,7 @@
# Service for updating new episodes on library series
# ------------------------------------------------------------
import datetime, imp, math, threading
import datetime, imp, math, threading, traceback
from core import channeltools, filetools, videolibrarytools
from platformcode import config, logger
@@ -32,7 +32,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
serie.category = category
serie, it, overwrite = generictools.redirect_clone_newpct1(serie, head_nfo, it, path, overwrite)
except:
pass
logger.error(traceback.format_exc())
channel_enabled = channeltools.is_enabled(serie.channel)
@@ -89,7 +89,7 @@ def update(path, p_dialog, i, t, serie, overwrite):
from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
except:
pass
logger.error(traceback.format_exc())
return insertados_total > 0
@@ -127,7 +127,7 @@ def check_for_update(overwrite=True):
try:
serie, serie, overwrite_forced = generictools.redirect_clone_newpct1(serie, head_nfo, serie, path, overwrite, lookup=True)
except:
pass
logger.error(traceback.format_exc())
if overwrite_forced == True:
overwrite = True
serie.update_next = ''
@@ -143,7 +143,7 @@ def check_for_update(overwrite=True):
if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora
serie, estado = videolibrary.verify_playcount_series(serie, path) #También se pasa si falta un PlayCount por completo
except:
pass
logger.error(traceback.format_exc())
else:
if estado: #Si ha tenido éxito la actualización...
estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca
@@ -159,7 +159,7 @@ def check_for_update(overwrite=True):
from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_content_as_watched_on_alfa(path + '/tvshow.nfo')
except:
pass
logger.error(traceback.format_exc())
continue