KoD 0.8.1

- riorganizzate le impostazioni
- aggiunte descrizioni tag qualità su cb01 (presto anche sugli altri)
- aggiunto il supporto alle serie di polpotv
- fixato server mystream
- fix Rinumerazione per episodi Nuovi
This commit is contained in:
marco
2020-03-14 17:03:57 +01:00
parent c642ddc358
commit 3cdedad7e8
413 changed files with 10944 additions and 1540 deletions

View File

@@ -19,6 +19,8 @@ PLUGIN_NAME = "kod"
__settings__ = xbmcaddon.Addon(id="plugin.video." + PLUGIN_NAME)
__language__ = __settings__.getLocalizedString
channels_data = list()
def get_addon_core():
return __settings__
@@ -97,12 +99,13 @@ def is_xbmc():
def get_videolibrary_support():
return True
def get_channel_url(findhostMethod=None):
def get_channel_url(findhostMethod=None, name=None):
from core import jsontools
import inspect
frame = inspect.stack()[1]
name = os.path.basename(frame[0].f_code.co_filename).replace('.py', '')
if not name:
name = os.path.basename(frame[0].f_code.co_filename).replace('.py', '')
if findhostMethod:
url = jsontools.get_node_from_file(name, 'url')
if not url:
@@ -112,9 +115,11 @@ def get_channel_url(findhostMethod=None):
else:
ROOT_DIR = xbmc.translatePath(__settings__.getAddonInfo('Path'))
LOCAL_FILE = os.path.join(ROOT_DIR, "channels.json")
with open(LOCAL_FILE) as f:
data = jsontools.load(f.read())
return data[name]
global channels_data
if not channels_data:
with open(LOCAL_FILE) as f:
channels_data = jsontools.load(f.read())
return channels_data[name]
def get_system_platform():
""" fonction: pour recuperer la platform que xbmc tourne """
@@ -306,7 +311,7 @@ def set_setting(name, value, channel="", server=""):
canal 'channel'.
Devuelve el valor cambiado o None si la asignacion no se ha podido completar.
Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.kod\settings_channels el
archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
channel_data.json no existe busca en la carpeta channels el archivo channel.json y crea un archivo channel_data.json
antes de modificar el parametro 'name'.

View File

