Traduzioni Client Torrent

This commit is contained in:
Alhaziel01
2020-04-18 17:36:27 +02:00
parent 2d3527b38a
commit 3b850f7efd
4 changed files with 251 additions and 138 deletions
+1 -1
View File
@@ -69,7 +69,7 @@ if DOWNLOAD_LIMIT:
else: else:
DOWNLOAD_LIMIT = 0 DOWNLOAD_LIMIT = 0
UPLOAD_LIMIT = 100 * 1024 UPLOAD_LIMIT = 100 * 1024
msg_header = 'KoD Client Torrent MCT' msg_header = 'MCT Client Torrent'
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None): def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
+59
View File
@@ -5923,6 +5923,65 @@ msgctxt "#70789"
msgid "* Change by opening the settings from KoD main menu" msgid "* Change by opening the settings from KoD main menu"
msgstr "" msgstr ""
msgctxt "#70790"
msgid "RAR download in progress"
msgstr ""
msgctxt "#70791"
msgid "A RAR file was detected in the download, but you have not installed the UnRAR extractor.\nDo you want to download it anyway?"
msgstr ""
msgctxt "#70792"
msgid "Delete downloaded files?"
msgstr ""
msgctxt "#70793"
msgid "Starting extraction..."
msgstr ""
msgctxt "#70794"
msgid "Enter the password (Look in %s)"
msgstr ""
msgctxt "#70795"
msgid "Extracted"
msgstr ""
msgctxt "#70796"
msgid "Error opening RAR File"
msgstr ""
msgctxt "#70797"
msgid "The RAR file is empty"
msgstr ""
msgctxt "#70798"
msgid "Or does not contain valid archives"
msgstr ""
msgctxt "#70799"
msgid "Extraction error"
msgstr ""
msgctxt "#70800"
msgid "Archive with errors"
msgstr ""
msgctxt "#70801"
msgid "Extract without playing"
msgstr ""
msgctxt "#70802"
msgid "Wait some minutes..."
msgstr ""
msgctxt "#70803"
msgid "Extracting files..."
msgstr ""
msgctxt "#70804"
msgid "Next extraction..."
msgstr ""
# DNS start [ settings and declaration ] # DNS start [ settings and declaration ]
msgctxt "#707401" msgctxt "#707401"
+59
View File
@@ -5923,6 +5923,65 @@ msgctxt "#70789"
msgid "* Change by opening the settings from KoD main menu" msgid "* Change by opening the settings from KoD main menu"
msgstr "* Cambia aprendo le impostazioni dal menu principale di KoD" msgstr "* Cambia aprendo le impostazioni dal menu principale di KoD"
msgctxt "#70790"
msgid "RAR download in progress"
msgstr "Download RAR in corso"
msgctxt "#70791"
msgid "A RAR file was detected in the download, but you have not installed the UnRAR extractor.\nDo you want to download it anyway?"
msgstr "Un file RAR è stato rilevato nel download, ma non hai installato l'estrattore UnRAR.\nVuoi scaricarlo in ogni caso?"
msgctxt "#70792"
msgid "Delete downloaded files?"
msgstr "Cancellare i file scaricati?"
msgctxt "#70793"
msgid "Starting extraction..."
msgstr "Avvio dell'estrazione..."
msgctxt "#70794"
msgid "Enter the password (Look in %s)"
msgstr "Inserisci la password (Cerca in %s)"
msgctxt "#70795"
msgid "Extracted"
msgstr "Estratto"
msgctxt "#70796"
msgid "Error opening RAR File"
msgstr "Errore durante l'apertura del file RAR"
msgctxt "#70797"
msgid "The RAR file is empty"
msgstr "Il file RAR è vuoto"
msgctxt "#70798"
msgid "Or does not contain valid archives"
msgstr "O non contiene archivi validi"
msgctxt "#70799"
msgid "Extraction error"
msgstr "Errore di estrazione"
msgctxt "#70800"
msgid "Archive with errors"
msgstr "Archivio con errori"
msgctxt "#70801"
msgid "Extract without playing"
msgstr "Estrarre senza riprodurre"
msgctxt "#70802"
msgid "Wait some minutes..."
msgstr "Aspetta qualche minuto..."
msgctxt "#70803"
msgid "Extracting files..."
msgstr "Estrazione dei files..."
msgctxt "#70804"
msgid "Next extraction..."
msgstr "Estrazione successiva..."
# DNS start [ settings and declaration ] # DNS start [ settings and declaration ]
msgctxt "#707401" msgctxt "#707401"
+132 -137
View File
@@ -61,8 +61,8 @@ trackers = [
# Returns an array of possible video url's from the page_url # Returns an array of possible video url's from the page_url
def get_video_url(page_url, premium=False, user="", password="", video_password=""): def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("server=torrent, la url es la buena") logger.info("server=torrent, the url is the good")
if page_url.startswith("magnet:"): if page_url.startswith("magnet:"):
video_urls = [["magnet: [torrent]", page_url]] video_urls = [["magnet: [torrent]", page_url]]
else: else:
@@ -92,12 +92,12 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
t_hash = '' t_hash = ''
if referer: if referer:
headers.update({'Content-Type': 'application/x-www-form-urlencoded', 'Referer': referer}) #Necesario para el Post del .Torrent headers.update({'Content-Type': 'application/x-www-form-urlencoded', 'Referer': referer}) #Necesario para el Post del .Torrent
""" """
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
""" """
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
if torrents_path == None: if torrents_path == None:
if not videolibrary_path: if not videolibrary_path:
@@ -110,7 +110,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
torrents_path += '.torrent' #path para dejar el .torrent torrents_path += '.torrent' #path para dejar el .torrent
#torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path #torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
torrents_path_encode = torrents_path torrents_path_encode = torrents_path
#if url.endswith(".rar") or url.startswith("magnet:"): #No es un archivo .torrent #if url.endswith(".rar") or url.startswith("magnet:"): #No es un archivo .torrent
if url.endswith(".rar"): #No es un archivo .torrent if url.endswith(".rar"): #No es un archivo .torrent
logger.error('No es un archivo Torrent: ' + url) logger.error('No es un archivo Torrent: ' + url)
@@ -118,7 +118,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) 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
try: try:
#Descargamos el .torrent #Descargamos el .torrent
if url.startswith("magnet:"): if url.startswith("magnet:"):
@@ -156,17 +156,17 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
#Si es un archivo .ZIP tratamos de extraer el contenido #Si es un archivo .ZIP tratamos de extraer el contenido
if torrent_file.startswith("PK"): if torrent_file.startswith("PK"):
logger.info('Es un archivo .ZIP: ' + url) logger.info("it's a zip archive: " + url)
torrents_path_zip = filetools.join(videolibrary_path, 'temp_torrents_zip') #Carpeta de trabajo torrents_path_zip = filetools.join(videolibrary_path, 'temp_torrents_zip') #Carpeta de trabajo
torrents_path_zip = filetools.encode(torrents_path_zip) torrents_path_zip = filetools.encode(torrents_path_zip)
torrents_path_zip_file = filetools.join(torrents_path_zip, 'temp_torrents_zip.zip') #Nombre del .zip torrents_path_zip_file = filetools.join(torrents_path_zip, 'temp_torrents_zip.zip') #Nombre del .zip
import time import time
filetools.rmdirtree(torrents_path_zip) #Borramos la carpeta temporal filetools.rmdirtree(torrents_path_zip) #Borramos la carpeta temporal
time.sleep(1) #Hay que esperar, porque si no da error time.sleep(1) #Hay que esperar, porque si no da error
filetools.mkdir(torrents_path_zip) #La creamos de nuevo filetools.mkdir(torrents_path_zip) #La creamos de nuevo
if filetools.write(torrents_path_zip_file, torrent_file_uncoded, vfs=VFS): #Salvamos el .zip if filetools.write(torrents_path_zip_file, torrent_file_uncoded, vfs=VFS): #Salvamos el .zip
torrent_file = '' #Borramos el contenido en memoria torrent_file = '' #Borramos el contenido en memoria
try: #Extraemos el .zip try: #Extraemos el .zip
@@ -177,7 +177,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
import xbmc import xbmc
xbmc.executebuiltin('XBMC.Extract("%s", "%s")' % (torrents_path_zip_file, torrents_path_zip)) xbmc.executebuiltin('XBMC.Extract("%s", "%s")' % (torrents_path_zip_file, torrents_path_zip))
time.sleep(1) time.sleep(1)
for root, folders, files in filetools.walk(torrents_path_zip): #Recorremos la carpeta para leer el .torrent for root, folders, files in filetools.walk(torrents_path_zip): #Recorremos la carpeta para leer el .torrent
for file in files: for file in files:
if file.endswith(".torrent"): if file.endswith(".torrent"):
@@ -196,20 +196,20 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) 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
#Calculamos el Hash del Torrent y modificamos el path #Calculamos el Hash del Torrent y modificamos el path
import bencode, hashlib import bencode, hashlib
decodedDict = bencode.bdecode(torrent_file_uncoded) decodedDict = bencode.bdecode(torrent_file_uncoded)
if not PY3: if not PY3:
t_hash = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest() t_hash = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest()
else: else:
t_hash = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest() t_hash = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest()
if t_hash: if t_hash:
torrents_path = filetools.join(filetools.dirname(torrents_path), t_hash + '.torrent') torrents_path = filetools.join(filetools.dirname(torrents_path), t_hash + '.torrent')
torrents_path_encode = filetools.join(filetools.dirname(torrents_path_encode), t_hash + '.torrent') torrents_path_encode = filetools.join(filetools.dirname(torrents_path_encode), t_hash + '.torrent')
#Salvamos el .torrent #Salvamos el .torrent
if not lookup: if not lookup:
if not filetools.write(torrents_path_encode, torrent_file_uncoded, vfs=VFS): if not filetools.write(torrents_path_encode, torrent_file_uncoded, vfs=VFS):
@@ -224,16 +224,16 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
torrent_file = '' #... y el buffer del .torrent torrent_file = '' #... y el buffer del .torrent
logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode) logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode)
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
#logger.debug(torrents_path) #logger.debug(torrents_path)
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) return (torrents_path, torrent_file)
return torrents_path return torrents_path
def magnet2torrent(magnet, headers={}): def magnet2torrent(magnet, headers={}):
logger.info() logger.info()
torrent_file = '' torrent_file = ''
info = '' info = ''
post = '' post = ''
@@ -276,7 +276,7 @@ def magnet2torrent(magnet, headers={}):
'trackers': trackers, 'trackers': trackers,
'storage_mode': lt.storage_mode_t.storage_mode_allocate 'storage_mode': lt.storage_mode_t.storage_mode_allocate
} # Creamos los parámetros de la sesión } # Creamos los parámetros de la sesión
h = lt.add_magnet_uri(ses, magnet, params) # Abrimos la sesión h = lt.add_magnet_uri(ses, magnet, params) # Abrimos la sesión
i = 0 i = 0
while not h.has_metadata() and not xbmc.abortRequested: # Esperamos mientras Libtorrent abre la sesión while not h.has_metadata() and not xbmc.abortRequested: # Esperamos mientras Libtorrent abre la sesión
@@ -287,14 +287,14 @@ def magnet2torrent(magnet, headers={}):
if i > 5: if i > 5:
LIBTORRENT_PATH = '' # No puede convertir el magnet LIBTORRENT_PATH = '' # No puede convertir el magnet
break break
if LIBTORRENT_PATH: if LIBTORRENT_PATH:
info = h.get_torrent_info() # Obtiene la información del .torrent info = h.get_torrent_info() # Obtiene la información del .torrent
torrent_file = lt.bencode(lt.create_torrent(info).generate()) # Obtiene los datos del .torrent torrent_file = lt.bencode(lt.create_torrent(info).generate()) # Obtiene los datos del .torrent
ses.remove_torrent(h) # Desactiva Libtorrent ses.remove_torrent(h) # Desactiva Libtorrent
filetools.rmdirtree(LIBTORRENT_MAGNET_PATH) # Elimina la carpeta temporal filetools.rmdirtree(LIBTORRENT_MAGNET_PATH) # Elimina la carpeta temporal
return torrent_file return torrent_file
def verify_url_torrent(url, timeout=5): def verify_url_torrent(url, timeout=5):
@@ -316,7 +316,7 @@ def verify_url_torrent(url, timeout=5):
# Reproductor Cliente Torrent propio (libtorrent) # Reproductor Cliente Torrent propio (libtorrent)
def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None): def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None):
logger.info() logger.info()
# Importamos el cliente # Importamos el cliente
from btserver import Client from btserver import Client
@@ -334,7 +334,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not save_path_videos: if not save_path_videos:
save_path_videos = filetools.join(config.get_data_path(), 'downloads', 'BT-torrents') save_path_videos = filetools.join(config.get_data_path(), 'downloads', 'BT-torrents')
config.set_setting("bt_download_path", filetools.join(config.get_data_path(), 'downloads'), server="torrent") config.set_setting("bt_download_path", filetools.join(config.get_data_path(), 'downloads'), server="torrent")
UNRAR = config.get_setting("unrar_path", server="torrent", default="") UNRAR = config.get_setting("unrar_path", server="torrent", default="")
BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True) BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True)
RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True) RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True)
@@ -351,7 +351,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
else: else:
DOWNLOAD_LIMIT = 0 DOWNLOAD_LIMIT = 0
UPLOAD_LIMIT = 100 UPLOAD_LIMIT = 100
torr_client = 'BT' torr_client = 'BT'
rar_file = '' rar_file = ''
rar_names = [] rar_names = []
@@ -366,7 +366,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
'.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
'.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip'] '.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip']
for entry in rar_files: for entry in rar_files:
for file, path in list(entry.items()): for file, path in list(entry.items()):
if file == 'path' and '.rar' in str(path): if file == 'path' and '.rar' in str(path):
@@ -389,16 +389,15 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not video_file and mediaurl.startswith('magnet'): if not video_file and mediaurl.startswith('magnet'):
video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&)dn=([^\&]+)\&')) video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&)dn=([^\&]+)\&'))
erase_file_path = filetools.join(save_path_videos, video_file) erase_file_path = filetools.join(save_path_videos, video_file)
if rar and RAR and not UNRAR: if rar and RAR and not UNRAR:
if not platformtools.dialog_yesno(msg_header, 'Se ha detectado un archivo .RAR en la descarga', \ if not platformtools.dialog_yesno(msg_header, config.get_localized_string(70791)):
'No tiene instalado el extractor UnRAR', '¿Desea descargarlo en cualquier caso?'):
return return
# Iniciamos el cliente: # Iniciamos el cliente:
c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10, c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10,
temp_path=save_path_videos, print_status=debug, auto_delete=False) temp_path=save_path_videos, print_status=debug, auto_delete=False)
activo = True activo = True
finalizado = False finalizado = False
dp_cerrado = True dp_cerrado = True
@@ -406,10 +405,9 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
# Mostramos el progreso # Mostramos el progreso
if rar and RAR and BACKGROUND: # Si se descarga un RAR... if rar and RAR and BACKGROUND: # Si se descarga un RAR...
progreso = platformtools.dialog_progress_bg(msg_header) progreso = platformtools.dialog_progress_bg(msg_header)
platformtools.dialog_notification("Descarga de RAR en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(70790), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
else: else:
progreso = platformtools.dialog_progress('Alfa %s Cliente Torrent' % torr_client, '') progreso = platformtools.dialog_progress('%s Torrent Client' % torr_client, '')
dp_cerrado = False dp_cerrado = False
# Mientras el progreso no sea cancelado ni el cliente cerrado # Mientras el progreso no sea cancelado ni el cliente cerrado
@@ -441,7 +439,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
time.sleep(1) time.sleep(1)
if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()): if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()):
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
dp_cerrado = True dp_cerrado = True
@@ -477,7 +475,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if ((s.pieces_sum >= BUFFER or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \ if ((s.pieces_sum >= BUFFER or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \
(s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \ (s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \
in s.str_state) and (rar or bkg_user)) and not played: in s.str_state) and (rar or bkg_user)) and not played:
if rar and RAR and UNRAR: if rar and RAR and UNRAR:
c.stop() c.stop()
activo = False activo = False
@@ -495,7 +493,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
elif bkg_user: elif bkg_user:
finalizado = True finalizado = True
break break
# Cerramos el progreso # Cerramos el progreso
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
@@ -506,8 +504,8 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background
bkg_auto = True bkg_auto = True
while xbmc_player.isPlaying() and not xbmc.abortRequested: while xbmc_player.isPlaying() and not xbmc.abortRequested:
time.sleep(3) time.sleep(3)
# Obtenemos el playlist del torrent # Obtenemos el playlist del torrent
#videourl = c.get_play_list() #videourl = c.get_play_list()
if not rar_res: # Es un Magnet ? if not rar_res: # Es un Magnet ?
@@ -528,20 +526,20 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
# Marcamos como reproducido para que no se vuelva a iniciar # Marcamos como reproducido para que no se vuelva a iniciar
played = True played = True
mark_auto_as_watched(item) mark_auto_as_watched(item)
# Y esperamos a que el reproductor se cierre # Y esperamos a que el reproductor se cierre
bkg_auto = True bkg_auto = True
dp_cerrado = True dp_cerrado = True
while xbmc_player.isPlaying() and not xbmc.abortRequested: while xbmc_player.isPlaying() and not xbmc.abortRequested:
time.sleep(1) time.sleep(1)
if xbmc.getCondVisibility('Player.Playing'): if xbmc.getCondVisibility('Player.Playing'):
if not dp_cerrado: if not dp_cerrado:
dp_cerrado = True dp_cerrado = True
progreso.close() progreso.close()
if xbmc.getCondVisibility('Player.Paused') and not rar_res: if xbmc.getCondVisibility('Player.Paused') and not rar_res:
if not c.closed: s = c.status if not c.closed: s = c.status
txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
@@ -555,11 +553,11 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
progreso = xbmcgui.DialogProgressBG() progreso = xbmcgui.DialogProgressBG()
progreso.create(msg_header) progreso.create(msg_header)
progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2) progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2)
if not dp_cerrado: if not dp_cerrado:
dp_cerrado = True dp_cerrado = True
progreso.close() progreso.close()
# Miramos si se ha completado la descarga para borrar o no los archivos # Miramos si se ha completado la descarga para borrar o no los archivos
if activo: if activo:
s = c.status s = c.status
@@ -567,7 +565,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
finalizado = True finalizado = True
break break
if platformtools.dialog_yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032)): if not platformtools.dialog_yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032)):
progreso = platformtools.dialog_progress(msg_header, '') progreso = platformtools.dialog_progress(msg_header, '')
dp_cerrado = False dp_cerrado = False
break break
@@ -579,18 +577,18 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
progreso.update(s.buffer, txt, txt2) progreso.update(s.buffer, txt, txt2)
dp_cerrado = False dp_cerrado = False
continue continue
# Cuando este cerrado, Volvemos a mostrar el dialogo # Cuando este cerrado, Volvemos a mostrar el dialogo
if not (rar and bkg_user): if not (rar and bkg_user):
progreso = platformtools.dialog_progress(msg_header, '') progreso = platformtools.dialog_progress(msg_header, '')
progreso.update(s.buffer, txt, txt2, txt3) progreso.update(s.buffer, txt, txt2, txt3)
dp_cerrado = False dp_cerrado = False
break break
except: except:
logger.error(traceback.format_exc(1)) logger.error(traceback.format_exc(1))
return return
if not dp_cerrado: if not dp_cerrado:
if rar or bkg_user: if rar or bkg_user:
progreso.update(100, config.get_localized_string(70200), " ") progreso.update(100, config.get_localized_string(70200), " ")
@@ -606,11 +604,11 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
dp_cerrado = True dp_cerrado = True
# Y borramos los archivos de descarga restantes # Y borramos los archivos de descarga restantes
time.sleep(1) time.sleep(1)
if filetools.exists(erase_file_path) and not bkg_user: if filetools.exists(erase_file_path) and not bkg_user:
if finalizado and not platformtools.dialog_yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)'): if finalizado and not platformtools.dialog_yesno(msg_header, config.get_localized_string(70792)):
return return
log("##### erase_file_path: %s" % erase_file_path) log("##### erase_file_path: %s" % erase_file_path)
for x in range(10): for x in range(10):
@@ -629,7 +627,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
def call_torrent_via_web(mediaurl, torr_client): def call_torrent_via_web(mediaurl, torr_client):
# Usado para llamar a los clientes externos de Torrents para automatizar la descarga de archivos que contienen .RAR # Usado para llamar a los clientes externos de Torrents para automatizar la descarga de archivos que contienen .RAR
logger.info() logger.info()
post = '' post = ''
ELEMENTUMD_HOST = "http://localhost:65220" ELEMENTUMD_HOST = "http://localhost:65220"
if torr_client == 'elementum': if torr_client == 'elementum':
@@ -642,7 +640,7 @@ def call_torrent_via_web(mediaurl, torr_client):
local_host = {"quasar": ["http://localhost:65251/torrents/", "add?uri"], \ local_host = {"quasar": ["http://localhost:65251/torrents/", "add?uri"], \
"elementum": ["%s/torrents/" % ELEMENTUMD_HOST, "add"]} "elementum": ["%s/torrents/" % ELEMENTUMD_HOST, "add"]}
if torr_client == "quasar": if torr_client == "quasar":
uri = '%s%s=%s' % (local_host[torr_client][0], local_host[torr_client][1], mediaurl) uri = '%s%s=%s' % (local_host[torr_client][0], local_host[torr_client][1], mediaurl)
elif torr_client == "elementum": elif torr_client == "elementum":
@@ -658,9 +656,9 @@ def call_torrent_via_web(mediaurl, torr_client):
def mark_auto_as_watched(item): def mark_auto_as_watched(item):
time_limit = time.time() + 150 #Marcamos el timepo máx. de buffering time_limit = time.time() + 150 #Marcamos el timepo máx. de buffering
while not platformtools.is_playing() and time.time() < time_limit: #Esperamos mientra buffera while not platformtools.is_playing() and time.time() < time_limit: #Esperamos mientra buffera
time.sleep(5) #Repetimos cada intervalo time.sleep(5) #Repetimos cada intervalo
#logger.debug(str(time_limit)) #logger.debug(str(time_limit))
if item.subtitle: if item.subtitle:
@@ -679,7 +677,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
logger.info() logger.info()
from subprocess import Popen, PIPE, STDOUT from subprocess import Popen, PIPE, STDOUT
# Analizamos los archivos dentro del .torrent # Analizamos los archivos dentro del .torrent
rar = False rar = False
rar_names = [] rar_names = []
@@ -700,10 +698,10 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
rar = True rar = True
elif file == '__name': elif file == '__name':
folder = path folder = path
if not folder: # Si no se detecta el folder... if not folder: # Si no se detecta el folder...
return ('', '', '') # ... no podemos hacer nada return ('', '', '') # ... no podemos hacer nada
if not rar_names: if not rar_names:
return ('', '', folder) return ('', '', folder)
rar_file = '%s/%s' % (folder, rar_names[0]) rar_file = '%s/%s' % (folder, rar_names[0])
@@ -726,7 +724,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if not save_path_videos: # No hay path de descarga? if not save_path_videos: # No hay path de descarga?
return ('', '', folder) # Volvemos return ('', '', folder) # Volvemos
log("##### save_path_videos: %s" % save_path_videos) log("##### save_path_videos: %s" % save_path_videos)
# Si es nueva descarga, ponemos un archivo de control para reiniciar el UNRar si ha habido cancelación de Kodi # Si es nueva descarga, ponemos un archivo de control para reiniciar el UNRar si ha habido cancelación de Kodi
# Si ya existe el archivo (llamada), se reinicia el proceso de UNRar donde se quedó # Si ya existe el archivo (llamada), se reinicia el proceso de UNRar donde se quedó
if rar_control: if rar_control:
@@ -751,17 +749,17 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if torr_client == 'quasar': # Quasar no copia en .torrent if torr_client == 'quasar': # Quasar no copia en .torrent
ret = filetools.copy(item.url, filetools.join(save_path_videos, 'torrents', \ ret = filetools.copy(item.url, filetools.join(save_path_videos, 'torrents', \
filetools.basename(item.url)), silent=True) filetools.basename(item.url)), silent=True)
# Esperamos mientras el .torrent se descarga. Verificamos si el .RAR está descargado al completo # Esperamos mientras el .torrent se descarga. Verificamos si el .RAR está descargado al completo
platformtools.dialog_notification("Automatizando la extracción", "Acepta descargar el archivo RAR y te iremos guiando...", time=10000) platformtools.dialog_notification(config.get_localized_string(70803), "", time=10000)
# Plan A: usar el monitor del cliente torrent para ver el status de la descarga # Plan A: usar el monitor del cliente torrent para ver el status de la descarga
loop = 3600 # Loop de 10 horas hasta crear archivo loop = 3600 # Loop de 10 horas hasta crear archivo
wait_time = 10 wait_time = 10
time.sleep(wait_time) time.sleep(wait_time)
fast = False fast = False
ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control)) ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control))
for x in range(loop): for x in range(loop):
if xbmc.abortRequested: if xbmc.abortRequested:
return ('', '', folder) return ('', '', folder)
@@ -773,27 +771,26 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
return ('', '', folder) # Volvemos return ('', '', folder) # Volvemos
if (torr_client in ['quasar'] or torr_client in ['elementum']) and not \ if (torr_client in ['quasar'] or torr_client in ['elementum']) and not \
torr_data['label'].startswith('0.00%') and not fast: torr_data['label'].startswith('0.00%') and not fast:
platformtools.dialog_notification("Descarga en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(60200), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
fast = True fast = True
if not torr_data['label'].startswith('100.00%'): if not torr_data['label'].startswith('100.00%'):
log("##### Descargado: %s, ID: %s" % (scrapertools.find_single_match(torr_data['label'], '(^.*?\%)'), index)) log("##### Downloading: %s, ID: %s" % (scrapertools.find_single_match(torr_data['label'], '(^.*?\%)'), index))
time.sleep(wait_time) time.sleep(wait_time)
continue continue
update_rar_control(rar_control['download_path'], status='downloaded') update_rar_control(rar_control['download_path'], status='downloaded')
log("##### Torrent FINALIZADO: %s" % str(folder)) log("##### Torrent FINALIZED: %s" % str(folder))
return (rar_file, save_path_videos, folder) return (rar_file, save_path_videos, folder)
# Plan B: monitorizar con UnRAR si los archivos se han desacargado por completo # Plan B: monitorizar con UnRAR si los archivos se han desacargado por completo
unrar_path = config.get_setting("unrar_path", server="torrent", default="") unrar_path = config.get_setting("unrar_path", server="torrent", default="")
if not unrar_path: # Si Unrar no está instalado... if not unrar_path: # Si Unrar no está instalado...
return ('', '', folder) # ... no podemos hacer nada return ('', '', folder) # ... no podemos hacer nada
cmd = [] cmd = []
for rar_name in rar_names: # Preparamos por si es un archivo multiparte for rar_name in rar_names: # Preparamos por si es un archivo multiparte
cmd.append(['%s' % unrar_path, 'l', '%s' % filetools.join(save_path_videos, folder, rar_name)]) cmd.append(['%s' % unrar_path, 'l', '%s' % filetools.join(save_path_videos, folder, rar_name)])
creationflags = '' creationflags = ''
if xbmc.getCondVisibility("system.platform.Windows"): if xbmc.getCondVisibility("system.platform.Windows"):
creationflags = 0x08000000 creationflags = 0x08000000
@@ -834,7 +831,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if returncode == '0': # Ya se ha descargado... parte ... if returncode == '0': # Ya se ha descargado... parte ...
dl_files += 1 dl_files += 1
part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)') part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)')
log("##### Torrent descargando: %s, %s" % (part_name, str(returncode))) log("##### Torrent downloading: %s, %s" % (part_name, str(returncode)))
if dl_files == len(cmd): # ... o todo if dl_files == len(cmd): # ... o todo
fast = True fast = True
rar = False rar = False
@@ -848,8 +845,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
#if loop == 30 and y == len(responses): # Si es la primera vez en proceso ... #if loop == 30 and y == len(responses): # Si es la primera vez en proceso ...
if loop == 30 and y == 1: # Si es la primera vez en proceso ... if loop == 30 and y == 1: # Si es la primera vez en proceso ...
if torr_client in ['quasar']: if torr_client in ['quasar']:
platformtools.dialog_notification("Descarga en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(60200), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
loop_change = 3600 # ... pasamos a un loop de 10 horas loop_change = 3600 # ... pasamos a un loop de 10 horas
elif loop <= 6: # Recuerado el error desconocido elif loop <= 6: # Recuerado el error desconocido
loop_change = 3600 # ... pasamos a un loop de 10 horas loop_change = 3600 # ... pasamos a un loop de 10 horas
@@ -857,16 +853,16 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
break break
elif returncode == '1': # Ha alcanzado el fin de archivo ??? pasamos elif returncode == '1': # Ha alcanzado el fin de archivo ??? pasamos
part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)') part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)')
log("##### Torrent descargando: %s, %s" % (part_name, str(returncode))) log("##### Torrent downloading: %s, %s" % (part_name, str(returncode)))
else: # No entendemos el error else: # No entendemos el error
loop_change = loop_error # ... pasamos a un loop de 1 minutos para reintentar loop_change = loop_error # ... pasamos a un loop de 1 minutos para reintentar
loop_error += -1 loop_error += -1
break #... abortamos break #... abortamos
if str(returncode) in ['0', '6', '10']: if str(returncode) in ['0', '6', '10']:
log("##### Torrent descargando: %s" % str(returncode)) log("##### Torrent downloading: %s" % str(returncode))
else: else:
log("##### Torrent descargando: %s, %s" % (str(out__), str(returncode))) log("##### Torrent downloading: %s, %s" % (str(out__), str(returncode)))
if not rar or fast: if not rar or fast:
fast = False fast = False
break break
@@ -876,14 +872,14 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
break break
if str(returncode) == '0': if str(returncode) == '0':
log("##### Torrent FINALIZADO: %s" % str(returncode)) log("##### Torrent FINALIZED: %s" % str(returncode))
else: else:
rar_file = '' rar_file = ''
logger.error('##### Torrent NO DESCARGADO: %s, %s' % (str(out__), str(returncode))) logger.error('##### Torrent NO DESCARGADO: %s, %s' % (str(out__), str(returncode)))
return (rar_file, save_path_videos, folder) return (rar_file, save_path_videos, folder)
def get_tclient_data(folder, torr_client): def get_tclient_data(folder, torr_client):
# Monitoriza el estado de descarga del torrent en Quasar y Elementum # Monitoriza el estado de descarga del torrent en Quasar y Elementum
@@ -901,7 +897,7 @@ def get_tclient_data(folder, torr_client):
torr_id = '' torr_id = ''
x = 0 x = 0
y = '' y = ''
try: try:
data = httptools.downloadpage(local_host[torr_client], timeout=5, alfa_s=True).data data = httptools.downloadpage(local_host[torr_client], timeout=5, alfa_s=True).data
if not data: if not data:
@@ -920,7 +916,7 @@ def get_tclient_data(folder, torr_client):
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
return '', local_host[torr_client], 0 return '', local_host[torr_client], 0
if torr_id: if torr_id:
y = torr_id y = torr_id
else: else:
@@ -931,9 +927,9 @@ def get_tclient_data(folder, torr_client):
def extract_files(rar_file, save_path_videos, password, dp, item=None, \ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
torr_client=None, rar_control={}, size='RAR', mediaurl=''): torr_client=None, rar_control={}, size='RAR', mediaurl=''):
logger.info() logger.info()
from platformcode import custom_code from platformcode import custom_code
if not rar_control: if not rar_control:
rar_control = { rar_control = {
'torr_client': torr_client, 'torr_client': torr_client,
@@ -949,12 +945,12 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
'mediaurl': mediaurl 'mediaurl': mediaurl
} }
ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control)) ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control))
#reload(sys) #reload(sys)
#sys.setdefaultencoding('utf-8') #sys.setdefaultencoding('utf-8')
sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\ sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\
.replace('/unrar', '').replace('\\unrar,exe', '')) .replace('/unrar', '').replace('\\unrar,exe', ''))
import rarfile import rarfile
# Verificamos si hay path para UnRAR # Verificamos si hay path para UnRAR
@@ -965,7 +961,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
return rar_file, False, '', '' return rar_file, False, '', ''
log("##### unrar_path: %s" % rarfile.UNRAR_TOOL) log("##### unrar_path: %s" % rarfile.UNRAR_TOOL)
rarfile.DEFAULT_CHARSET = 'utf-8' rarfile.DEFAULT_CHARSET = 'utf-8'
# Preparamos un path alternativo más corto para no sobrepasar la longitud máxima # Preparamos un path alternativo más corto para no sobrepasar la longitud máxima
video_path = '' video_path = ''
if item: if item:
@@ -978,7 +974,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
.replace("ú", "u").replace("ü", "u").replace("ñ", "n")\ .replace("ú", "u").replace("ü", "u").replace("ñ", "n")\
.replace("Á", "A").replace("É", "E").replace("Í", "I").replace("Ó", "O")\ .replace("Á", "A").replace("É", "E").replace("Í", "I").replace("Ó", "O")\
.replace("Ú", "U").replace("Ü", "U").replace("Ñ", "N") .replace("Ú", "U").replace("Ü", "U").replace("Ñ", "N")
# Renombramos el path dejado en la descarga a uno más corto # Renombramos el path dejado en la descarga a uno más corto
rename_status = False rename_status = False
org_rar_file = rar_file org_rar_file = rar_file
@@ -1007,11 +1003,11 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
save_path_videos = filetools.join(save_path_videos, 'Extracted') save_path_videos = filetools.join(save_path_videos, 'Extracted')
if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
log("##### save_path_videos: %s" % save_path_videos) log("##### save_path_videos: %s" % save_path_videos)
rar_control = update_rar_control(erase_file_path, status='UnRARing') rar_control = update_rar_control(erase_file_path, status='UnRARing')
# Permite hasta 5 pasadas de extracción de .RARs anidados # Permite hasta 5 pasadas de extracción de .RARs anidados
platformtools.dialog_notification("Empezando extracción...", rar_file, time=5000) platformtools.dialog_notification(config.get_localized_string(70793), rar_file, time=5000)
for x in range(5): for x in range(5):
try: try:
if not PY3: if not PY3:
@@ -1019,11 +1015,11 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
else: else:
archive = rarfile.RarFile(file_path) archive = rarfile.RarFile(file_path)
except: except:
log("##### ERROR en Archivo rar: %s" % rar_file) log("##### ERROR in rar archive: %s" % rar_file)
log("##### ERROR en Carpeta del rar: %s" % file_path) log("##### ERROR in rar folder: %s" % file_path)
log(traceback.format_exc()) log(traceback.format_exc())
error_msg = "Error al abrir el RAR" error_msg = config.get_localized_string(70796)
error_msg1 = "Comprueba el log para más detalles" error_msg1 = config.get_localized_string(60015)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
return rar_file, False, '', '' return rar_file, False, '', ''
@@ -1034,9 +1030,9 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
pass_path = filetools.split(file_path)[0] pass_path = filetools.split(file_path)[0]
password = last_password_search(pass_path, erase_file_path) password = last_password_search(pass_path, erase_file_path)
if not password : if not password :
password = platformtools.dialog_input(heading="Introduce la contraseña (Mira en %s)" % pass_path) password = platformtools.dialog_input(heading=config.get_localized_string(70794) % pass_path)
if not password: if not password:
error_msg = "No se ha introducido la contraseña" error_msg = config.get_localized_string(60309)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
@@ -1056,10 +1052,10 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0)) info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0))
if info: if info:
info.append("Extraer todo sin reproducir") info.append(config.get_localized_string(70801))
else: else:
error_msg = "El RAR está vacío" error_msg = config.get_localized_string(70797)
error_msg1 = "O no contiene archivos válidos" error_msg1 = config.get_localized_string(70798)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
@@ -1069,7 +1065,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
#selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info) #selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info)
selection = len(info) - 1 selection = len(info) - 1
if selection < 0: if selection < 0:
error_msg = "El RAR está vacío" error_msg = config.get_localized_string(70797)
platformtools.dialog_notification(error_msg) platformtools.dialog_notification(error_msg)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
return rar_file, False, '', '' return rar_file, False, '', ''
@@ -1079,26 +1075,26 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
if selection == len(info) - 1: if selection == len(info) - 1:
log("##### rar_file 1: %s" % file_path) log("##### rar_file 1: %s" % file_path)
log("##### save_path_videos 1: %s" % save_path_videos) log("##### save_path_videos 1: %s" % save_path_videos)
dp.update(99, "Extrayendo archivos...", "Espera unos minutos....") dp.update(99, config.get_localized_string(70803), config.get_localized_string(70802))
archive.extractall(save_path_videos) archive.extractall(save_path_videos)
else: else:
log("##### rar_file 2: %s" % file_path) log("##### rar_file 2: %s" % file_path)
log("##### save_path_videos 2: %s" % save_path_videos) log("##### save_path_videos 2: %s" % save_path_videos)
dp.update(99, "Espera unos minutos....", "Extrayendo archivo... %s" % info[selection]) dp.update(99, config.get_localized_string(70802), config.get_localized_string(70803) + " %s" % info[selection])
archive.extract(files[selection], save_path_videos) archive.extract(files[selection], save_path_videos)
log("##### RAR Extract END #####") log("##### RAR Extract END #####")
except (rarfile.RarWrongPassword, rarfile.RarCRCError): except (rarfile.RarWrongPassword, rarfile.RarCRCError):
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Contraseña incorrecta" error_msg1 = config.get_localized_string(60309)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
except rarfile.BadRarFile: except rarfile.BadRarFile:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Archivo rar con errores" error_msg1 = config.get_localized_string(60800)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR')
#return rar_file, False, '', erase_file_path #return rar_file, False, '', erase_file_path
@@ -1106,8 +1102,8 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Comprueba el log para más detalles" error_msg1 = config.get_localized_string(60015)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
@@ -1116,7 +1112,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
'.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
'.mpe', '.mp4', '.ogg', '.wmv'] '.mpe', '.mp4', '.ogg', '.wmv']
# Localizamos el path donde se ha dejado la extracción # Localizamos el path donde se ha dejado la extracción
folder = True folder = True
file_result = filetools.listdir(save_path_videos) file_result = filetools.listdir(save_path_videos)
@@ -1142,25 +1138,25 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
save_path_videos = filetools.join(save_path_videos, 'Extracted') save_path_videos = filetools.join(save_path_videos, 'Extracted')
rar_control = update_rar_control(erase_file_path, newextract=(rar_file)) rar_control = update_rar_control(erase_file_path, newextract=(rar_file))
if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
platformtools.dialog_notification("Siguiente extracción...", rar_file, time=5000) platformtools.dialog_notification(config.get_localized_string(70804), rar_file, time=5000)
# Si ya se ha extraido todo, preparamos el retorno # Si ya se ha extraido todo, preparamos el retorno
else: else:
video_list = [] video_list = []
for file_r in file_result: for file_r in file_result:
if os.path.splitext(file_r)[1] in extensions_list: if os.path.splitext(file_r)[1] in extensions_list:
video_list += [file_r] video_list += [file_r]
if len(video_list) == 0: if len(video_list) == 0:
error_msg = "El rar está vacío" error_msg = config.get_localized_string(70797)
error_msg1 = "O no contiene archivos válidos" error_msg1 = config.get_localized_string(70798)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
else: else:
log("##### Archivo extraído: %s" % video_list[0]) log("##### Archive extracted: %s" % video_list[0])
platformtools.dialog_notification("Archivo extraído...", video_list[0], time=10000) platformtools.dialog_notification(config.get_localized_string(70795), video_list[0], time=10000)
log("##### Archivo remove: %s" % file_path) log("##### Archive removes: %s" % file_path)
#rar_control = update_rar_control(erase_file_path, status='DONE') #rar_control = update_rar_control(erase_file_path, status='DONE')
ret = filetools.remove(filetools.join(erase_file_path, '_rar_control.json'), silent=True) ret = filetools.remove(filetools.join(erase_file_path, '_rar_control.json'), silent=True)
return str(video_list[0]), True, save_path_videos, erase_file_path return str(video_list[0]), True, save_path_videos, erase_file_path
@@ -1180,12 +1176,12 @@ def rename_rar_dir(rar_file, save_path_videos, video_path, torr_client):
src = filetools.join(save_path_videos, folders[0]) src = filetools.join(save_path_videos, folders[0])
dst = filetools.join(save_path_videos, video_path) dst = filetools.join(save_path_videos, video_path)
dst_file = video_path dst_file = video_path
for x in range(20): for x in range(20):
if xbmc.abortRequested: if xbmc.abortRequested:
return rename_status, rar_file return rename_status, rar_file
xbmc.sleep(1000) xbmc.sleep(1000)
# Se para la actividad para que libere los archivos descargados # Se para la actividad para que libere los archivos descargados
if torr_client in ['quasar', 'elementum']: if torr_client in ['quasar', 'elementum']:
torr_data, deamon_url, index = get_tclient_data(folders[0], torr_client) torr_data, deamon_url, index = get_tclient_data(folders[0], torr_client)
@@ -1209,13 +1205,13 @@ def rename_rar_dir(rar_file, save_path_videos, video_path, torr_client):
rename_status = True rename_status = True
update_rar_control(dst, newpath=dst) update_rar_control(dst, newpath=dst)
break break
return rename_status, rar_file return rename_status, rar_file
def last_password_search(pass_path, erase_file_path=''): def last_password_search(pass_path, erase_file_path=''):
logger.info(pass_path) logger.info(pass_path)
if not erase_file_path: if not erase_file_path:
erase_file_path = pass_path erase_file_path = pass_path
@@ -1223,7 +1219,7 @@ def last_password_search(pass_path, erase_file_path=''):
password = '' password = ''
patron_url = '(http.*\:\/\/(?:www.)?\w+\.\w+\/.*?)[\n|\r|$]' patron_url = '(http.*\:\/\/(?:www.)?\w+\.\w+\/.*?)[\n|\r|$]'
patron_pass = '<input\s*type="text"\s*id="txt_password"\s*name="[^"]+"\s*onClick="[^"]+"\s*value="([^"]+)"' patron_pass = '<input\s*type="text"\s*id="txt_password"\s*name="[^"]+"\s*onClick="[^"]+"\s*value="([^"]+)"'
try: try:
pass_path_list = filetools.listdir(pass_path) pass_path_list = filetools.listdir(pass_path)
for file in pass_path_list: for file in pass_path_list:
@@ -1238,18 +1234,18 @@ def last_password_search(pass_path, erase_file_path=''):
break break
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
log("##### Contraseña extraída: %s" % password) log("##### Password Extracted: %s" % password)
return password return password
def update_rar_control(path, newpath='', newextract='', password='', error='', error_msg='', status=''): def update_rar_control(path, newpath='', newextract='', password='', error='', error_msg='', status=''):
try: try:
rar_control = {} rar_control = {}
rar_control = jsontools.load(filetools.read(filetools.join(path, '_rar_control.json'))) rar_control = jsontools.load(filetools.read(filetools.join(path, '_rar_control.json')))
if rar_control: if rar_control:
if newpath: if newpath:
rar_control['download_path'] = newpath rar_control['download_path'] = newpath
for x, entry in enumerate(rar_control['rar_files']): for x, entry in enumerate(rar_control['rar_files']):
if '__name' in entry: if '__name' in entry:
@@ -1273,7 +1269,7 @@ def update_rar_control(path, newpath='', newextract='', password='', error='', e
str(rar_control['error']), rar_control['error_msg'], rar_control['status'])) str(rar_control['error']), rar_control['error_msg'], rar_control['status']))
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
return rar_control return rar_control
@@ -1300,21 +1296,21 @@ def import_libtorrent(LIBTORRENT_PATH):
from ctypes import CDLL from ctypes import CDLL
dll_path = os.path.join(LIBTORRENT_PATH, 'liblibtorrent.so') dll_path = os.path.join(LIBTORRENT_PATH, 'liblibtorrent.so')
liblibtorrent = CDLL(dll_path) liblibtorrent = CDLL(dll_path)
path_list = [LIBTORRENT_PATH, xbmc.translatePath('special://xbmc')] path_list = [LIBTORRENT_PATH, xbmc.translatePath('special://xbmc')]
fp, pathname, description = imp.find_module('libtorrent', path_list) fp, pathname, description = imp.find_module('libtorrent', path_list)
# Esta parte no funciona en Android. Por algún motivo da el error "dlopen failed: library "liblibtorrent.so" not found" # Esta parte no funciona en Android. Por algún motivo da el error "dlopen failed: library "liblibtorrent.so" not found"
# Hay que encontrar un hack para rodear el problema. Lo siguiente ha sido probado sin éxito: # Hay que encontrar un hack para rodear el problema. Lo siguiente ha sido probado sin éxito:
#if fp: fp.close() #if fp: fp.close()
#fp = filetools.file_open(filetools.join(LIBTORRENT_PATH, 'libtorrent.so'), mode='rb') # Usa XbmcVFS #fp = filetools.file_open(filetools.join(LIBTORRENT_PATH, 'libtorrent.so'), mode='rb') # Usa XbmcVFS
#fp = open(os.path.join(LIBTORRENT_PATH, 'libtorrent.so'), 'rb') #fp = open(os.path.join(LIBTORRENT_PATH, 'libtorrent.so'), 'rb')
try: try:
lt = imp.load_module('libtorrent', fp, pathname, description) lt = imp.load_module('libtorrent', fp, pathname, description)
finally: finally:
if fp: fp.close() if fp: fp.close()
except Exception as e1: except Exception as e1:
logger.error(traceback.format_exc(1)) logger.error(traceback.format_exc(1))
log('fp = ' + str(fp)) log('fp = ' + str(fp))
@@ -1332,7 +1328,7 @@ def import_libtorrent(LIBTORRENT_PATH):
ok = platformtools.dialog_ok(config.get_localized_string(30035), config.get_localized_string(30036), config.get_localized_string(60015), str(e2)) ok = platformtools.dialog_ok(config.get_localized_string(30035), config.get_localized_string(30036), config.get_localized_string(60015), str(e2))
except: except:
pass pass
try: try:
if not e1 and e2: e1 = e2 if not e1 and e2: e1 = e2
except: except:
@@ -1345,7 +1341,7 @@ def import_libtorrent(LIBTORRENT_PATH):
except: except:
e1 = '' e1 = ''
e2 = '' e2 = ''
return lt, e, e1, e2 return lt, e, e1, e2
@@ -1354,4 +1350,3 @@ def log(texto):
xbmc.log(texto, xbmc.LOGNOTICE) xbmc.log(texto, xbmc.LOGNOTICE)
except: except:
pass pass