Fix Download Torrent

This commit is contained in:
Alhaziel01
2020-05-11 19:40:20 +02:00
parent 7484be7656
commit f7c85c97dd
3 changed files with 641 additions and 712 deletions
File diff suppressed because it is too large Load Diff
+187 -191
View File
@@ -1,41 +1,25 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import re, os, sys import re, os, sys, time, requests, xbmc, xbmcaddon
# from builtins import str from core import filetools, jsontools
from builtins import range from core.support import dbg, log, match
from platformcode import config, platformtools
from torrentool.api import Torrent
from lib.guessit import guessit
PY3 = False if sys.version_info[0] >= 3:
VFS = True
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int; VFS = False
if PY3:
import urllib.parse as urllib import urllib.parse as urllib
else: else:
import urllib import urllib
import time, requests, xbmc, xbmcgui, xbmcaddon, shutil monitor = filetools.join(config.get_data_path(), 'elementum_monitor.json')
from core import filetools, jsontools
from core.support import dbg, log, match
# from core import httptools
# from core import scrapertools
from platformcode import config, platformtools
from threading import Thread, currentThread
from torrentool.api import Torrent
from lib.guessit import guessit
try:
elementum_setting = xbmcaddon.Addon(id='plugin.video.elementum')
elementum_host = 'http://127.0.0.1:' + elementum_setting.getSetting('remote_port') + '/torrents/'
TorrentPath = xbmc.translatePath(elementum_setting.getSetting('torrents_path'))
except:
pass
extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.mpe', '.mp4', '.ogg', '.wmv'] extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.mpe', '.mp4', '.ogg', '.wmv']
monitorPath = filetools.join(config.get_data_path(), 'elementum_torrent.txt')
# 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=''):
torrent_options = platformtools.torrent_client_installed(show_tuple=True) torrent_options = platformtools.torrent_client_installed(show_tuple=True)
if len(torrent_options) == 0: if len(torrent_options) == 0:
from specials import elementum_download from specials import elementum_download
@@ -71,184 +55,154 @@ def mark_auto_as_watched(item):
xbmc_videolibrary.mark_auto_as_watched(item) xbmc_videolibrary.mark_auto_as_watched(item)
########################## ELEMENTUM MONITOR TEST ########################## def setting():
try:
elementum_setting = xbmcaddon.Addon(id='plugin.video.elementum')
elementum_host = 'http://127.0.0.1:' + elementum_setting.getSetting('remote_port') + '/torrents/'
TorrentPath = xbmc.translatePath(elementum_setting.getSetting('torrents_path'))
except:
elementum_setting = ''
elementum_host = ''
TorrentPath = ''
return elementum_setting, elementum_host, TorrentPath
elementumHost = 'http://127.0.0.1:65220/torrents/'
def elementum_download(item): def elementum_download(item):
elementum = False elementum_setting, elementum_host, TorrentPath = setting()
while not elementum:
try:
sleep = False
if elementum_setting.getSetting('logger_silent') == False:
elementum_setting.setSetting('logger_silent', 'true')
sleep = True
if elementum_setting.getSetting('download_storage') != 0:
config.set_setting('elementumtype', elementum_setting.getSetting('download_storage')) # Backup Setting
elementum_setting.setSetting('download_storage', '0') # Set Setting
sleep = True
if elementum_setting.getSetting('download_path') != config.get_setting('downloadpath'):
elementum_setting.setSetting('download_path', config.get_setting('downloadpath')) # Backup Setting
config.set_setting('elementumdl', elementum_setting.getSetting('download_path')) # Set Setting
sleep = True
if sleep: time.sleep(3)
elementum = True
path = filetools.join(config.get_data_path(),'elementum_torrent.txt')
url = urllib.quote_plus(item.url)
filetools.write(path, url)
except:
pass
if elementum_setting:
set_elementum(True)
time.sleep(3)
TorrentName = match(item.url, patron=r'btih(?::|%3A)([^&%]+)', string=True).match
post = 'uri=%s&file=null&all=1' % urllib.quote_plus(item.url)
match(elementum_host + 'add', post=post, timeout=5, alfa_s=True, ignore_response_code=True)
while not filetools.isfile(filetools.join(elementum_setting.getSetting('torrents_path'), TorrentName + '.torrent')):
time.sleep(1)
# def stop_elementum_monitor(): monitor_update(TorrentPath, TorrentName)
# config.set_setting('stop_elementum_monitor', True)
# time.sleep(2)
# def start_elementum_monitor():
# config.set_setting('stop_elementum_monitor', False)
# time.sleep(3)
# Thread(target=elementum_monitor).start()
def elementum_monitor(): def elementum_monitor():
partials = [] path = xbmc.translatePath(config.get_setting('downloadlistpath'))
try: elementum_setting, elementum_host, TorrentPath = setting()
if filetools.isfile(monitorPath): active_torrent = filetools.listdir(TorrentPath)
log('Add Torrent')
url = filetools.read(monitorPath) if elementum_setting:
if url.startswith('/'): # check if command file exist
requests.get(elementum_host + url) if filetools.isfile(monitor):
wait = False json = jsontools.load(open(monitor, "r").read())
else: Monitor = json['monitor']
TorrentName = match(url, patron=r'btih(?::|%3A)([^&%]+)', string=True).match # else create it
uri = elementum_host + 'add'
post = 'uri=%s&file=null&all=1' % url
match(uri, post=post, timeout=5, alfa_s=True, ignore_response_code=True)
wait = True
filetools.remove(monitorPath)
if wait:
while not filetools.isfile(filetools.join(elementum_setting.getSetting('torrents_path'), TorrentName + '.torrent')):
time.sleep(1)
else: else:
log('Watch') json = jsontools.load('{"monitor":{},"settings":{}}')
json = jsontools.dump(json)
filetools.write(monitor, json, silent=True)
if len(Monitor) > 0:
try: try:
data = requests.get(elementum_host).json() data = requests.get(elementum_host + '/list').json()
except: except:
data = '' data = ''
if data: if data:
json = data['items'] for it in data:
progress = round(it['progress'], 2)
for it in json: status = it['status']
Partial = float(match(it['label'], patron=r'(\d+\.\d+)%').match) name = it['id']
Title = it['info']['title'] if name in Monitor:
TorrentName = match(it['path'], patron=r'resume=([^&]+)').match jsontools.update_node(progress, Monitor[name]['file'], 'downloadProgress', path, silent=True)
File, Json = find_file(TorrentName) jsontools.update_node(4, Monitor[name]['file'], 'downloadStatus', path, silent=True)
update_download_info(Partial, Title, TorrentName, File, Json) if status in ['Paused']:
partials.append(Partial) jsontools.update_node(0, Monitor[name]['file'], 'downloadStatus', path, silent=True)
if status in ['Seeding', 'Finished']:
partials.sort() monitor_update(TorrentPath, name, remove=True)
if len(partials) > 0 and partials[0] == 100: dlJson = jsontools.load(open(filetools.join(path, Monitor[name]['file']), "r").read())
unset_elementum() jsontools.update_node(dlJson['downloadSize'], Monitor[name]['file'], 'downloadCompleted', path, silent=True)
except: jsontools.update_node(2, Monitor[name]['file'], 'downloadStatus', path, silent=True)
pass requests.get(elementum_host + 'pause/' + name)
filetools.remove(filetools.join(TorrentPath, name + '.torrent'))
filetools.remove(filetools.join(TorrentPath, name + '.fastresume'))
time.sleep(1)
rename(Monitor[name]['file'])
def find_file(File): def monitor_update(TorrentPath, value, remove=False):
elementum_setting, elementum_host, TorrentPath = setting()
json = jsontools.load(open(monitor, "r").read())
Monitor = json['monitor']
info = Torrent.from_file(filetools.join(TorrentPath, value + '.torrent'))
path = xbmc.translatePath(config.get_setting('downloadlistpath'))
if not value in Monitor:
Monitor[value]={}
Monitor[value]['name'] = info.name
Monitor[value]['size'] = info.total_size
File = find_file(value)
Monitor[value]['file'] = File
json = jsontools.dump(json)
filetools.write(monitor, json, silent=True)
backupFilename = jsontools.load(open(filetools.join(path, File), "r").read())['downloadFilename']
jsontools.update_node(value, File, 'TorrentName', path, silent=True)
jsontools.update_node(info.total_size, File, 'downloadSize', path, silent=True)
jsontools.update_node(backupFilename, File, 'backupFilename', path, silent=True)
jsontools.update_node(info.name, File, 'downloadFilename', path, silent=True)
elif remove:
Monitor.pop(value)
jsontools.dump(json)
filetools.write(monitor, jsontools.dump(json), silent=True)
if len(Monitor) == 0: set_elementum()
def set_elementum(SET=False):
elementum_setting, elementum_host, TorrentPath = setting()
json = jsontools.load(open(monitor, "r").read())
backup_setting = json['settings']
write = False
if SET:
if elementum_setting.getSetting('logger_silent') == False or not 'logger_silent' in backup_setting:
elementum_setting.setSetting('logger_silent', 'true')
backup_setting['logger_silent'] = 'false'
if elementum_setting.getSetting('download_storage') != 0 or not 'download_storage' in backup_setting:
backup_setting['download_storage'] = elementum_setting.getSetting('download_storage') # Backup Setting
elementum_setting.setSetting('download_storage', '0') # Set Setting
if elementum_setting.getSetting('download_path') != config.get_setting('downloadpath') or not 'download_path' in backup_setting:
backup_setting['download_path'] = elementum_setting.getSetting('download_path') # Backup Setting
elementum_setting.setSetting('download_path', config.get_setting('downloadpath')) # Set Setting
write = True
elif backup_setting:
elementum_setting.setSetting('logger_silent', backup_setting['logger_silent'])
elementum_setting.setSetting('download_storage', backup_setting['download_storage'])
elementum_setting.setSetting('download_path', backup_setting['download_path'])
json['settings'] = {}
write = True
if write:
json = jsontools.dump(json)
filetools.write(monitor, json, silent=True)
time.sleep(1)
def find_file(hash):
path = xbmc.translatePath(config.get_setting('downloadlistpath')) path = xbmc.translatePath(config.get_setting('downloadlistpath'))
files = filetools.listdir(path) files = filetools.listdir(path)
# dbg()
for f in files: for f in files:
filepath = filetools.join(path, f) filepath = filetools.join(path, f)
json = jsontools.load(filetools.read(filepath)) json = jsontools.load(filetools.read(filepath))
if ('downloadServer' in json and 'url' in json['downloadServer'] and File in json['downloadServer']['url']) or ('url' in json and File in json['url']): if ('downloadServer' in json and 'url' in json['downloadServer'] and hash in json['downloadServer']['url']) or ('url' in json and hash in json['url']):
break break
return filetools.split(filepath)[-1], json return filetools.split(filepath)[-1]
def update_download_info(Partial, Title, TorrentName, File, Json): def elementum_actions(parameter, TorrentHash):
path = xbmc.translatePath(config.get_setting('downloadlistpath')) elementum_setting, elementum_host, TorrentPath = setting()
dlpath = filetools.join(config.get_setting('downloadpath'), Title) if elementum_setting:
if parameter == 'delete' : monitor_update(TorrentPath, TorrentHash, remove=True)
requests.get('%s/%s/%s' %(elementum_host, parameter, TorrentHash))
if 'TorrentName' not in Json:
jsontools.update_node(TorrentName, File, 'TorrentName', path, silent=True)
if Json['downloadSize'] == 0:
size = Torrent.from_file(filetools.join(TorrentPath, TorrentName + '.torrent')).total_size
jsontools.update_node(size, File, 'downloadSize', path, silent=True)
if Json['downloadFilename'] != dlpath and 'backupFilename' not in Json:
jsontools.update_node(Json['downloadFilename'], File, 'backupFilename', path, silent=True)
jsontools.update_node(dlpath, File, 'downloadFilename', path, silent=True)
if Json['downloadProgress'] != Partial and Partial != 0:
jsontools.update_node(Partial, File, 'downloadProgress', path, silent=True)
jsontools.update_node(4, File, 'downloadStatus', path, silent=True)
if Partial == 100:
jsontools.update_node(Json['downloadSize'], File, 'downloadCompleted', path, silent=True)
jsontools.update_node(2, File, 'downloadStatus', path, silent=True)
requests.get(elementum_host + 'pause/' + TorrentName)
del_torrent(TorrentName)
time.sleep(1)
rename(TorrentName, path)
# requests.get(elementum_host + 'delete/' + TorrentName + '?files=false')
def del_torrent(TorrentName):
filetools.remove(filetools.join(TorrentPath, TorrentName + '.torrent'))
def rename(TorrentName, Path):
# dbg()
File, Json = find_file(TorrentName)
path = Json['downloadFilename']
if Json['infoLabels']['mediatype'] == 'movie':
if filetools.isdir(path):
extension = ''
files = filetools.listdir(path)
sep = '/' if path.lower().startswith("smb://") else os.sep
oldName = path.split(sep)[-1]
newName = Json['backupFilename']
for f in files:
ext = os.path.splitext(f)[-1]
if ext in extensions_list: extension = ext
filetools.rename(filetools.join(path, f), f.replace(oldName, newName))
filetools.rename(path, newName)
jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', Path)
else:
oldName = filetools.split(path)[-1]
newName = Json['backupFilename'] + os.path.splitext(oldName)[-1]
filetools.rename(path, newName)
jsontools.update_node(newName, File, 'downloadFilename', Path)
else:
sep = '/' if path.lower().startswith("smb://") else os.sep
FolderName = Json['backupFilename'].split(sep)[0]
Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName)
if filetools.isdir(path):
files = filetools.listdir(path)
file_dict = {}
for f in files:
title = process_filename(f, Title, ext=False)
ext = os.path.splitext(f)[-1]
name = os.path.splitext(f)[0]
if title not in file_dict and ext in extensions_list:
file_dict[title] = name
for title, name in file_dict.items():
for f in files:
if name in f:
# log('Name:',name,'Title:',title)
filetools.rename(filetools.join(path, f), f.replace(name, title))
filetools.rename(path, FolderName)
jsontools.update_node(FolderName, File, 'downloadFilename', Path)
else:
filename = filetools.split(path)[-1]
title = process_filename(filename, Title)
NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName)
if not filetools.isdir(NewFolder):
filetools.mkdir(NewFolder)
from_folder = filetools.join(config.get_setting('downloadpath'), filename)
to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title)
filetools.move(from_folder, to_folder)
jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', Path)
def process_filename(filename, Title, ext=True): def process_filename(filename, Title, ext=True):
extension = os.path.splitext(filename)[-1] extension = os.path.splitext(filename)[-1]
@@ -275,16 +229,58 @@ def process_filename(filename, Title, ext=True):
title = (t if t else Title) + s + episode + (extension if ext else '') title = (t if t else Title) + s + episode + (extension if ext else '')
return title return title
def unset_elementum():
log('UNSET Elementum')
Sleep = False
if config.get_setting('elementumtype') and config.get_setting('elementumtype') != elementum_setting.gerSetting('download_storage'):
elementum_setting.setSetting('download_storage', str(config.get_setting('elementumtype')))
Sleep = True
if config.get_setting('elementumdl') and config.get_setting('elementumdl') != elementum_setting.gerSetting('download_path'):
elementum_setting.setSetting('download_path', config.get_setting('elementumdl'))
Sleep = True
if Sleep:
time.sleep(1)
########################## ELEMENTUM MONITOR TEST ########################## def rename(File):
jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath'))
json = jsontools.load(open(filetools.join(jsonPath, File), "r").read())
filePath = filetools.join(xbmc.translatePath(config.get_setting('downloadpath')), json['downloadFilename'])
if json['infoLabels']['mediatype'] == 'movie':
if filetools.isdir(filePath):
extension = ''
files = filetools.listdir(filePath)
oldName = json['downloadFilename']
newName = json['backupFilename']
for f in files:
ext = os.path.splitext(f)[-1]
if ext in extensions_list: extension = ext
filetools.rename(filetools.join(filePath, f), f.replace(oldName, newName))
filetools.rename(filePath, newName)
jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', jsonPath)
else:
oldName = json['downloadFilename']
newName = json['backupFilename'] + os.path.splitext(oldName)[-1]
filetools.rename(filePath, newName)
jsontools.update_node(newName, File, 'downloadFilename', jsonPath)
else:
sep = '/' if filePath.lower().startswith("smb://") else os.sep
FolderName = json['backupFilename'].split(sep)[0]
Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName)
if filetools.isdir(filePath):
files = filetools.listdir(filePath)
file_dict = {}
for f in files:
title = process_filename(f, Title, ext=False)
ext = os.path.splitext(f)[-1]
name = os.path.splitext(f)[0]
if title not in file_dict and ext in extensions_list:
file_dict[title] = name
for title, name in file_dict.items():
for f in files:
if name in f:
filetools.rename(filetools.join(filePath, f), f.replace(name, title))
filetools.rename(filePath, FolderName)
jsontools.update_node(FolderName, File, 'downloadFilename', jsonPath)
else:
filename = filetools.split(filePath)[-1]
title = process_filename(filename, Title)
NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName)
if not filetools.isdir(NewFolder):
filetools.mkdir(NewFolder)
from_folder = filetools.join(config.get_setting('downloadpath'), filename)
to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title)
filetools.move(from_folder, to_folder)
jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', jsonPath)
+98 -107
View File
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# ------------------------------------------------------------ # ------------------------------------------------------------
# Gestor de descargas # Download manager
# ------------------------------------------------------------ # ------------------------------------------------------------
from __future__ import division from __future__ import division
@@ -23,6 +23,7 @@ from core.item import Item
from platformcode import config, logger from platformcode import config, logger
from platformcode import platformtools from platformcode import platformtools
from core.support import log, dbg, typo from core.support import log, dbg, typo
from servers import torrent
kb = '0xFF65B3DA' kb = '0xFF65B3DA'
kg = '0xFF65DAA8' kg = '0xFF65DAA8'
@@ -46,21 +47,21 @@ def mainlist(item):
log() log()
itemlist = [] itemlist = []
# Lista de archivos # File list
for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
# Saltamos todos los que no sean JSON # We skip all the non JSON
if not file.endswith(".json"): continue if not file.endswith(".json"): continue
# cargamos el item # we load the item
file = filetools.join(DOWNLOAD_LIST_PATH, file) file = filetools.join(DOWNLOAD_LIST_PATH, file)
i = Item(path=file).fromjson(filetools.read(file)) i = Item(path=file).fromjson(filetools.read(file))
i.thumbnail = i.contentThumbnail i.thumbnail = i.contentThumbnail
# Listado principal # Main listing
if not item.contentType == "tvshow": if not item.contentType == "tvshow":
# Series # Series
if i.contentType == "episode": if i.contentType == "episode":
# Comprobamos que la serie no este ya en el itemlist # We check that the series is not already in the itemlist
if not [x for x in itemlist if x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel]: if not [x for x in itemlist if x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel]:
title = TITLE_TVSHOW % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel) title = TITLE_TVSHOW % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel)
@@ -81,12 +82,12 @@ def mainlist(item):
s.title = TITLE_TVSHOW % (STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) s.title = TITLE_TVSHOW % (STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel)
# Peliculas # Movies
elif i.contentType == "movie" or i.contentType == "video": elif i.contentType == "movie" or i.contentType == "video":
i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentTitle) i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentTitle)
itemlist.append(i) itemlist.append(i)
# Listado dentro de una serie # Listed within a series
else: else:
if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel: if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel:
i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle)) i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
@@ -94,19 +95,19 @@ def mainlist(item):
estados = [i.downloadStatus for i in itemlist] estados = [i.downloadStatus for i in itemlist]
# Si hay alguno completado # If there is any completed
if 2 in estados: if 2 in estados:
itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title=config.get_localized_string(70218), itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title=config.get_localized_string(70218),
contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('delete.png'), contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('delete.png'),
contentSerieName=item.contentSerieName, text_color=STATUS_COLORS[STATUS_CODES.completed])) contentSerieName=item.contentSerieName, text_color=STATUS_COLORS[STATUS_CODES.completed]))
# Si hay alguno con error # If there is any error
if 3 in estados: if 3 in estados:
itemlist.insert(0, Item(channel=item.channel, action="restart_error", title=config.get_localized_string(70219), itemlist.insert(0, Item(channel=item.channel, action="restart_error", title=config.get_localized_string(70219),
contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('update.png'), contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('update.png'),
contentSerieName=item.contentSerieName, text_color=STATUS_COLORS[STATUS_CODES.error])) contentSerieName=item.contentSerieName, text_color=STATUS_COLORS[STATUS_CODES.error]))
# Si hay alguno pendiente # If there is any pending
if 1 in estados or 0 in estados: if 1 in estados or 0 in estados:
itemlist.insert(0, Item(channel=item.channel, action="download_all", title=support.typo(config.get_localized_string(70220),'bold'), itemlist.insert(0, Item(channel=item.channel, action="download_all", title=support.typo(config.get_localized_string(70220),'bold'),
contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('downloads.png'), contentType=item.contentType, contentChannel=item.contentChannel, thumbnail=get_thumb('downloads.png'),
@@ -190,11 +191,7 @@ def clean_all(item):
if File.endswith(".json"): if File.endswith(".json"):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, File))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, File)))
if download_item.TorrentName: if download_item.TorrentName:
path = filetools.join(config.get_data_path(),'elementum_torrent.txt') torrent.elementum_actions('delete', item.TorrentName)
url = '/pause/' + download_item.TorrentName
filetools.write(path, url)
from servers.torrent import del_torrent
del_torrent(download_item.TorrentName)
if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, File)) filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, File))
if removeFiles: if removeFiles:
@@ -218,9 +215,7 @@ def stop_all(item=None):
if fichero.endswith(".json"): if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if download_item.TorrentName: if download_item.TorrentName:
path = filetools.join(config.get_data_path(),'elementum_torrent.txt') torrent.elementum_actions('pause', download_item.TorrentName)
url = '/pause/' + download_item.TorrentName
filetools.write(path, url)
if download_item.downloadStatus == 4: if download_item.downloadStatus == 4:
update_json(filetools.join(DOWNLOAD_LIST_PATH, fichero), {"downloadStatus": STATUS_CODES.stoped}) update_json(filetools.join(DOWNLOAD_LIST_PATH, fichero), {"downloadStatus": STATUS_CODES.stoped})
xbmc.sleep(300) xbmc.sleep(300)
@@ -275,72 +270,75 @@ def download_all_background(item):
if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]: if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]:
res = start_download(download_item) res = start_download(download_item)
# platformtools.itemlist_refresh() # platformtools.itemlist_refresh()
# Si se ha cancelado paramos # If canceled, we stop
if res == STATUS_CODES.canceled: break if res == STATUS_CODES.canceled: break
def menu(item): def menu(item):
log() log(item)
if item.downloadServer: if item.downloadServer:
servidor = item.downloadServer.get("server", "Auto") servidor = item.downloadServer.get("server", "Auto")
else: else:
servidor = "Auto" servidor = "Auto"
# Opciones disponibles para el menu # Options available for the menu
op = [config.get_localized_string(70225), config.get_localized_string(70226), config.get_localized_string(70227), op = [config.get_localized_string(70225), config.get_localized_string(70226), config.get_localized_string(70227),
config.get_localized_string(30165) % (servidor.capitalize()), config.get_localized_string(60220), config.get_localized_string(30165) % (servidor.capitalize()), config.get_localized_string(60220),
config.get_localized_string(60221)] config.get_localized_string(60221)]
opciones = [] opciones = []
# Opciones para el menu # Options for the menu
if item.downloadStatus == STATUS_CODES.stoped: if item.downloadStatus == STATUS_CODES.stoped:
opciones.append(op[0]) # Descargar opciones.append(op[0]) # Download
if not item.server: opciones.append(op[3]) # Elegir Servidor if not item.server: opciones.append(op[3]) # Choose Server
opciones.append(op[1]) # Eliminar de la lista opciones.append(op[1]) # Remove from the list
if item.downloadStatus == STATUS_CODES.canceled: if item.downloadStatus == STATUS_CODES.canceled:
opciones.append(op[0]) # Descargar opciones.append(op[0]) # Download
if not item.server: opciones.append(op[3]) # Elegir Servidor if not item.server: opciones.append(op[3]) # Choose Server
opciones.append(op[2]) # Reiniciar descarga opciones.append(op[2]) # Restart download
opciones.append(op[1]) # Eliminar de la lista opciones.append(op[1]) # Remove from the list
if item.downloadStatus == STATUS_CODES.completed: if item.downloadStatus == STATUS_CODES.completed:
opciones.append(op[5]) # Play opciones.append(op[5]) # Play
opciones.append(op[1]) # Eliminar de la lista opciones.append(op[1]) # Remove from the list
opciones.append(op[2]) # Reiniciar descarga opciones.append(op[2]) # Restart download
if item.downloadStatus == STATUS_CODES.error: # descarga con error if item.downloadStatus == STATUS_CODES.error: # Download with error
opciones.append(op[2]) # Reiniciar descarga opciones.append(op[2]) # Restart download
opciones.append(op[1]) # Eliminar de la lista opciones.append(op[1]) # Remove from the list
if item.downloadStatus == STATUS_CODES.downloading: if item.downloadStatus == STATUS_CODES.downloading:
opciones.append(op[5]) # Play opciones.append(op[5]) # Play
opciones.append(op[4]) # pause download opciones.append(op[4]) # Pause Download
opciones.append(op[1]) # Eliminar de la lista opciones.append(op[1]) # Remove from the list
# Mostramos el dialogo # Show Dialog
seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones) seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones)
logger.info('SELECTION: '+ op[seleccion])
# -1 es cancelar # -1 is cancel
if seleccion == -1: return if seleccion == -1: return
log("option=", opciones[seleccion]) # Delete
# Opcion Eliminar
if opciones[seleccion] == op[1]: if opciones[seleccion] == op[1]:
filetools.remove(item.path) filetools.remove(item.path)
if platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(30300)): if item.TorrentName:
filetools.remove(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) torrent.elementum_actions('delete', item.TorrentName)
else:
if platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(30300)):
filetools.remove(filetools.join(DOWNLOAD_PATH, item.downloadFilename))
# Opcion inicaiar descarga # Start Download
if opciones[seleccion] == op[0]: if opciones[seleccion] == op[0]:
item.action = "start_download" item.action = "start_download"
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?" + item.tourl() + ")") xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?" + item.tourl() + ")")
# Elegir Servidor # Select Server
if opciones[seleccion] == op[3]: if opciones[seleccion] == op[3]:
select_server(item) select_server(item)
# Reiniciar descarga # Restart Download
if opciones[seleccion] == op[2]: if opciones[seleccion] == op[2]:
if filetools.isfile(filetools.join(DOWNLOAD_PATH, item.downloadFilename)): if filetools.isfile(filetools.join(DOWNLOAD_PATH, item.downloadFilename)):
filetools.remove(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) filetools.remove(filetools.join(DOWNLOAD_PATH, item.downloadFilename))
@@ -348,6 +346,8 @@ def menu(item):
update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0, "downloadServer": {}}) update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0, "downloadServer": {}})
if opciones[seleccion] == op[4]: if opciones[seleccion] == op[4]:
if item.TorrentName:
torrent.elementum_actions('pause', item.TorrentName)
update_json(item.path, {"downloadStatus": STATUS_CODES.stoped}) update_json(item.path, {"downloadStatus": STATUS_CODES.stoped})
if opciones[seleccion] == op[5]: if opciones[seleccion] == op[5]:
@@ -472,9 +472,7 @@ def get_server_position(server):
servers = {} servers = {}
if server in servers: if server in servers:
pos = [s for s in sorted(servers, key=lambda x: (old_div(sum(servers[x]["speeds"]), (len(servers[x]["speeds"]) or 1)), pos = [s for s in sorted(servers, key=lambda x: (old_div(sum(servers[x]["speeds"]), (len(servers[x]["speeds"]) or 1)), float(sum(servers[x]["success"])) / ( len(servers[x]["success"]) or 1)), reverse=True)]
float(sum(servers[x]["success"])) / (
len(servers[x]["success"]) or 1)), reverse=True)]
return pos.index(server) + 1 return pos.index(server) + 1
else: else:
return 0 return 0
@@ -482,27 +480,26 @@ def get_server_position(server):
def get_match_list(data, match_list, order_list=None, only_ascii=False, ignorecase=False): def get_match_list(data, match_list, order_list=None, only_ascii=False, ignorecase=False):
""" """
Busca coincidencias en una cadena de texto, con un diccionario de "ID" / "Listado de cadenas de busqueda": Search for matches in a text string, with a dictionary of "ID" / "List of search strings":
{ "ID1" : ["Cadena 1", "Cadena 2", "Cadena 3"],     {"ID1": ["String 1", "String 2", "String 3"],
"ID2" : ["Cadena 4", "Cadena 5", "Cadena 6"]       "ID2": ["String 4", "String 5", "String 6"]
}     }
El diccionario no pude contener una misma cadena de busqueda en varías IDs.     The dictionary could not contain the same search string in several IDs.
    The search is performed in order of search string size (from longest to shortest) if a string matches,