@@ -29,7 +29,7 @@ def init():
"""
Todo el código añadido al add-on se borra con cada actualización. Esta función permite restaurarlo automáticamente con cada actualización. Esto permite al usuario tener su propio código, bajo su responsabilidad, y restaurarlo al add-on cada vez que se actualiza.
El mecanismo funciona copiando el contenido de la carpeta-arbol "./userdata/addon_data/plugin.video.alfa/custom_code/..." sobre
El mecanismo funciona copiando el contenido de la carpeta-arbol "./userdata/addon_data/plugin.video.kod/custom_code/..." sobre
las carpetas de código del add-on. No verifica el contenido, solo vuelca(reemplaza) el contenido de "custom_code".
El usuario almacenará en las subcarpetas de "custom_code" su código actualizado y listo para ser copiado en cualquier momento.
@@ -42,7 +42,7 @@ def init():
from platformcode import custom_code
custom_code.init()
2.- En el inicio de Kodi, comprueba si existe la carpeta "custom_code" en "./userdata/addon_data/plugin.video.alfa/".
2.- En el inicio de Kodi, comprueba si existe la carpeta "custom_code" en "./userdata/addon_data/plugin.video.kod/".
Si no existe, la crea y sale sin más, dando al ususario la posibilidad de copiar sobre esa estructura su código,
y que la función la vuelque sobre el add-on en el próximo inicio de Kodi.
@@ -63,7 +63,7 @@ def init():
try:
#Borra el .zip de instalación de Alfa de la carpeta Packages, por si está corrupto, y que así se pueda descargar de nuevo
version = 'plugin.video.alfa-%s.zip' % config.get_addon_version(with_fix=False)
version = 'plugin.video.kod-%s.zip' % config.get_addon_version(with_fix=False)
filetools.remove(filetools.join(xbmc.translatePath('special://home'), 'addons', 'packages', version), True)
#Verifica si Kodi tiene algún achivo de Base de Datos de Vídeo de versiones anteriores, entonces los borra
@@ -329,6 +329,7 @@ def update_libtorrent():
config.get_setting("libtorrent_path", server="torrent", default="") :
return
try:
from lib.python_libtorrent.python_libtorrent import get_libtorrent
except Exception as e:

View File

@@ -490,7 +490,7 @@ def play_from_library(item):
check_next_ep = nextep.check(item)
window_type = 1 if check_next_ep else config.get_setting("window_type", "videolibrary")
window_type = config.get_setting("window_type", "videolibrary")
# y volvemos a lanzar kodi
if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:

View File

@@ -70,7 +70,7 @@ if DOWNLOAD_LIMIT:
else:
DOWNLOAD_LIMIT = 0
UPLOAD_LIMIT = 100 * 1024
msg_header = 'Alfa MCT Cliente Torrent'
msg_header = 'KoD Client Torrent MCT'
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
@@ -93,7 +93,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
url = decode_adfly(data)
except:
ddd = xbmcgui.Dialog()
ddd.ok( msg_header + ": Sin soporte adf.ly", "El script no tiene soporte para el acortador de urls adf.ly.", "", "url: " + url )
ddd.ok( msg_header + ": No adf.ly support "," The script has no support for the adf.ly url shortener.", "", "url: " + url )
return
"""
@@ -153,10 +153,9 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
except Exception as e:
do = xbmcgui.Dialog()
e = e1 or e2
do.ok('ERROR en el cliente MCT Libtorrent', 'Módulo no encontrado o imcompatible con el dispositivo.',
'Reporte el fallo adjuntando un "log".', str(e))
do.ok(config.get_localized_string(30035) + 'MCT Libtorrent', config.get_localized_string(30036), config.get_localized_string(60015), str(e))
return
log("XXX libtorrent version: %s" % lt.version)
log("##### Torrent file: %s ##" % torrent_file)
@@ -221,7 +220,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
dp = xbmcgui.DialogProgress()
dp.create(msg_header)
while not h.has_metadata():
message, porcent, msg_file, s, download = getProgress(h, "Creando torrent desde magnet")
message, porcent, msg_file, s, download = getProgress(h, "Creating torrent from magnet")
dp.update(porcent, message, msg_file)
if s.state == 1: download = 1
if dp.iscanceled():
@@ -257,7 +256,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
# -- Prioritarizar/Seleccionar archivo-----------------------
_index, video_file, video_size, len_files = get_video_files_sizes( info )
if len_files == 0:
dp = xbmcgui.Dialog().ok("No se puede reproducir", "El torrent no contiene ningún archivo de vídeo")
dp = xbmcgui.Dialog().ok(config.get_localized_string(20000), config.get_localized_string(60339))
if _index < 0:
log("##### parts = %s #########" % str(video_file))
@@ -280,21 +279,18 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
extracted_rar = False
global erase_file_path
erase_file_path = ''
if _video_file_ext == ".rar":
rar = True
filename = video_file
if "/" in filename:
filename = filename.split("/")[1]
if RAR and BACKGROUND:
xbmcgui.Dialog().notification("Encontrado archivo .RAR de %.2f MB" % (video_size / 1048576.0),
"Puedes realizar otras tareas en Kodi mientrastanto. " + \
"Te informaremos...", time=10000)
xbmcgui.Dialog().notification(config.get_localized_string(70768) % (video_size / 1048576.0), config.get_localized_string(70769), time=10000)
dialog = True
else:
dialog = xbmcgui.Dialog().yesno("Encontrado archivo .RAR...", "Nombre: %s" % filename,
"Tamaño: %.2f MB" % (video_size / 1048576.0),
"¿Descargar en segundo plano? Cancelar en menú Descargas")
dialog = xbmcgui.Dialog().yesno(config.get_localized_string(70770), config.get_localized_string(70771) % filename,
config.get_localized_string(70772) % (video_size / 1048576.0), config.get_localized_string(70773))
if dialog:
dp_cerrado = False
dp = xbmcgui.DialogProgressBG()
@@ -365,7 +361,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
dp_cerrado = True
dp = xbmcgui.DialogProgress()
dp.create(msg_header)
# -- Recuperar los datos del progreso -------------------
message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info)
@@ -381,12 +377,12 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
video_file, rar, play_file, erase_path = torr.extract_files(video_file, \
save_path_videos, password, dp, item=item, torr_client='MCT') # ... extraemos el vídeo del RAR
dp.close()
erase_file_path = erase_path
ren_video_file = erase_file_path
extracted_rar = rar
if not play_file:
remove_files( download, torrent_file, erase_file_path, ses, h, ren_video_file )
remove_files( download, torrent_file, erase_file_path, ses, h, ren_video_file, erase_file_path )
return
is_view = "Ok"
save_path_videos = play_file
@@ -421,14 +417,14 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
if not bkg_user:
is_view = "Ok"
else:
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
return
if is_view == "Ok":
# -- Esperando a que termine otra reproducción --------------------------
while xbmc.Player().isPlaying():
xbmc.sleep(3000)
# -- Player - Ver el vídeo --------------------------
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
@@ -533,7 +529,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info)
dp.update(porcent, message, '[CR]' + message + '[CR]' + msg_file)
else:
dp.update(100, "Descarga completa: " + video_file)
dp.update(100, "Download complete: " + video_file)
# -- Se canceló el progreso en el visionado -
# -- Continuar -
@@ -556,26 +552,25 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
player.pause()
is_greater_num_pieces_pause = False
is_greater_num_pieces_canceled = 0
# -- El usuario cancelo el visionado --------
# -- Terminar -
if player.ended:
# -- Diálogo eliminar archivos ----------
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
return
xbmc.sleep(1000)
# -- Kodi - Se cerró el visionado -----------------------
# -- Continuar | Terminar -
if is_view == "Ok" and not xbmc.Player().isPlaying():
dp.close()
if h.status().num_pieces < tot_piece_set:
# -- Diálogo continuar o terminar ---------------
# Preguntamos si el usuario quiere pasar a backgroung
ok = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)",
"Selecciona NO para seguir descargando en segundo plano")
ok = xbmcgui.Dialog().yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032))
else: ok = True
# -- NO ---------------------------------------------
if not ok:
@@ -584,12 +579,12 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
dp_cerrado = False
dp = xbmcgui.DialogProgressBG()
dp.create(msg_header)
else:
# -- Terminar: ----------------------------------
# -- Comprobar si el vídeo pertenece a una ------
# -- lista de archivos -
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
dp.close()
return
"""
@@ -597,7 +592,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
if _index < 0 or len_files == 1:
# -- Diálogo eliminar archivos --------------
#video_file = _video_file
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
dp.close()
return
else:
@@ -618,18 +613,17 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
if not bkg_user and dp_cerrado and dp.iscanceled():
dp.close()
# Preguntamos si el usuario quiere pasar a backgroung
dialog = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)",
"Seleccione NO para seguir descargando en segundo plano")
dialog = xbmcgui.Dialog().yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032))
if not dialog:
bkg_user = True
dp_cerrado = False
dp = xbmcgui.DialogProgressBG()
dp.create(msg_header)
if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT)
else:
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
return
# -- Comprobar si el vídeo pertenece a una lista de -
# -- archivos -
@@ -637,7 +631,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
if _index < 0 or len_files == 1:
# -- Diálogo eliminar archivos ------------------
#video_file = _video_file
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path )
return
else:
# -- Lista de archivos. Diálogo de opciones -----
@@ -651,7 +645,7 @@ def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
if is_view == "Ok" and not xbmc.Player().isPlaying():
dp.close()
# -- Diálogo eliminar archivos --------------------------
remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
remove_files( download, torrent_file, video_file, ses, h, ren_video_file, erase_file_path)
return
@@ -764,7 +758,7 @@ def get_video_files_sizes( info ):
if "/" in _file_name: _file_name = _file_name.split('/')[1]
_file_ext = os.path.splitext( _title )[1]
if '.rar' in _file_ext or '.zip' in _file_ext:
rar_parts += 1
rar_size += _size
@@ -791,7 +785,7 @@ def get_video_files_sizes( info ):
return index, rar_parts, rar_size, len(opciones)
else:
d = xbmcgui.Dialog()
seleccion = d.select(msg_header + ": Selecciona el vídeo, o 'Cancelar' para todos", list(opciones.values()))
seleccion = d.select(msg_header + config.get_localized_string(30034), list(opciones.values()))
else: seleccion = 0
index = list(opciones.keys())[seleccion]
@@ -803,7 +797,7 @@ def get_video_files_sizes( info ):
return index, vfile_name[seleccion], vfile_size[seleccion], len(opciones)
# -- Preguntar si se desea borrar lo descargado -----------------
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="" ):
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", erase_file_path='' ):
dialog_view = False
torrent = False
@@ -815,21 +809,18 @@ def remove_files( download, torrent_file, video_file, ses, h, ren_video_file=""
dialog_view = True
if bkg_user and not extracted_rar:
dialog_view = False
if erase_file_path and erase_file_path != \
os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
if erase_file_path and erase_file_path != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
ren_video_file = erase_file_path
if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != \
os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
ren_video_file = filetools.split(ren_video_file)[0]
elif filetools.isdir(ren_video_file) and ren_video_file == \
os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
elif filetools.isdir(ren_video_file) and ren_video_file == os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
ren_video_file = ''
if dialog_view and ren_video_file:
if h.status().num_pieces >= tot_piece_set:
d = xbmcgui.Dialog()
ok = d.yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)', video_file)
ok = d.yesno(msg_header, config.get_localized_string(30031), video_file)
else:
ok = True
@@ -850,7 +841,7 @@ def remove_files( download, torrent_file, video_file, ses, h, ren_video_file=""
try:
if os.path.isdir(ren_video_file):
filetools.rmdirtree(ren_video_file, silent=True)
elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file):
elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file):
os.remove(ren_video_file)
log("##### erase_file_path: %s" % ren_video_file)
except:
@@ -880,7 +871,7 @@ def remove_files( download, torrent_file, video_file, ses, h, ren_video_file=""
pass
log("### End session #########")
return
return
# -- Descargar de la web los datos para crear el torrent --------

View File

@@ -465,37 +465,37 @@ def set_context_commands(item, parent_item):
else:
context = []
if config.get_setting("faster_item_serialization"):
# logger.info("Reducing serialization!")
itemBK = item
item = Item()
item.action = itemBK.action
item.channel = itemBK.channel
infoLabels = {}
if itemBK.infoLabels["year"]: infoLabels["year"] = itemBK.infoLabels["year"]
if itemBK.infoLabels["imdb_id"]: infoLabels["imdb_id"] = itemBK.infoLabels["imdb_id"]
if itemBK.infoLabels["tmdb_id"]: infoLabels["tmdb_id"] = itemBK.infoLabels["tmdb_id"]
if itemBK.infoLabels["tvdb_id"]: infoLabels["tvdb_id"] = itemBK.infoLabels["tvdb_id"]
if itemBK.infoLabels["noscrap_id"]: infoLabels["noscrap_id"] = itemBK.infoLabels["noscrap_id"]
if len(infoLabels) > 0: item.infoLabels = infoLabels
# if config.get_setting("faster_item_serialization"):
# # logger.info("Reducing serialization!")
# itemBK = item
# item = Item()
# item.action = itemBK.action
# item.channel = itemBK.channel
# infoLabels = {}
# if itemBK.infoLabels["year"]: infoLabels["year"] = itemBK.infoLabels["year"]
# if itemBK.infoLabels["imdb_id"]: infoLabels["imdb_id"] = itemBK.infoLabels["imdb_id"]
# if itemBK.infoLabels["tmdb_id"]: infoLabels["tmdb_id"] = itemBK.infoLabels["tmdb_id"]
# if itemBK.infoLabels["tvdb_id"]: infoLabels["tvdb_id"] = itemBK.infoLabels["tvdb_id"]
# if itemBK.infoLabels["noscrap_id"]: infoLabels["noscrap_id"] = itemBK.infoLabels["noscrap_id"]
# if len(infoLabels) > 0: item.infoLabels = infoLabels
if itemBK.thumbnail: item.thumbnail = itemBK.thumbnail
if itemBK.extra: item.extra = itemBK.extra
if itemBK.contentEpisodeNumber: item.contentEpisodeNumber = itemBK.contentEpisodeNumber
if itemBK.contentEpisodeTitle: item.contentEpisodeTitle = itemBK.contentEpisodeTitle
if itemBK.contentPlot: item.contentPlot = itemBK.contentPlot
if itemBK.contentQuality: item.contentQuality = itemBK.contentQuality
if itemBK.contentSeason: item.contentSeason = itemBK.contentSeason
if itemBK.contentSerieName: item.contentSerieName = itemBK.contentSerieName
if itemBK.contentThumbnail: item.contentThumbnail = itemBK.contentThumbnail
if itemBK.contentTitle: item.contentTitle = itemBK.contentTitle
if itemBK.contentType: item.contentType = itemBK.contentType
if itemBK.duration: item.duration = itemBK.duration
if itemBK.plot: item.plot = itemBK.plot
if itemBK.quality: item.quality = itemBK.quality
if itemBK.show: item.show = itemBK.show
if itemBK.title: item.title = itemBK.title
if itemBK.viewcontent: item.viewcontent = itemBK.viewcontent
# if itemBK.thumbnail: item.thumbnail = itemBK.thumbnail
# if itemBK.extra: item.extra = itemBK.extra
# if itemBK.contentEpisodeNumber: item.contentEpisodeNumber = itemBK.contentEpisodeNumber
# if itemBK.contentEpisodeTitle: item.contentEpisodeTitle = itemBK.contentEpisodeTitle
# if itemBK.contentPlot: item.contentPlot = itemBK.contentPlot
# if itemBK.contentQuality: item.contentQuality = itemBK.contentQuality
# if itemBK.contentSeason: item.contentSeason = itemBK.contentSeason
# if itemBK.contentSerieName: item.contentSerieName = itemBK.contentSerieName
# if itemBK.contentThumbnail: item.contentThumbnail = itemBK.contentThumbnail
# if itemBK.contentTitle: item.contentTitle = itemBK.contentTitle
# if itemBK.contentType: item.contentType = itemBK.contentType
# if itemBK.duration: item.duration = itemBK.duration
# if itemBK.plot: item.plot = itemBK.plot
# if itemBK.quality: item.quality = itemBK.quality
# if itemBK.show: item.show = itemBK.show
# if itemBK.title: item.title = itemBK.title
# if itemBK.viewcontent: item.viewcontent = itemBK.viewcontent
# itemJson = item.tojson()
# logger.info("Elemento: {0} bytes".format(len(itemJson)))
@@ -584,9 +584,9 @@ def set_context_commands(item, parent_item):
# Ir al Menu Principal (channel.mainlist)
if parent_item.channel not in ["news", "channelselector"] and item.action != "mainlist" \
and parent_item.action != "mainlist":
context_commands.append((config.get_localized_string(60349), "XBMC.Container.Refresh (%s?%s)" %
context_commands.insert(0, (config.get_localized_string(60349), "XBMC.Container.Refresh (%s?%s)" %
(sys.argv[0], Item(channel=item.channel, action="mainlist").tourl())))
context_commands.insert(2, (config.get_localized_string(70739),
context_commands.insert(1, (config.get_localized_string(70739),
"XBMC.Container.Update (%s?%s)" % (sys.argv[0], Item(action="open_browser",
url=item.url).tourl())))
@@ -598,11 +598,11 @@ def set_context_commands(item, parent_item):
(sys.argv[0], item.clone(channel="favorites", action="addFavourite",
from_channel=item.channel,
from_action=item.action).tourl())))
# Añadir a Alfavoritos (Mis enlaces)
if item.channel not in ["favorites", "videolibrary", "help", ""] and parent_item.channel != "favorites":
context_commands.append(
('[COLOR blue]%s[/COLOR]' % config.get_localized_string(70557), "XBMC.RunPlugin(%s?%s)" %
(config.get_localized_string(70557), "XBMC.RunPlugin(%s?%s)" %
(sys.argv[0], item.clone(channel="kodfavourites", action="addFavourite",
from_channel=item.channel,
from_action=item.action).tourl())))
@@ -630,7 +630,7 @@ def set_context_commands(item, parent_item):
text=item.wanted).tourl())))
context_commands.append(
("[COLOR yellow]%s[/COLOR]" % config.get_localized_string(70561), "XBMC.Container.Update (%s?%s)" % (
(config.get_localized_string(70561), "XBMC.Container.Update (%s?%s)" % (
sys.argv[0], item.clone(channel='search', action='from_context', search_type='list', page='1',
list_type='%s/%s/similar' % (
mediatype, item.infoLabels['tmdb_id'])).tourl())))
@@ -657,7 +657,7 @@ def set_context_commands(item, parent_item):
(sys.argv[0], item.clone(action="add_pelicula_to_library",
from_action=item.action).tourl())))
if item.channel != "downloads" and item.server != 'torrent':
if item.channel not in ["downloads", "videolibrary"] and item.server != 'torrent':
# Descargar pelicula
if item.contentType == "movie" and item.contentTitle:
context_commands.append((config.get_localized_string(60354), "XBMC.RunPlugin(%s?%s)" %
@@ -672,6 +672,10 @@ def set_context_commands(item, parent_item):
(sys.argv[0], item.clone(channel="downloads", action="save_download",
from_channel=item.channel,
from_action=item.action).tourl())))
context_commands.append((config.get_localized_string(60357), "XBMC.RunPlugin(%s?%s)" %
(sys.argv[0], item.clone(channel="downloads", action="save_download", download="seson",
from_channel=item.channel,
from_action=item.action).tourl())))
# Descargar episodio
elif item.contentType == "episode":
context_commands.append((config.get_localized_string(60356), "XBMC.RunPlugin(%s?%s)" %
@@ -703,7 +707,7 @@ def set_context_commands(item, parent_item):
context_commands.append((config.get_localized_string(60361),
"XBMC.RunScript(special://home/addons/plugin.program.super.favourites/LaunchSFMenu.py)"))
context_commands = sorted(context_commands, key=lambda comand: comand[0])
# context_commands = sorted(context_commands, key=lambda comand: comand[0])
# Menu Rapido
# context_commands.insert(0, (config.get_localized_string(60360),
@@ -712,7 +716,7 @@ def set_context_commands(item, parent_item):
# parent=parent_item.tourl()).tourl(
# ))))
if config.dev_mode():
context_commands.insert(2, ("item info",
context_commands.insert(0, ("item info",
"XBMC.Container.Update (%s?%s)" % (sys.argv[0], Item(action="itemInfo", parent=item.tojson()).tourl())))
return context_commands
@@ -1235,8 +1239,8 @@ def play_torrent(item, xlistitem, mediaurl):
# Opciones disponibles para Reproducir torrents
torrent_options = list()
torrent_options.append(["Cliente interno (necesario libtorrent)"])
torrent_options.append(["Cliente interno MCT (necesario libtorrent)"])
torrent_options.append([config.get_localized_string(30033)])
torrent_options.append([config.get_localized_string(30033) + ' MCT'])
torrent_options.extend(torrent_client_installed(show_tuple=True))
@@ -1263,10 +1267,9 @@ def play_torrent(item, xlistitem, mediaurl):
# Si es Libtorrent y no está soportado, se ofrecen alternativas, si las hay...
if seleccion < 2 and not LIBTORRENT:
dialog_ok('Cliente Interno (LibTorrent):', 'Este cliente no está soportado en su dispositivo.', \
'Error: [COLOR yellow]%s[/COLOR]' % config.get_setting("libtorrent_error", server="torrent",
default=''), \
'Use otro cliente Torrent soportado')
dialog_ok(config.get_localized_string(30033), config.get_localized_string(70774), \
config.get_localized_string(70775) % config.get_setting("libtorrent_error", server="torrent", default=''), \
config.get_localized_string(70776))
if len(torrent_options) > 2:
seleccion = dialog_select(config.get_localized_string(70193), [opcion[0] for opcion in torrent_options])
if seleccion < 2:
@@ -1276,14 +1279,8 @@ def play_torrent(item, xlistitem, mediaurl):
# Si es Torrenter o Elementum con opción de Memoria, se ofrece la posibilidad ee usar Libtorrent temporalemente
elif seleccion > 1 and LIBTORRENT and UNRAR and 'RAR-' in item.torrent_info and (
"torrenter" in torrent_options[seleccion][0] \
or ("elementum" in torrent_options[seleccion][0] and xbmcaddon.Addon(id="plugin.video.%s" \
% torrent_options[seleccion][
0].replace('Plugin externo: ',
'')).getSetting(
'download_storage') == '1')):
if dialog_yesno(torrent_options[seleccion][0], 'Este plugin externo no soporta extraer on-line archivos RAR', \
'[COLOR yellow]¿Quiere que usemos esta vez el Cliente interno MCT?[/COLOR]', \
'Esta operación ocupará en disco [COLOR yellow][B]%s+[/B][/COLOR] veces el tamaño del vídeo' % size_rar):
or ("elementum" in torrent_options[seleccion][0] and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ','')).getSetting('download_storage') == '1')):
if dialog_yesno(torrent_options[seleccion][0], config.get_localized_string(70777), config.get_localized_string(70778), config.get_localized_string(70779) % size_rar):
seleccion = 1
else:
return
@@ -1292,11 +1289,7 @@ def play_torrent(item, xlistitem, mediaurl):
torrent_options[seleccion][0] \
and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', '')) \
.getSetting('download_storage') == '1':
if dialog_yesno(torrent_options[seleccion][0],
'Elementum con descarga en [COLOR yellow]Memoria[/COLOR] no soporta ' + \
'extraer on-line archivos RAR (ocupación en disco [COLOR yellow][B]%s+[/B][/COLOR] veces)' % size_rar, \
'[COLOR yellow]¿Quiere llamar a los Ajustes de Elementum para cambiar [B]temporalmente[/B] ' + \
'a [COLOR hotpink]"Usar Archivos"[/COLOR] y [B]reintentarlo[/B]?[/COLOR]'):
if dialog_yesno(torrent_options[seleccion][0], config.get_localized_string(70780) % size_rar, config.get_localized_string(70781)):
__settings__ = xbmcaddon.Addon(
id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', ''))
__settings__.openSettings() # Se visulizan los Ajustes de Elementum
@@ -1329,17 +1322,14 @@ def play_torrent(item, xlistitem, mediaurl):
password = item.password
videolibrary_path = config.get_videolibrary_path() # Calculamos el path absoluto a partir de la Videoteca
if scrapertools.find_single_match(videolibrary_path,
'(^\w+:\/\/)'): # Si es una conexión REMOTA, usamos userdata local
if scrapertools.find_single_match(videolibrary_path, '(^\w+:\/\/)'): # Si es una conexión REMOTA, usamos userdata local
videolibrary_path = config.get_data_path() # Calculamos el path absoluto a partir de Userdata
if not filetools.exists(videolibrary_path): # Si no existe el path, pasamos al modo clásico
videolibrary_path = False
else:
torrents_path = filetools.join(videolibrary_path, 'temp_torrents_Alfa', \
'cliente_torrent_Alfa.torrent') # path descarga temporal
if not videolibrary_path or not filetools.exists(filetools.join(videolibrary_path, \
'temp_torrents_Alfa')): # Si no existe la carpeta temporal, la creamos
filetools.mkdir(filetools.join(videolibrary_path, 'temp_torrents_Alfa'))
torrents_path = filetools.join(videolibrary_path, 'temp_torrents', 'client_torrent.torrent') # path descarga temporal
if not videolibrary_path or not filetools.exists(filetools.join(videolibrary_path, 'temp_torrents')): # Si no existe la carpeta temporal, la creamos
filetools.mkdir(filetools.join(videolibrary_path, 'temp_torrents'))
# Si hay headers, se pasar a la petición de descarga del .torrent
headers = {}
@@ -1355,10 +1345,7 @@ def play_torrent(item, xlistitem, mediaurl):
if item.referer: referer = item.referer
if item.post: post = item.post
# Descargamos el .torrent
size, url, torrent_f, rar_files = generictools.get_torrent_size(item.url, referer, post, \
torrents_path=torrents_path,
timeout=timeout, lookup=False,
headers=headers, short_pad=True)
size, url, torrent_f, rar_files = generictools.get_torrent_size(item.url, referer, post, torrents_path=torrents_path, timeout=timeout, lookup=False, headers=headers, short_pad=True)
if url:
url_stat = True
item.url = url
@@ -1393,7 +1380,17 @@ def play_torrent(item, xlistitem, mediaurl):
mediaurl = item.url
if seleccion >= 0:
# Si tiene .torrent válido o magnet, lo registramos
if size or item.url.startswith('magnet'):
try:
import threading
if not PY3: from lib import alfaresolver
else: from lib import alfaresolver_py3 as alfaresolver
threading.Thread(target=alfaresolver.frequency_count, args=(item, )).start()
except:
logger.error(traceback.format_exc(1))
# Reproductor propio BT (libtorrent)
if seleccion == 0:
torrent.bt_client(mediaurl, xlistitem, rar_files, subtitle=item.subtitle, password=password, item=item)
@@ -1425,7 +1422,7 @@ def play_torrent(item, xlistitem, mediaurl):
rar_file, save_path_videos, folder_torr = torrent.wait_for_download(rar_files,
torr_client) # Esperamos mientras se descarga el RAR
if rar_file and save_path_videos: # Si se ha descargado el RAR...
dp = dialog_progress_bg('Alfa %s' % torr_client)
dp = dialog_progress_bg('KoD %s' % torr_client)
video_file, rar, video_path, erase_file_path = torrent.extract_files(rar_file, \
save_path_videos, password, dp,
item,
@@ -1452,7 +1449,7 @@ def play_torrent(item, xlistitem, mediaurl):
while is_playing() and rar and not xbmc.abortRequested:
time.sleep(3) # Repetimos cada intervalo
if rar and not xbmc.abortRequested:
if dialog_yesno('Alfa %s' % torr_client, '¿Borrar las descargas del RAR y Vídeo?'):
if dialog_yesno('KoD %s' % torr_client, config.get_localized_string(30031)):
log("##### erase_file_path: %s" % erase_file_path)
try:
torr_data, deamon_url, index = torrent.get_tclient_data(folder_torr, torr_client)

View File

@@ -25,7 +25,7 @@ _hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@.*")
branch = 'stable'
user = 'kodiondemand'
repo = 'addon'
addonDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\', '/') + '/'
addonDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
maxPage = 5 # le api restituiscono 30 commit per volta, quindi se si è rimasti troppo indietro c'è bisogno di andare avanti con le pagine
trackingFile = "last_commit.txt"
changelogFile = "special://profile/addon_data/plugin.video.kod/changelog.txt"
@@ -49,19 +49,20 @@ def loadCommits(page=1):
return ret
# ret -> aggiornato, necessita reload videolibrary_service
def check(background=False):
if not addon.getSetting('addon_update_enabled'):
return False
return False, False
logger.info('Cerco aggiornamenti..')
commits = loadCommits()
if not commits:
return False
return False, False
try:
localCommitFile = open(addonDir+trackingFile, 'r+')
localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+')
except:
calcCurrHash()
localCommitFile = open(addonDir + trackingFile, 'r+')
localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+')
localCommitSha = localCommitFile.read()
localCommitSha = localCommitSha.replace('\n', '') # da testare
logger.info('Commit locale: ' + localCommitSha)
@@ -77,7 +78,7 @@ def check(background=False):
# evitiamo che dia errore perchè il file è già in uso
localCommitFile.close()
calcCurrHash()
return True
return True, False
if pos > 0:
changelog = ''
@@ -115,17 +116,17 @@ def check(background=False):
if 'patch' in file:
text = ""
try:
localFile = io.open(addonDir + file["filename"], 'r+', encoding="utf8")
localFile = io.open(os.path.join(addonDir, file["filename"]), 'r+', encoding="utf8")
text = localFile.read()
if not PY3:
text = text.decode('utf-8')
except IOError: # nuovo file
# crea le cartelle se non esistono
dirname = os.path.dirname(addonDir + file["filename"])
dirname = os.path.dirname(os.path.join(addonDir, file["filename"]))
if not os.path.exists(dirname):
os.makedirs(dirname)
localFile = io.open(addonDir + file["filename"], 'w', encoding="utf8")
localFile = io.open(os.path.join(addonDir, file["filename"]), 'w', encoding="utf8")
patched = apply_patch(text, (file['patch']+'\n').encode('utf-8'))
if patched != text: # non eseguo se già applicata (es. scaricato zip da github)
@@ -143,22 +144,22 @@ def check(background=False):
# se non è già applicato
filename = os.path.join(addonDir, file['filename'])
dirname = os.path.dirname(filename)
if not (filetools.isfile(addonDir + file['filename']) and getSha(filename) == file['sha']):
if not (filetools.isfile(os.path.join(addonDir, file['filename'])) and getSha(filename) == file['sha']):
if not os.path.exists(dirname):
os.makedirs(dirname)
urllib.urlretrieve(file['raw_url'], filename)
alreadyApplied = False
elif file['status'] == 'removed':
remove(addonDir+file["filename"])
remove(os.path.join(addonDir, file["filename"]))
alreadyApplied = False
elif file['status'] == 'renamed':
# se non è già applicato
if not (filetools.isfile(addonDir + file['filename']) and getSha(addonDir + file['filename']) == file['sha']):
if not (filetools.isfile(os.path.join(addonDir, file['filename'])) and getSha(os.path.join(addonDir, file['filename'])) == file['sha']):
dirs = file['filename'].split('/')
for d in dirs[:-1]:
if not filetools.isdir(addonDir + d):
filetools.mkdir(addonDir + d)
filetools.move(addonDir + file['previous_filename'], addonDir + file['filename'])
if not filetools.isdir(os.path.join(addonDir, d)):
filetools.mkdir(os.path.join(addonDir, d))
filetools.move(os.path.join(addonDir, file['previous_filename']), os.path.join(addonDir, file['filename']))
alreadyApplied = False
if not alreadyApplied: # non mando notifica se già applicata (es. scaricato zip da github)
changelog += commitJson['commit']['message'] + "\n"
@@ -212,7 +213,7 @@ def calcCurrHash():
found = False
for n, c in enumerate(commits):
if c['commit']['tree']['sha'] == treeHash:
localCommitFile = open(addonDir + trackingFile, 'w')
localCommitFile = open(os.path.join(addonDir, trackingFile), 'w')
localCommitFile.write(c['sha'])
localCommitFile.close()
found = True
@@ -289,13 +290,15 @@ def updateFromZip(message='Installazione in corso...'):
remotefilename = 'https://github.com/' + user + "/" + repo + "/archive/" + branch + ".zip"
localfilename = filetools.join(xbmc.translatePath("special://home/addons/"), "plugin.video.kod.update.zip")
destpathname = xbmc.translatePath("special://home/addons/")
extractedDir = filetools.join(destpathname, "addon-" + branch)
logger.info("remotefilename=%s" % remotefilename)
logger.info("localfilename=%s" % localfilename)
logger.info('extract dir: ' + extractedDir)
# pulizia preliminare
remove(localfilename)
removeTree(filetools.join(destpathname, "addon-" + branch))
removeTree(extractedDir)
try:
urllib.urlretrieve(remotefilename, localfilename,
@@ -341,10 +344,13 @@ def updateFromZip(message='Installazione in corso...'):
dp.update(99)
# puliamo tutto
removeTree(addonDir)
global addonDir
if extractedDir != addonDir:
removeTree(addonDir)
xbmc.sleep(1000)
rename(filetools.join(destpathname, "addon-" + branch), 'plugin.video.kod')
rename(extractedDir, 'plugin.video.kod')
addonDir = filetools.join(destpathname, 'plugin.video.kod')
logger.info("Cancellando il file zip...")
remove(localfilename)