La busqueda se realiza por orden de tamaño de cadena de busqueda (de mas larga a mas corta) si una cadena coincide,     it is removed from the search string for the following, so that two categories are not detected if one string is part of another:
se elimina de la cadena a buscar para las siguientes, para que no se detecten dos categorias si una cadena es parte de otra:     for example: "Spanish Language" and "Spanish" if the first appears in the string "Pablo knows how to speak the Spanish Language"
por ejemplo: "Idioma Español" y "Español" si la primera aparece en la cadena "Pablo sabe hablar el Idioma Español"     It will match "Spanish Language" but not "Spanish" since the longest match has priority.
coincidira con "Idioma Español" pero no con "Español" ya que la coincidencia mas larga tiene prioridad.
""" """
match_dict = dict() match_dict = dict()
matches = [] matches = []
# Pasamos la cadena a unicode # We pass the string to unicode
if not PY3: if not PY3:
data = unicode(data, "utf8") data = unicode(data, "utf8")
# Pasamos el diccionario a {"Cadena 1": "ID1", "Cadena 2", "ID1", "Cadena 4", "ID2"} y los pasamos a unicode # We pass the dictionary to {"String 1": "ID1", "String 2", "ID1", "String 4", "ID2"} and we pass them to unicode
for key in match_list: for key in match_list:
if order_list and not key in order_list: if order_list and not key in order_list:
raise Exception("key '%s' not in match_list" % key) raise Exception("key '%s' not in match_list" % key)
@@ -514,17 +511,17 @@ def get_match_list(data, match_list, order_list=None, only_ascii=False, ignoreca
else: else:
match_dict[value] = key match_dict[value] = key
# Si ignorecase = True, lo pasamos todo a mayusculas # If ignorecase = True, we pass everything to capital letters
if ignorecase: if ignorecase:
data = data.upper() data = data.upper()
match_dict = dict((key.upper(), match_dict[key]) for key in match_dict) match_dict = dict((key.upper(), match_dict[key]) for key in match_dict)
# Si ascii = True, eliminamos todos los accentos y Ñ # If ascii = True, we remove all accents and Ñ
if only_ascii: if only_ascii:
data = ''.join((c for c in unicodedata.normalize('NFD', data) if unicodedata.category(c) != 'Mn')) data = ''.join((c for c in unicodedata.normalize('NFD', data) if unicodedata.category(c) != 'Mn'))
match_dict = dict((''.join((c for c in unicodedata.normalize('NFD', key) if unicodedata.category(c) != 'Mn')), match_dict[key]) for key in match_dict) match_dict = dict((''.join((c for c in unicodedata.normalize('NFD', key) if unicodedata.category(c) != 'Mn')), match_dict[key]) for key in match_dict)
# Ordenamos el listado de mayor tamaño a menor y buscamos. # We sort the list from largest to smallest and search.
for match in sorted(match_dict, key=lambda x: len(x), reverse=True): for match in sorted(match_dict, key=lambda x: len(x), reverse=True):
s = data s = data
for a in matches: for a in matches:
@@ -533,8 +530,7 @@ def get_match_list(data, match_list, order_list=None, only_ascii=False, ignoreca
matches.append(match) matches.append(match)
if matches: if matches:
if order_list: if order_list:
return type("Mtch_list", (), return type("Mtch_list", (), {"key": match_dict[matches[-1]], "index": order_list.index(match_dict[matches[-1]])})
{"key": match_dict[matches[-1]], "index": order_list.index(match_dict[matches[-1]])})
else: else:
return type("Mtch_list", (), {"key": match_dict[matches[-1]], "index": None}) return type("Mtch_list", (), {"key": match_dict[matches[-1]], "index": None})
else: else:
@@ -595,17 +591,17 @@ def download_from_url(url, item):
platformtools.dialog_notification('m3u8 Download',config.get_localized_string(60364), sound=False) platformtools.dialog_notification('m3u8 Download',config.get_localized_string(60364), sound=False)
return {"downloadStatus": STATUS_CODES.error} return {"downloadStatus": STATUS_CODES.error}
# Obtenemos la ruta de descarga y el nombre del archivo # We get the download path and the file name
item.downloadFilename = item.downloadFilename item.downloadFilename = item.downloadFilename
download_path = filetools.dirname(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) download_path = filetools.dirname(filetools.join(DOWNLOAD_PATH, item.downloadFilename))
file_name = filetools.basename(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) file_name = filetools.basename(filetools.join(DOWNLOAD_PATH, item.downloadFilename))
# Creamos la carpeta si no existe # We create the folder if it does not exist
if not filetools.exists(download_path): if not filetools.exists(download_path):
filetools.mkdir(download_path) filetools.mkdir(download_path)
# Lanzamos la descarga # We launch the download
d = Downloader(url, download_path, file_name, d = Downloader(url, download_path, file_name,
max_connections=1 + int(config.get_setting("max_connections", "downloads")), max_connections=1 + int(config.get_setting("max_connections", "downloads")),
block_size=2 ** (17 + int(config.get_setting("block_size", "downloads"))), block_size=2 ** (17 + int(config.get_setting("block_size", "downloads"))),
@@ -620,18 +616,18 @@ def download_from_url(url, item):
d.start_dialog(config.get_localized_string(60332)) d.start_dialog(config.get_localized_string(60332))
# Descarga detenida. Obtenemos el estado: # Download stopped. We get the state:
# Se ha producido un error en la descarga # Download failed
if d.state == d.states.error: if d.state == d.states.error:
log("Error trying to download", url) log("Error trying to download", url)
status = STATUS_CODES.error status = STATUS_CODES.error
# La descarga se ha detenifdo # Download has stopped
elif d.state == d.states.stopped: elif d.state == d.states.stopped:
log("Stop download") log("Stop download")
status = STATUS_CODES.canceled status = STATUS_CODES.canceled
# La descarga ha finalizado # Download is complete
elif d.state == d.states.completed: elif d.state == d.states.completed:
log("Downloaded correctly") log("Downloaded correctly")
status = STATUS_CODES.completed status = STATUS_CODES.completed
@@ -701,7 +697,7 @@ def download_from_server(item):
else: else:
video_urls, puedes, motivo = item.video_urls, True, "" video_urls, puedes, motivo = item.video_urls, True, ""
# Si no esta disponible, salimos # If it is not available, we go out
if not puedes: if not puedes:
log("The video is NOT available") log("The video is NOT available")
return {"downloadStatus": STATUS_CODES.error} return {"downloadStatus": STATUS_CODES.error}
@@ -711,7 +707,7 @@ def download_from_server(item):
result = {} result = {}
# Recorre todas las opciones hasta que consiga descargar una correctamente # Go through all the options until I can download one correctly
for video_url in reversed(video_urls): for video_url in reversed(video_urls):
result = download_from_url(video_url[1], item) result = download_from_url(video_url[1], item)
@@ -719,11 +715,11 @@ def download_from_server(item):
if result["downloadStatus"] in [STATUS_CODES.canceled, STATUS_CODES.completed]: if result["downloadStatus"] in [STATUS_CODES.canceled, STATUS_CODES.completed]:
break break
# Error en la descarga, continuamos con la siguiente opcion # Download error, we continue with the next option
if result["downloadStatus"] == STATUS_CODES.error: if result["downloadStatus"] == STATUS_CODES.error:
continue continue
# Devolvemos el estado # We return the state
return result return result
@@ -737,10 +733,6 @@ def download_from_best_server(item):
if item.downloadItemlist: if item.downloadItemlist:
log('using cached servers') log('using cached servers')
play_items = [Item().fromurl(i) for i in item.downloadItemlist] play_items = [Item().fromurl(i) for i in item.downloadItemlist]
elif item.TorrentName:
path = filetools.join(config.get_data_path(),'elementum_torrent.txt')
url = '/resume/' + item.TorrentName
filetools.write(path, url)
else: else:
if item.contentChannel in ['community', 'videolibrary']: if item.contentChannel in ['community', 'videolibrary']:
channel = __import__('specials.%s' % item.contentChannel, None, None, ['specials.%s' % item.contentChannel]) channel = __import__('specials.%s' % item.contentChannel, None, None, ['specials.%s' % item.contentChannel])
@@ -766,7 +758,7 @@ def download_from_best_server(item):
finally: finally:
progreso.close() progreso.close()
# Recorremos el listado de servers, hasta encontrar uno que funcione # We go through the list of servers, until we find one that works
for play_item in play_items: for play_item in play_items:
play_item = item.clone(**play_item.__dict__) play_item = item.clone(**play_item.__dict__)
play_item.contentAction = play_item.action play_item.contentAction = play_item.action
@@ -777,7 +769,7 @@ def download_from_best_server(item):
# if progreso.iscanceled(): # if progreso.iscanceled():
# result["downloadStatus"] = STATUS_CODES.canceled # result["downloadStatus"] = STATUS_CODES.canceled
# Tanto si se cancela la descarga como si se completa dejamos de probar mas opciones # Whether the download is canceled or completed, we stop trying more options
if result["downloadStatus"] in [STATUS_CODES.canceled, STATUS_CODES.completed]: if result["downloadStatus"] in [STATUS_CODES.canceled, STATUS_CODES.completed]:
result["downloadServer"] = {"url": play_item.url, "server": play_item.server} result["downloadServer"] = {"url": play_item.url, "server": play_item.server}
break break
@@ -820,7 +812,7 @@ def select_server(item):
# if there is only one server select it # if there is only one server select it
seleccion = 1 seleccion = 1
else: else:
# altrimenti mostra la finestra di selezione # otherwise it shows the selection window
seleccion = platformtools.dialog_select(config.get_localized_string(70192), ["Auto"] + [s.title for s in play_items]) seleccion = platformtools.dialog_select(config.get_localized_string(70192), ["Auto"] + [s.title for s in play_items])
if seleccion >= 1: if seleccion >= 1:
@@ -835,14 +827,14 @@ def select_server(item):
def start_download(item): def start_download(item):
log("contentAction: %s | contentChannel: %s | url: %s" % (item.contentAction, item.contentChannel, item.url)) log("contentAction: %s | contentChannel: %s | url: %s" % (item.contentAction, item.contentChannel, item.url))
# Ya tenemnos server, solo falta descargar # We already have a server, we just need to download
if item.contentAction == "play": if item.contentAction == "play":
ret = download_from_server(item) ret = download_from_server(item)
elif item.downloadServer and item.downloadServer.get("server"): elif item.downloadServer and item.downloadServer.get("server"):
ret = download_from_server( ret = download_from_server(
item.clone(server=item.downloadServer.get("server"), url=item.downloadServer.get("url"), item.clone(server=item.downloadServer.get("server"), url=item.downloadServer.get("url"),
contentAction="play")) contentAction="play"))
# No tenemos server, necesitamos buscar el mejor # We don't have a server, we need to find the best
else: else:
ret = download_from_best_server(item) ret = download_from_best_server(item)
@@ -861,21 +853,21 @@ def get_episodes(item):
season_number = item.dlseason season_number = item.dlseason
else: else:
season = False season = False
# El item que pretendemos descargar YA es un episodio # The item we want to download NOW is an episode
if item.contentType == "episode": if item.contentType == "episode":
episodes = [item.clone()] episodes = [item.clone()]
# El item es uma serie o temporada # The item is a series or season
elif item.contentType in ["tvshow", "season"]: elif item.contentType in ["tvshow", "season"]:
if item.downloadItemlist: if item.downloadItemlist:
episodes = [Item().fromurl(i) for i in item.downloadItemlist] episodes = [Item().fromurl(i) for i in item.downloadItemlist]
else: else:
# importamos el canal # The item is a series or season...
if item.contentChannel in ['community', 'videolibrary']: if item.contentChannel in ['community', 'videolibrary']:
channel = __import__('specials.%s' % item.contentChannel, None, None, ["specials.%s" % item.contentChannel]) channel = __import__('specials.%s' % item.contentChannel, None, None, ["specials.%s" % item.contentChannel])
else: else:
channel = __import__('channels.%s' % item.contentChannel, None, None, ["channels.%s" % item.contentChannel]) channel = __import__('channels.%s' % item.contentChannel, None, None, ["channels.%s" % item.contentChannel])
# Obtenemos el listado de episodios # We get the list of episodes
episodes = getattr(channel, item.contentAction)(item) episodes = getattr(channel, item.contentAction)(item)
itemlist = [] itemlist = []
@@ -888,38 +880,38 @@ def get_episodes(item):
else: else:
renumber(episodes, item) renumber(episodes, item)
# Tenemos las lista, ahora vamos a comprobar # We get the list of episodes...
for episode in episodes: for episode in episodes:
# Si partiamos de un item que ya era episodio estos datos ya están bien, no hay que modificarlos # If we started from an item that was already an episode, this data is already good, it should not be modified
if item.contentType != "episode": if item.contentType != "episode":
episode.contentAction = episode.action episode.contentAction = episode.action
episode.contentChannel = episode.channel episode.contentChannel = episode.channel
# Si el resultado es una temporada, no nos vale, tenemos que descargar los episodios de cada temporada # If the result is a season, it is not worth it, we have to download the episodes of each season
if episode.contentType == "season": if episode.contentType == "season":
itemlist.extend(get_episodes(episode)) itemlist.extend(get_episodes(episode))
# Si el resultado es un episodio ya es lo que necesitamos, lo preparamos para añadirlo a la descarga # If the result is an episode is already what we need, we prepare it to add it to the download
if episode.contentType == "episode": if episode.contentType == "episode":
# Pasamos el id al episodio # We pass the id to the episode
if not episode.infoLabels["tmdb_id"]: if not episode.infoLabels["tmdb_id"]:
episode.infoLabels["tmdb_id"] = item.infoLabels["tmdb_id"] episode.infoLabels["tmdb_id"] = item.infoLabels["tmdb_id"]
# Episodio, Temporada y Titulo # Episode, Season and Title
if not episode.contentSeason or not episode.contentEpisodeNumber: if not episode.contentSeason or not episode.contentEpisodeNumber:
season_and_episode = scrapertools.get_season_and_episode(episode.title) season_and_episode = scrapertools.get_season_and_episode(episode.title)
if season_and_episode: if season_and_episode:
episode.contentSeason = season_and_episode.split("x")[0] episode.contentSeason = season_and_episode.split("x")[0]
episode.contentEpisodeNumber = season_and_episode.split("x")[1] episode.contentEpisodeNumber = season_and_episode.split("x")[1]
# Buscamos en tmdb # Episode, Season and Title...
if item.infoLabels["tmdb_id"]: if item.infoLabels["tmdb_id"]:
scraper.find_and_set_infoLabels(episode) scraper.find_and_set_infoLabels(episode)
# Episodio, Temporada y Titulo # Episode, Season and Title
if not episode.contentTitle: if not episode.contentTitle:
episode.contentTitle = re.sub("\[[^\]]+\]|\([^\)]+\)|\d*x\d*\s*-", "", episode.title).strip() episode.contentTitle = re.sub(r"\[[^\]]+\]|\([^\)]+\)|\d*x\d*\s*-", "", episode.title).strip()
episode.downloadFilename = filetools.validate_path(filetools.join(item.downloadFilename, "%dx%0.2d - %s" % (episode.contentSeason, episode.contentEpisodeNumber, episode.contentTitle.strip()))) episode.downloadFilename = filetools.validate_path(filetools.join(item.downloadFilename, "%dx%0.2d - %s" % (episode.contentSeason, episode.contentEpisodeNumber, episode.contentTitle.strip())))
if season: if season:
@@ -929,11 +921,11 @@ def get_episodes(item):
itemlist.append(episode) itemlist.append(episode)
# Cualquier otro resultado no nos vale, lo ignoramos # Any other result is not worth it, we ignore it
else: else:
log("Omitiendo item no válido:", episode.tostring()) log("Omitiendo item no válido:", episode.tostring())
# if Multiple Languages or Qualities # Any other result is not worth it, we ignore it...
itemlist = videolibrarytools.filter_list(itemlist) itemlist = videolibrarytools.filter_list(itemlist)
return itemlist return itemlist
@@ -1079,8 +1071,7 @@ def save_download_movie(item):
progreso.close() progreso.close()
if not platformtools.dialog_yesno(config.get_localized_string(30101), config.get_localized_string(70189)): if not platformtools.dialog_yesno(config.get_localized_string(30101), config.get_localized_string(70189)):
platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle, platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle, config.get_localized_string(30109))
config.get_localized_string(30109))
else: else:
play_item = select_server(item) play_item = select_server(item)
if play_item == 'Auto': if play_item == 'Auto':
@@ -1144,10 +1135,10 @@ def save_download_tvshow(item):
def set_movie_title(item): def set_movie_title(item):
if not item.contentTitle: if not item.contentTitle:
item.contentTitle = re.sub("\[[^\]]+\]|\([^\)]+\)", "", item.contentTitle).strip() item.contentTitle = re.sub(r"\[[^\]]+\]|\([^\)]+\)", "", item.contentTitle).strip()
if not item.contentTitle: if not item.contentTitle:
item.contentTitle = re.sub("\[[^\]]+\]|\([^\)]+\)", "", item.title).strip() item.contentTitle = re.sub(r"\[[^\]]+\]|\([^\)]+\)", "", item.title).strip()
def show_disclaimer(): def show_disclaimer():