Traduzioni Platformcode

This commit is contained in:
Alhaziel01
2020-05-27 18:10:34 +02:00
parent 6c320a2290
commit 724bac6159
8 changed files with 417 additions and 531 deletions

View File

@@ -1,19 +1,13 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Parámetros de configuración (kodi)
# Configuration parameters (kodi)
# ------------------------------------------------------------
#from builtins import str
import sys
# from builtins import str
import sys, os, re, xbmc, xbmcaddon
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import os
import re
import xbmc
import xbmcaddon
PLUGIN_NAME = "kod"
__settings__ = xbmcaddon.Addon(id="plugin.video." + PLUGIN_NAME)
@@ -29,7 +23,7 @@ def get_addon_core():
def get_addon_version(with_fix=True):
'''
Devuelve el número de versión del addon, y opcionalmente número de fix si lo hay
Returns the version number of the addon, and optionally fix number if there is one
'''
if with_fix:
return __settings__.getAddonInfo('version') + " " + get_addon_version_fix()
@@ -61,17 +55,17 @@ def dev_mode():
def get_platform(full_version=False):
"""
Devuelve la información la version de xbmc o kodi sobre el que se ejecuta el plugin
Returns the information the version of xbmc or kodi on which the plugin is run
@param full_version: indica si queremos toda la informacion o no
@param full_version: indicates if we want all the information or not
@type full_version: bool
@rtype: str o dict
@return: Si el paramentro full_version es True se retorna un diccionario con las siguientes claves:
'num_version': (float) numero de version en formato XX.X
'name_version': (str) nombre clave de cada version
'video_db': (str) nombre del archivo que contiene la base de datos de videos
'plaform': (str) esta compuesto por "kodi-" o "xbmc-" mas el nombre de la version segun corresponda.
Si el parametro full_version es False (por defecto) se retorna el valor de la clave 'plaform' del diccionario anterior.
@return: If the full_version parameter is True, a dictionary with the following keys is returned:
'num_version': (float) version number in XX.X format
'name_version': (str) key name of each version
'video_db': (str) name of the file that contains the video database
'plaform': (str) is made up of "kodi-" or "xbmc-" plus the version name as appropriate.
If the full_version parameter is False (default) the value of the 'plaform' key from the previous dictionary is returned.
"""
ret = {}
@@ -130,7 +124,7 @@ def get_channel_url(findhostMethod=None, name=None):
return channels_data[name]
def get_system_platform():
""" fonction: pour recuperer la platform que xbmc tourne """
""" function: to recover the platform that xbmc is running """
platform = "unknown"
if xbmc.getCondVisibility("system.platform.linux"):
platform = "linux"
@@ -172,7 +166,7 @@ def enable_disable_autorun(is_enabled):
return True
def get_all_settings_addon():
# Lee el archivo settings.xml y retorna un diccionario con {id: value}
# Read the settings.xml file and return a dictionary with {id: value}
from core import scrapertools
infile = open(os.path.join(get_data_path(), "settings.xml"), "r")
@@ -194,27 +188,26 @@ def open_settings():
def get_setting(name, channel="", server="", default=None):
"""
Retorna el valor de configuracion del parametro solicitado.
Returns the configuration value of the requested parameter.
Devuelve el valor del parametro 'name' en la configuracion global, en la configuracion propia del canal 'channel'
o en la del servidor 'server'.
Returns the value of the parameter 'name' in the global configuration, in the own configuration of the channel 'channel' or in that of the server 'server'.
Los parametros channel y server no deben usarse simultaneamente. Si se especifica el nombre del canal se devolvera
el resultado de llamar a channeltools.get_channel_setting(name, channel, default). Si se especifica el nombre del
servidor se devolvera el resultado de llamar a servertools.get_channel_setting(name, server, default). Si no se
especifica ninguno de los anteriores se devolvera el valor del parametro en la configuracion global si existe o
el valor default en caso contrario.
The channel and server parameters should not be used simultaneously. If the channel name is specified it will be returned
the result of calling channeltools.get_channel_setting (name, channel, default). If the name of the
server will return the result of calling servertools.get_channel_setting (name, server, default). If I dont know
Specify none of the above will return the value of the parameter in the global configuration if it exists or
the default value otherwise.
@param name: nombre del parametro
@param name: parameter name
@type name: str
@param channel: nombre del canal
@param channel: channel name
@type channel: str
@param server: nombre del servidor
@param server: server name
@type server: str
@param default: valor devuelto en caso de que no exista el parametro name
@param default: return value in case the name parameter does not exist
@type default: any
@return: El valor del parametro 'name'
@return: The value of the parameter 'name'
@rtype: any
"""
@@ -261,26 +254,24 @@ def get_setting(name, channel="", server="", default=None):
def set_setting(name, value, channel="", server=""):
"""
Fija el valor de configuracion del parametro indicado.
Sets the configuration value of the indicated parameter.
Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
canal 'channel'.
Devuelve el valor cambiado o None si la asignacion no se ha podido completar.
Set 'value' as the value of the parameter 'name' in the global configuration or in the own configuration of the channel 'channel'.
Returns the changed value or None if the assignment could not be completed.
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'.
Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.
If the name of the channel is specified, search in the path \ addon_data \ plugin.video.kod \ settings_channels the
channel_data.json file and set the parameter 'name' to the value indicated by 'value'. If the file
channel_data.json does not exist look in the channels folder for the channel.json file and create a channel_data.json file before modifying the 'name' parameter.
If the parameter 'name' does not exist, it adds it, with its value, to the corresponding file.
Parametros:
name -- nombre del parametro
value -- valor del parametro
channel [opcional] -- nombre del canal
Parameters:
name - name of the parameter
value - value of the parameter
channel [optional] - channel name
Retorna:
'value' en caso de que se haya podido fijar el valor y None en caso contrario
Returns:
'value' if the value could be set and None otherwise
"""
if channel:
@@ -304,7 +295,7 @@ def set_setting(name, value, channel="", server=""):
except Exception as ex:
from platformcode import logger
logger.error("Error al convertir '%s' no se guarda el valor \n%s" % (name, ex))
logger.error("Error converting '%s' value is not saved \n%s" % (name, ex))
return None
return value
@@ -322,7 +313,7 @@ def get_localized_string(code):
# All encodings to utf8
elif not PY3 and isinstance(dev, str):
dev = unicode(dev, "utf8", errors="replace").encode("utf8")
# Bytes encodings to utf8
elif PY3 and isinstance(dev, bytes):
dev = dev.decode("utf8")
@@ -365,7 +356,7 @@ def get_runtime_path():
def get_data_path():
dev = xbmc.translatePath(__settings__.getAddonInfo('Profile'))
# Crea el directorio si no existe
# Create the directory if it doesn't exist
if not os.path.exists(dev):
os.makedirs(dev)
@@ -405,7 +396,7 @@ def verify_directories_created():
for path, default in config_paths:
saved_path = get_setting(path)
# videoteca
# video store
if path == "videolibrarypath":
if not saved_path:
saved_path = xbmc_videolibrary.search_library_path()
@@ -435,7 +426,7 @@ def verify_directories_created():
if not filetools.exists(content_path):
logger.debug("Creating %s: %s" % (path, content_path))
# si se crea el directorio
# if the directory is created
filetools.mkdir(content_path)
from platformcode import xbmc_videolibrary
@@ -444,11 +435,10 @@ def verify_directories_created():
try:
from core import scrapertools
# Buscamos el archivo addon.xml del skin activo
skindir = filetools.join(xbmc.translatePath("special://home"), 'addons', xbmc.getSkinDir(),
'addon.xml')
if not os.path.isdir(skindir): return # No hace falta mostrar error en el log si no existe la carpeta
# Extraemos el nombre de la carpeta de resolución por defecto
# We look for the addon.xml file of the active skin
skindir = filetools.join(xbmc.translatePath("special://home"), 'addons', xbmc.getSkinDir(), 'addon.xml')
if not os.path.isdir(skindir): return # No need to show error in log if folder doesn't exist
# We extract the name of the default resolution folder
folder = ""
data = filetools.read(skindir)
res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
@@ -457,22 +447,18 @@ def verify_directories_created():
folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
break
# Comprobamos si existe en el addon y sino es así, la creamos
# We check if it exists in the addon and if not, we create it
default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default')
if folder and not filetools.exists(filetools.join(default, folder)):
filetools.mkdir(filetools.join(default, folder))
# Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente
# We copy the file to said folder from the 720p folder if it does not exist or if the size is different
if folder and folder != '720p':
for root, folders, files in filetools.walk(filetools.join(default, '720p')):
for f in files:
if not filetools.exists(filetools.join(default, folder, f)) or \
(filetools.getsize(filetools.join(default, folder, f)) !=
filetools.getsize(filetools.join(default, '720p', f))):
filetools.copy(filetools.join(default, '720p', f),
filetools.join(default, folder, f),
True)
if not filetools.exists(filetools.join(default, folder, f)) or (filetools.getsize(filetools.join(default, folder, f)) != filetools.getsize(filetools.join(default, '720p', f))):
filetools.copy(filetools.join(default, '720p', f), filetools.join(default, folder, f), True)
except:
import traceback
logger.error("Al comprobar o crear la carpeta de resolución")
logger.error("When checking or creating the resolution folder")
logger.error(traceback.format_exc())

View File

@@ -14,23 +14,14 @@ import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import urllib.request, urllib.parse, urllib.error
import os
import re
import socket
import threading
import time
import xbmc
import xbmcgui
import urllib.request, urllib.parse, urllib.error, os, re, socket, threading, time, xbmc, xbmcgui
from core import downloadtools
from platformcode import config, logger
# Download a file and start playing while downloading
def download_and_play(url, file_name, download_path):
# Lanza thread
# Start thread
logger.info("Active threads " + str(threading.active_count()))
logger.info("" + repr(threading.enumerate()))
logger.info("Starting download thread...")
@@ -40,7 +31,7 @@ def download_and_play(url, file_name, download_path):
logger.info("Active threads " + str(threading.active_count()))
logger.info("" + repr(threading.enumerate()))
# Espera
# Wait
logger.info("Waiting...")
while True:
@@ -52,8 +43,7 @@ def download_and_play(url, file_name, download_path):
while not cancelled and download_thread.isAlive():
dialog.update(download_thread.get_progress(), config.get_localized_string(60313),
config.get_localized_string(60314) + str(int(old_div(download_thread.get_speed(), 1024))) + " KB/s " + str(
download_thread.get_actual_size()) + config.get_localized_string(60316) + str(
download_thread.get_total_size()) + "MB",
download_thread.get_actual_size()) + config.get_localized_string(60316) + str( download_thread.get_total_size()) + "MB",
config.get_localized_string(60202) % (str(downloadtools.sec_to_hms(download_thread.get_remaining_time()))))
xbmc.sleep(1000)
@@ -65,25 +55,25 @@ def download_and_play(url, file_name, download_path):
logger.info("End of waiting")
# Lanza el reproductor
# Launch the player
player = CustomPlayer()
player.set_download_thread(download_thread)
player.PlayStream(download_thread.get_file_name())
# Fin de reproducción
logger.info("Fin de reproducción")
# End of playback
logger.info("End of playback")
if player.is_stopped():
logger.info("Terminado por el usuario")
logger.info("Terminated by user")
break
else:
if not download_thread.isAlive():
logger.info("La descarga ha terminado")
logger.info("Download has finished")
break
else:
logger.info("Continua la descarga")
# Cuando el reproductor acaba, si continúa descargando lo para ahora
# When the player finishes, if you continue downloading it for now
logger.info("Download thread alive=" + str(download_thread.isAlive()))
if download_thread.isAlive():
logger.info("Killing download thread")
@@ -141,7 +131,7 @@ class CustomPlayer(xbmc.Player):
# Download in background
class DownloadThread(threading.Thread):
def __init__(self, url, file_name, download_path):
logger.info(repr(file))
# logger.info(repr(file))
self.url = url
self.download_path = download_path
self.file_name = os.path.join(download_path, file_name)
@@ -194,17 +184,17 @@ class DownloadThread(threading.Thread):
logger.info()
comando = "./megacrypter.sh"
logger.info("comando=" + comando)
logger.info("command= " + comando)
oldcwd = os.getcwd()
logger.info("oldcwd=" + oldcwd)
logger.info("oldcwd= " + oldcwd)
cwd = os.path.join(config.get_runtime_path(), "tools")
logger.info("cwd=" + cwd)
logger.info("cwd= " + cwd)
os.chdir(cwd)
logger.info("directory changed to=" + os.getcwd())
logger.info("directory changed to= " + os.getcwd())
logger.info("destino=" + self.download_path)
logger.info("destination= " + self.download_path)
os.system(comando + " '" + self.url + "' \"" + self.download_path + "\"")
# p = subprocess.Popen([comando , self.url , self.download_path], cwd=cwd, stdout=subprocess.PIPE , stderr=subprocess.PIPE )
@@ -218,18 +208,18 @@ class DownloadThread(threading.Thread):
headers = []
# Se asegura de que el fichero se podrá crear
logger.info("nombrefichero=" + self.file_name)
# Ensures that the file can be created
logger.info("filename= " + self.file_name)
self.file_name = xbmc.makeLegalFilename(self.file_name)
logger.info("nombrefichero=" + self.file_name)
logger.info("url=" + self.url)
logger.info("filename= " + self.file_name)
logger.info("url= " + self.url)
# Crea el fichero
# Create the file
existSize = 0
f = open(self.file_name, 'wb')
grabado = 0
# Interpreta las cabeceras en una URL como en XBMC
# Interpret headers in a URL like in XBMC
if "|" in self.url:
additional_headers = self.url.split("|")[1]
if "&" in additional_headers:
@@ -244,7 +234,7 @@ class DownloadThread(threading.Thread):
headers.append([name, value])
self.url = self.url.split("|")[0]
logger.info("url=" + self.url)
logger.info("url= " + self.url)
# Timeout del socket a 60 segundos
socket.setdefaulttimeout(60)
@@ -253,7 +243,7 @@ class DownloadThread(threading.Thread):
h = urllib.request.HTTPHandler(debuglevel=0)
request = urllib.request.Request(self.url)
for header in headers:
logger.info("Header=" + header[0] + ": " + header[1])
logger.info("Header= " + header[0] + ": " + header[1])
request.add_header(header[0], header[1])
# Lanza la petición
@@ -262,14 +252,14 @@ class DownloadThread(threading.Thread):
try:
connexion = opener.open(request)
except urllib.error.HTTPError as e:
logger.error("error %d (%s) al abrir la url %s" % (e.code, e.msg, self.url))
logger.error("error %d (%s) opening url %s" % (e.code, e.msg, self.url))
# print e.code
# print e.msg
# print e.hdrs
# print e.fp
f.close()
# El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo
# Error 416 is that the requested range is greater than the file => is that it is already complete
if e.code == 416:
return 0
else:
@@ -286,21 +276,21 @@ class DownloadThread(threading.Thread):
blocksize = 100 * 1024
bloqueleido = connexion.read(blocksize)
logger.info("Iniciando descarga del fichero, bloqueleido=%s" % len(bloqueleido))
logger.info("Starting file download, blocked= %s" % len(bloqueleido))
maxreintentos = 10
while len(bloqueleido) > 0:
try:
if os.path.exists(self.force_stop_file_name):
logger.info("Detectado fichero force_stop, se interrumpe la descarga")
logger.info("Force_stop file detected, download is interrupted")
f.close()
xbmc.executebuiltin("XBMC.Notification(%s,%s,300)" % (config.get_localized_string(60319),config.get_localized_string(60320)))
return
# Escribe el bloque leido
# Write the block read
# try:
# import xbmcvfs
# f.write( bloqueleido )
@@ -309,12 +299,12 @@ class DownloadThread(threading.Thread):
grabado = grabado + len(bloqueleido)
logger.info("grabado=%d de %d" % (grabado, totalfichero))
percent = int(float(grabado) * 100 / float(totalfichero))
self.progress = percent;
self.progress = percent
totalmb = float(float(totalfichero) / (1024 * 1024))
descargadosmb = float(float(grabado) / (1024 * 1024))
self.actual_size = int(descargadosmb)
# Lee el siguiente bloque, reintentando para no parar todo al primer timeout
#Read the next block, retrying not to stop everything at the first timeout
reintentos = 0
while reintentos <= maxreintentos:
try:
@@ -333,13 +323,13 @@ class DownloadThread(threading.Thread):
except:
import sys
reintentos = reintentos + 1
logger.info("ERROR en la descarga del bloque, reintento %d" % reintentos)
logger.info("ERROR in block download, retry %d" % reintentos)
for line in sys.exc_info():
logger.error("%s" % line)
# Ha habido un error en la descarga
# There was an error in the download
if reintentos > maxreintentos:
logger.error("ERROR en la descarga del fichero")
logger.error("ERROR in the file download")
f.close()
return -2

View File

@@ -10,13 +10,7 @@ import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import xbmc
import xbmcaddon
import os
import subprocess
import re
import platform
import xbmc, xbmcaddon, os, subprocess, re, platform
try:
import ctypes
@@ -123,18 +117,14 @@ def get_environment():
environment['kodi_bmode'] = '0'
environment['kodi_rfactor'] = '4.0'
if filetools.exists(filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")):
advancedsettings = filetools.read(filetools.join(xbmc.translatePath("special://userdata"),
"advancedsettings.xml")).split('\n')
advancedsettings = filetools.read(filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")).split('\n')
for label_a in advancedsettings:
if 'memorysize' in label_a:
environment['kodi_buffer'] = str(old_div(int(scrapertools.find_single_match
(label_a, '>(\d+)<\/')), 1024 ** 2))
environment['kodi_buffer'] = str(old_div(int(scrapertools.find_single_match(label_a, r'>(\d+)<\/')), 1024 ** 2))
if 'buffermode' in label_a:
environment['kodi_bmode'] = str(scrapertools.find_single_match
(label_a, '>(\d+)<\/'))
environment['kodi_bmode'] = str(scrapertools.find_single_match(label_a, r'>(\d+)<\/'))
if 'readfactor' in label_a:
environment['kodi_rfactor'] = str(scrapertools.find_single_match
(label_a, '>(.*?)<\/'))
environment['kodi_rfactor'] = str(scrapertools.find_single_match(label_a, r'>(.*?)<\/'))
except:
pass
@@ -142,14 +132,12 @@ def get_environment():
try:
if environment['os_name'].lower() == 'windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['userdata_path']),
None, None, ctypes.pointer(free_bytes))
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes))
environment['userdata_free'] = str(round(float(free_bytes.value) / (1024 ** 3), 3))
else:
disk_space = os.statvfs(environment['userdata_path'])
if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize
environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \
(1024 ** 3)) * float(disk_space.f_frsize), 3))
environment['userdata_free'] = str(round((float(disk_space.f_bavail) / (1024 ** 3)) * float(disk_space.f_frsize), 3))
except:
environment['userdata_free'] = '?'
@@ -158,22 +146,15 @@ def get_environment():
environment['videolab_episodios'] = '?'
environment['videolab_pelis'] = '?'
environment['videolab_path'] = str(xbmc.translatePath(config.get_videolibrary_path()))
if filetools.exists(filetools.join(environment['videolab_path'], \
config.get_setting("folder_tvshows"))):
environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
config.get_setting(
"folder_tvshows")))))
if filetools.exists(filetools.join(environment['videolab_path'], config.get_setting("folder_tvshows"))):
environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], config.get_setting("folder_tvshows")))))
counter = 0
for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \
config.get_setting("folder_tvshows"))):
for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], config.get_setting("folder_tvshows"))):
for file in files:
if file.endswith('.strm'): counter += 1
environment['videolab_episodios'] = str(counter)
if filetools.exists(filetools.join(environment['videolab_path'], \
config.get_setting("folder_movies"))):
environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
config.get_setting(
"folder_movies")))))
if filetools.exists(filetools.join(environment['videolab_path'], config.get_setting("folder_movies"))):
environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], config.get_setting("folder_movies")))))
except:
pass
try:
@@ -184,14 +165,12 @@ def get_environment():
try:
if environment['os_name'].lower() == 'windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['videolab_path']),
None, None, ctypes.pointer(free_bytes))
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes))
environment['videolab_free'] = str(round(float(free_bytes.value) / (1024 ** 3), 3))
else:
disk_space = os.statvfs(environment['videolab_path'])
if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize
environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \
(1024 ** 3)) * float(disk_space.f_frsize), 3))
environment['videolab_free'] = str(round((float(disk_space.f_bavail) / (1024 ** 3)) * float(disk_space.f_frsize), 3))
except:
environment['videolab_free'] = '?'
@@ -439,131 +418,116 @@ def paint_env(item, environment={}):
thumb = get_thumb("setting_0.png")
cabecera = """\
Muestra las [COLOR yellow]variables[/COLOR] del ecosistema de Kodi que puden ser relevantes para el diagnóstico de problema en Alfa:
- Versión de Alfa con Fix
It shows the [COLOR yellow] variables [/ COLOR] of the Kodi ecosystem that may be relevant to the problem diagnosis in Alpha:
- Alpha version with Fix
- Debug Alfa: True/False
"""
plataform = """\
Muestra los datos especificos de la [COLOR yellow]plataforma[/COLOR] en la que está alojado Kodi:
- Sistema Operativo
- Modelo (opt)
- Versión SO
- Procesador
- Aquitectura
- Idioma de Kodi
It shows the specific data of the [COLOR yellow] platform [/ COLOR] where Kodi is hosted:
- Operating system
- Model (opt)
- SO version
- Processor
- Architecture
- Kodi language
"""
kodi = """\
Muestra los datos especificos de la instalación de [COLOR yellow]Kodi[/COLOR]:
- Versión de Kodi
- Base de Datos de Vídeo
- Versión de Python
It shows the specific data of the installation of [COLOR yellow] Kodi [/ COLOR]:
- Kodi version
- Video Database
- Python version
"""
cpu = """\
Muestra los datos consumo actual de [COLOR yellow]CPU(s)[/COLOR]
Displays the current consumption data of [COLOR yellow] CPU (s) [/ COLOR]
"""
memoria = """\
Muestra los datos del uso de [COLOR yellow]Memoria[/COLOR] del sistema:
- Memoria total
- Memoria disponible
Displays the usage data of [COLOR yellow] System [/ COLOR] memory:
- Total memory
- Available memory
- en [COLOR yellow]Advancedsettings.xml[/COLOR]
- Buffer de memoria
configurado:
para Kodi: 3 x valor de
- Memory buffer
configured:
for Kodi: 3 x value of
<memorysize>
- Buffermode: cachea:
- Buffermode: cache:
* Internet (0, 2)
* También local (1)
* Also local (1)
* No Buffer (3)
- Readfactor: readfactor *
avg bitrate vídeo
- Readfactor: readfactor *
avg bitrate video
"""
userdata = """\
Muestra los datos del "path" de [COLOR yellow]Userdata[/COLOR]:
It shows the data of the "path" of [COLOR yellow] Userdata [/ COLOR]:
- Path
- Espacio disponible
- Available space
"""
videoteca = """\
Muestra los datos de la [COLOR yellow]Videoteca[/COLOR]:
- Nº de Series y Episodios
- Nº de Películas
- Tipo de actulización
It shows the data of the [COLOR yellow] Video Library [/ COLOR]:
- Number of Series and Episodes
- No. of Movies
- Update type
- Path
- Espacio disponible
- Available space
"""
torrent = """\
Muestra los datos generales del estado de [COLOR yellow]Torrent[/COLOR]:
- ID del cliente seleccionado
- Descompresión automática de archivos RAR?
- Está activo Libtorrent?
- Se descomprimen los RARs en background?
- Está operativo el módulo UnRAR? Qué plataforma?
It shows the general data of the status of [COLOR yellow] Torrent [/ COLOR]:
- ID of the selected customer
- Automatic decompression of RAR files?
- Is Libtorrent active?
- Are RARs decompressed in the background?
- Is the UnRAR module operational? Which platform?
"""
torrent_error = """\
Muestra los datos del error de importación de [COLOR yellow]Libtorrent[/COLOR]
Displays the import error data for [COLOR yellow] Libtorrent [/ COLOR]
"""
torrent_cliente = """\
Muestra los datos de los [COLOR yellow]Clientes Torrent[/COLOR]:
- Nombre del Cliente
- Tamaño de buffer inicial
- Path de descargas
- Tamaño de buffer en Memoria
It shows the data of the [COLOR yellow] Torrent Clients [/ COLOR]:
- Customer name
- Initial buffer size
- Download path
- Memory buffer size
(opt, si no disco)
- Espacio disponible
- Available space
"""
proxy = """\
Muestra las direcciones de canales o servidores que necesitan [COLOR yellow]Proxy[/COLOR]
Shows the addresses of channels or servers that need [COLOR yellow] Proxy [/ COLOR]
"""
log = """\
Muestra el tamaño actual del [COLOR yellow]Log[/COLOR]
Displays the current size of the [COLOR yellow] Log [/ COLOR]
"""
reporte = """\
Enlaza con la utilidad que permite el [COLOR yellow]envío del Log[/COLOR] de Kodi a través de un servicio Pastebin
Links with the utility that allows the [COLOR yellow] to send the Kodi Log [/ COLOR] through a Pastebin service
"""
itemlist.append(Item(channel=item.channel, title="[COLOR orange][B]Variables " +
"de entorno Alfa: %s Debug: %s[/B][/COLOR]" %
(environment['addon_version'], environment['debug']),
itemlist.append(Item(channel=item.channel, title="KoD environment variables: %s Debug: %s" % (environment['addon_version'], environment['debug']),
action="", plot=cabecera, thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]%s[/COLOR]' %
environment['os_name'] + ' ' + environment['prod_model'] + ' ' +
environment['os_release'] + ' ' + environment['machine'] + ' ' +
environment['architecture'] + ' ' + environment['language'],
itemlist.append(Item(channel=item.channel, title=environment['os_name'] + ' ' + environment['prod_model'] + ' ' + environment['os_release'] + ' ' + environment['machine'] + ' ' + environment['architecture'] + ' ' + environment['language'],
action="", plot=plataform, thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Kodi [/COLOR]' +
environment['num_version'] + ', Vídeo: ' + environment[
'video_db'] +
', Python ' + environment['python_version'], action="",
itemlist.append(Item(channel=item.channel, title='Kodi ' + environment['num_version'] + ', Vídeo: ' + environment[ 'video_db'] + ', Python ' + environment['python_version'], action="",
plot=kodi, thumbnail=thumb, folder=False))
if environment['cpu_usage']:
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]CPU: [/COLOR]' +
environment['cpu_usage'], action="", plot=cpu, thumbnail=thumb,
folder=False))
itemlist.append(Item(channel=item.channel, title='CPU: ' + environment['cpu_usage'], action="", plot=cpu, thumbnail=thumb, folder=False))
if environment['mem_total'] or environment['mem_free']:
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Memoria: [/COLOR]Total: ' +
itemlist.append(Item(channel=item.channel, title='Memory: Total: ' +
environment['mem_total'] + ' MB / Disp.: ' +
environment['mem_free'] + ' MB / Buffers: ' +
str(int(
environment['kodi_buffer']) * 3) + ' MB / Buffermode: ' +
str(int(environment['kodi_buffer']) * 3) + ' MB / Buffermode: ' +
environment['kodi_bmode'] + ' / Readfactor: ' +
environment['kodi_rfactor'],
action="", plot=memoria, thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Userdata: [/COLOR]' +
environment['userdata_path'] + ' - Free: ' + environment[
'userdata_free'].replace('.', ',') +
itemlist.append(Item(channel=item.channel, title='Userdata:' +
environment['userdata_path'] + ' - Free: ' + environment[ 'userdata_free'].replace('.', ',') +
' GB', action="", plot=userdata, thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Videoteca: [/COLOR]Series/Epis: ' +
environment['videolab_series'] + '/' + environment[
'videolab_episodios'] +
' - Pelis: ' + environment['videolab_pelis'] + ' - Upd: ' +
environment['videolab_update'] + ' - Path: ' +
environment['videolab_path'] + ' - Free: ' + environment[
'videolab_free'].replace('.', ',') +
itemlist.append(Item(channel=item.channel, title='Video store: Series/Epis: ' +
environment['videolab_series'] + '/' + environment['videolab_episodios'] +
' - Movie: ' + environment['videolab_pelis'] + ' - Upd: ' + environment['videolab_update'] + ' - Path: ' +
environment['videolab_path'] + ' - Free: ' + environment[ 'videolab_free'].replace('.', ',') +
' GB', action="", plot=videoteca, thumbnail=thumb, folder=False))
if environment['torrent_list']:
@@ -571,41 +535,27 @@ def paint_env(item, environment={}):
if x == 0:
cliente_alt = cliente.copy()
del cliente_alt['Torrent_opt']
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Torrent: [/COLOR]Opt: %s, %s' \
% (str(cliente['Torrent_opt']),
str(cliente_alt).replace('{', '').replace('}', '') \
.replace("'", '').replace('_', ' ')), action="",
plot=torrent, thumbnail=thumb,
folder=False))
itemlist.append(Item(channel=item.channel, title='Torrent: Opt: %s, %s' % (str(cliente['Torrent_opt']), str(cliente_alt).replace('{', '').replace('}', '').replace("'", '').replace('_', ' ')), action="",
plot=torrent, thumbnail=thumb, folder=False))
elif x == 1 and environment['torrent_error']:
itemlist.append(Item(channel=item.channel,
title='[COLOR magenta]- %s[/COLOR]' % str(cliente).replace('{', '').replace('}',
'') \
.replace("'", '').replace('_', ' '), action="", plot=torrent_error,
thumbnail=thumb,
folder=False))
title=str(cliente).replace('{', '').replace('}','').replace("'", '').replace('_', ' '), action="", plot=torrent_error,
thumbnail=thumb, folder=False))
else:
cliente_alt = cliente.copy()
del cliente_alt['Plug_in']
cliente_alt['Libre'] = cliente_alt['Libre'].replace('.', ',') + ' GB'
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]- %s: [/COLOR]: %s' %
(str(cliente['Plug_in']),
str(cliente_alt).replace('{', '').replace('}', '') \
.replace("'", '').replace('\\\\', '\\')), action="",
plot=torrent_cliente,
thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='- %s: %s' % (str(cliente['Plug_in']), str(cliente_alt).replace('{', '').replace('}', '').replace("'", '').replace('\\\\', '\\')), action="",
plot=torrent_cliente, thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]Proxy: [/COLOR]' +
environment['proxy_active'], action="", plot=proxy,
thumbnail=thumb,
folder=False))
itemlist.append(Item(channel=item.channel, title='Proxy: ' + environment['proxy_active'], action="", plot=proxy,
thumbnail=thumb, folder=False))
itemlist.append(Item(channel=item.channel, title='[COLOR yellow]TAMAÑO del LOG: [/COLOR]' +
environment['log_size'].replace('.', ',') + ' MB', action="",
itemlist.append(Item(channel=item.channel, title='LOG SIZE: ' + environment['log_size'].replace('.', ',') + ' MB', action="",
plot=log, thumbnail=thumb,
folder=False))
itemlist.append(Item(title="[COLOR hotpink][B]==> Reportar un fallo[/B][/COLOR]",
itemlist.append(Item(title="==> Report a bug",
channel="setting", action="report_menu", category='Configuración',
unify=False, plot=reporte, thumbnail=get_thumb("error.png")))

View File

@@ -11,31 +11,30 @@ PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
# if PY3:
# import urllib.error as urllib2 # Es muy lento en PY2. En PY3 es nativo
# import urllib.error as urllib2 # It is very slow in PY2. In PY3 it is native
# else:
# import urllib2 # Usamos el nativo de PY2 que es más rápido
# import urllib2 # We use the native of PY2 which is faster
import os
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools
from platformcode import config, logger, platformtools
from platformcode.logger import WebErrorException
def start():
""" Primera funcion que se ejecuta al entrar en el plugin.
Dentro de esta funcion deberian ir todas las llamadas a las
funciones que deseamos que se ejecuten nada mas abrir el plugin.
""" First function that is executed when entering the plugin.
Within this function all calls should go to
functions that we want to execute as soon as we open the plugin.
"""
logger.info()
#config.set_setting('show_once', True)
# config.set_setting('show_once', True)
# Test if all the required directories are created
config.verify_directories_created()
# controlla se l'utente ha qualche problema di connessione
# se lo ha: non lo fa entrare nell'addon
# se ha problemi di DNS avvia ma lascia entrare
# se tutto ok: entra nell'addon
# check if the user has any connection problems
# if it has: it does not enter the addon
# if it has DNS problems start but let in
# if everything is ok: enter the addon
from specials.checkhost import test_conn
import threading
@@ -191,7 +190,7 @@ def run(item=None):
# Special play action
if item.action == "play":
#define la info para trakt
# define la info para trakt
try:
from core import trakt_tools
trakt_tools.set_trakt_info(item)
@@ -444,14 +443,14 @@ def limit_itemlist(itemlist):
def play_from_library(item):
itemlist=[]
"""
Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
más items, como mucho se puede colocar un dialogo de seleccion.
Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
"Container.Update()" cargamos el strm como si un item desde dentro del addon se tratara, quitando todas
las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
la videoteca.
The .strm files when played from kodi, this expects it to be a "playable" file so it cannot contain
more items, at most a selection dialog can be placed.
We solve this by "cheating kodi" and making him believe that something has been reproduced, so later by
"Container.Update ()" we load the strm as if an item from inside the addon were treated, removing all
the limitations and allowing to reproduce through the general function without having to create new methods to
the video library.
@type item: item
@param item: elemento con información
@param item: item with information
"""
item.fromLibrary = True
logger.info()
@@ -463,30 +462,28 @@ def play_from_library(item):
from time import sleep, time
from specials import nextep
# Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
xbmcgui.ListItem(
path=os.path.join(config.get_runtime_path(), "resources", "kod.mp4")))
# We try to reproduce an image (this does nothing and also does not give an error)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "resources", "kod.mp4")))
# Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
# sleep(0.5) ### Si no se pone esto se bloquea Kodi
# Just in case the image did (in future versions) we give stop to stop the reproduction
# sleep(0.5) ### If you don't put this on you crash Kodi
xbmc.Player().stop()
# modificamos el action (actualmente la videoteca necesita "findvideos" ya que es donde se buscan las fuentes
# we modify the action (currently the video library needs "findvideos" since this is where the sources are searched
item.action = "findvideos"
check_next_ep = nextep.check(item)
window_type = config.get_setting("window_type", "videolibrary")
# y volvemos a lanzar kodi
# and we launch kodi again
if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:
# Ventana convencional
# Conventional window
xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")")
else:
# Ventana emergente
# Pop-up window
item.show_server = True
from specials import videolibrary, autoplay
@@ -505,22 +502,22 @@ def play_from_library(item):
else:
while platformtools.is_playing():
# Ventana convencional
# Conventional window
sleep(5)
p_dialog.update(50, '')
it = item
if item.show_server or not check_next_ep:
'''# Se filtran los enlaces segun la lista negra
if config.get_setting('filter_servers', "servers"):
itemlist = servertools.filter_servers(itemlist)'''
# The links are filtered according to the blacklist
# if config.get_setting('filter_servers', "servers"):
# itemlist = servertools.filter_servers(itemlist)
# Se limita la cantidad de enlaces a mostrar
# The number of links to show is limited
if config.get_setting("max_links", "videolibrary") != 0:
itemlist = limit_itemlist(itemlist)
# Se "limpia" ligeramente la lista de enlaces
# The list of links is slightly "cleaned"
if config.get_setting("replace_VD", "videolibrary") == 1:
itemlist = reorder_itemlist(itemlist)
@@ -532,12 +529,12 @@ def play_from_library(item):
if len(itemlist) > 0:
while not xbmc.Monitor().abortRequested():
# El usuario elige el mirror
# The user chooses the mirror
opciones = []
for item in itemlist:
opciones.append(item.title)
# Se abre la ventana de seleccion
# The selection window opens
if (item.contentSerieName != "" and
item.contentSeason != "" and
item.contentEpisodeNumber != ""):

View File

@@ -21,7 +21,7 @@ def log_enable(active):
def encode_log(message=""):
# Unicode to utf8
if isinstance(message, unicode):
message = message.encode("utf8")
@@ -30,7 +30,7 @@ def encode_log(message=""):
# All encodings to utf8
elif not PY3 and isinstance(message, str):
message = unicode(message, "utf8", errors="replace").encode("utf8")
# Bytes encodings to utf8
elif PY3 and isinstance(message, bytes):
message = message.decode("utf8")
@@ -43,7 +43,7 @@ def encode_log(message=""):
def get_caller(message=None):
if message and isinstance(message, unicode):
message = message.encode("utf8")
if PY3: message = message.decode("utf8")
@@ -52,8 +52,8 @@ def get_caller(message=None):
elif message and not PY3:
message = unicode(message, "utf8", errors="replace").encode("utf8")
elif message:
message = str(message)
message = str(message)
module = inspect.getmodule(inspect.currentframe().f_back.f_back)
if module == None:

View File

@@ -9,19 +9,16 @@ if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
#from future import standard_library
#standard_library.install_aliases()
import urllib.parse as urllib # Es muy lento en PY2. En PY3 es nativo
import urllib.parse as urllib # It is very slow in PY2. In PY3 it is native
else:
import urllib # Usamos el nativo de PY2 que es más rápido
import urllib # We use the native of PY2 which is faster
import os
import re
import string
from unicodedata import normalize
from core import filetools
from core import httptools
from core import jsontools
from core import scrapertools
from core import filetools, httptools, jsontools, scrapertools
import xbmc
import xbmcgui
@@ -32,22 +29,22 @@ if not PY3: allchars = string.maketrans('', '')
deletechars = ',\\/:*"<>|?'
# Extraemos el nombre de la serie, temporada y numero de capitulo ejemplo: 'fringe 1x01'
# We extract the name of the series, season and chapter number example: 'fringe 1x01'
def regex_tvshow(compare, file, sub=""):
regex_expressions = ['[Ss]([0-9]+)[][._-]*[Ee]([0-9]+)([^\\\\/]*)$',
'[\._ \-]([0-9]+)x([0-9]+)([^\\/]*)', # foo.1x09
'[\._ \-]([0-9]+)([0-9][0-9])([\._ \-][^\\/]*)', # foo.109
'([0-9]+)([0-9][0-9])([\._ \-][^\\/]*)',
'[\\\\/\\._ -]([0-9]+)([0-9][0-9])[^\\/]*',
'Season ([0-9]+) - Episode ([0-9]+)[^\\/]*',
'Season ([0-9]+) Episode ([0-9]+)[^\\/]*',
'[\\\\/\\._ -][0]*([0-9]+)x[0]*([0-9]+)[^\\/]*',
'[[Ss]([0-9]+)\]_\[[Ee]([0-9]+)([^\\/]*)', # foo_[s01]_[e01]
'[\._ \-][Ss]([0-9]+)[\.\-]?[Ee]([0-9]+)([^\\/]*)', # foo, s01e01, foo.s01.e01, foo.s01-e01
's([0-9]+)ep([0-9]+)[^\\/]*', # foo - s01ep03, foo - s1ep03
'[Ss]([0-9]+)[][ ._-]*[Ee]([0-9]+)([^\\\\/]*)$',
'[\\\\/\\._ \\[\\(-]([0-9]+)x([0-9]+)([^\\\\/]*)$',
'[\\\\/\\._ \\[\\(-]([0-9]+)X([0-9]+)([^\\\\/]*)$'
regex_expressions = [r'[Ss]([0-9]+)[][._-]*[Ee]([0-9]+)([^\\\\/]*)$',
r'[\._ \-]([0-9]+)x([0-9]+)([^\\/]*)', # foo.1x09
r'[\._ \-]([0-9]+)([0-9][0-9])([\._ \-][^\\/]*)', # foo.109
r'([0-9]+)([0-9][0-9])([\._ \-][^\\/]*)',
r'[\\\\/\\._ -]([0-9]+)([0-9][0-9])[^\\/]*',
r'Season ([0-9]+) - Episode ([0-9]+)[^\\/]*',
r'Season ([0-9]+) Episode ([0-9]+)[^\\/]*',
r'[\\\\/\\._ -][0]*([0-9]+)x[0]*([0-9]+)[^\\/]*',
r'[[Ss]([0-9]+)\]_\[[Ee]([0-9]+)([^\\/]*)', # foo_[s01]_[e01]
r'[\._ \-][Ss]([0-9]+)[\.\-]?[Ee]([0-9]+)([^\\/]*)', # foo, s01e01, foo.s01.e01, foo.s01-e01
r's([0-9]+)ep([0-9]+)[^\\/]*', # foo - s01ep03, foo - s1ep03
r'[Ss]([0-9]+)[][ ._-]*[Ee]([0-9]+)([^\\\\/]*)$',
r'[\\\\/\\._ \\[\\(-]([0-9]+)x([0-9]+)([^\\\\/]*)$',
r'[\\\\/\\._ \\[\\(-]([0-9]+)X([0-9]+)([^\\\\/]*)$'
]
sub_info = ""
tvshow = 0
@@ -83,8 +80,7 @@ def regex_tvshow(compare, file, sub=""):
else:
return "", "", ""
# Obtiene el nombre de la pelicula o capitulo de la serie guardado previamente en configuraciones del plugin
# y luego lo busca en el directorio de subtitulos, si los encuentra los activa.
# Gets the name of the movie or episode of the series previously saved in plugin settings and then searches for it in the subtitles directory, if it finds them, activates them.
def set_Subtitle():
@@ -134,7 +130,7 @@ def set_Subtitle():
except:
logger.error("error al cargar subtitulos")
# Limpia los caracteres unicode
# Clean unicode characters
def _normalize(title, charset='utf-8'):
@@ -222,9 +218,7 @@ def searchSubtitle(item):
filetools.join(full_path_tvshow, "%s %sx%s.mp4" % (tvshow_title, season, episode)))
logger.info(full_path_video_new)
listitem = xbmcgui.ListItem(title_new, iconImage="DefaultVideo.png", thumbnailImage="")
listitem.setInfo("video",
{"Title": title_new, "Genre": "Tv shows", "episode": int(episode), "season": int(season),
"tvshowtitle": tvshow_title})
listitem.setInfo("video", {"Title": title_new, "Genre": "Tv shows", "episode": int(episode), "season": int(season), "tvshowtitle": tvshow_title})
else:
full_path_video_new = xbmc.translatePath(filetools.join(path_movie_subt, title_new + ".mp4"))
@@ -248,7 +242,7 @@ def searchSubtitle(item):
# xbmctools.launchplayer(full_path_video_new,listitem)
except:
copy = False
logger.error("Error : no se pudo copiar")
logger.error("Error : could not copy")
time.sleep(1)
@@ -289,10 +283,9 @@ def saveSubtitleName(item):
def get_from_subdivx(sub_url):
"""
:param sub_url: Url de descarga del subtitulo alojado en suvdivx.com
Por Ejemplo: http://www.subdivx.com/bajar.php?id=573942&u=8
:param sub_url: Download url of the subtitle hosted on suvdivx.com For Example: http://www.subdivx.com/bajar.php?id=573942&u=8
:return: La ruta al subtitulo descomprimido
:return: The path to the unzipped subtitle
"""
logger.info()
@@ -319,20 +312,20 @@ def get_from_subdivx(sub_url):
filetools.write(filename, data_dl)
sub = extract_file_online(sub_dir, filename)
except:
logger.info('sub no valido')
logger.info('sub invalid')
else:
logger.info('sub no valido')
logger.info('sub invalid')
return sub
def extract_file_online(path, filename):
"""
:param path: Ruta donde se encuentra el archivo comprimido
:param path: Path where the compressed file is located
:param filename: Nombre del archivo comprimido
:param filename:
:return: Devuelve la ruta al subtitulo descomprimido
:return:
"""
logger.info()

View File

@@ -2,24 +2,18 @@
# ------------------------------------------------------------
# Unify
# ------------------------------------------------------------
# Herramientas responsables de unificar diferentes tipos de
# datos obtenidos de las paginas
# Tools responsible for unifying different types of data obtained from the pages
# ----------------------------------------------------------
# from builtins import str
import sys
import sys, os, unicodedata, re
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import os
import unicodedata
import re
from platformcode import config
from platformcode import config, logger
from core.item import Item
from core import scrapertools
from platformcode import logger
thumb_dict = {"movies": "https://s10.postimg.cc/fxtqzdog9/peliculas.png",
"tvshows": "https://s10.postimg.cc/kxvslawe1/series.png",
@@ -147,10 +141,10 @@ def set_genre(string):
def remove_format(string):
# logger.info()
# logger.debug('entra en remove: %s' % string)
# logger.debug('enter remove: %s' % string)
string = string.rstrip()
string = re.sub(r'(\[|\[\/)(?:color|COLOR|b|B|i|I).*?\]|\[|\]|\(|\)|\:|\.', '', string)
# logger.debug('sale de remove: %s' % string)
# logger.debug('leaves remove: %s' % string)
return string
@@ -163,7 +157,7 @@ def normalize(string):
def simplify(string):
# logger.info()
# logger.debug('entra en simplify: %s'%string)
# logger.debug('enter simplify: %s'%string)
string = remove_format(string)
string = string.replace('-', ' ').replace('_', ' ')
string = re.sub(r'\d+', '', string)
@@ -196,7 +190,7 @@ def add_info_plot(plot, languages, quality):
last = '[/I][/B]\n'
if languages:
l_part = '[COLOR yellowgreen][B][I]Idiomas:[/COLOR] '
l_part = 'Languages: '
mid = ''
if isinstance(languages, list):
@@ -208,7 +202,7 @@ def add_info_plot(plot, languages, quality):
p_lang = '%s%s%s' % (l_part, mid, last)
if quality:
q_part = '[COLOR yellowgreen][B][I]Calidad:[/COLOR] '
q_part = 'Quality: '
p_quality = '%s%s%s' % (q_part, quality, last)
if languages and quality:
@@ -236,18 +230,17 @@ def set_color(title, category):
color_scheme = {'otro': 'white', 'dual': 'white'}
# logger.debug('category antes de remove: %s' % category)
# logger.debug('category before remove: %s' % category)
category = remove_format(category).lower()
# logger.debug('category despues de remove: %s' % category)
# Lista de elementos posibles en el titulo
# logger.debug('category after remove: %s' % category)
# List of possible elements in the title
color_list = ['movie', 'tvshow', 'year', 'rating_1', 'rating_2', 'rating_3', 'quality', 'cast', 'lat', 'vose',
'vos', 'vo', 'server', 'library', 'update', 'no_update']
# Se verifica el estado de la opcion de colores personalizados
# Check the status of the custom colors options
custom_colors = config.get_setting('title_color')
# Se Forma el diccionario de colores para cada elemento, la opcion esta activas utiliza la configuracion del
# usuario, si no pone el titulo en blanco.
# The color dictionary is formed for each element, the option is active uses the user's configuration, if it does not leave the title blank.
if title not in ['', ' ']:
for element in color_list:
@@ -258,13 +251,13 @@ def set_color(title, category):
# color_scheme[element] = 'white'
if category in ['update', 'no_update']:
# logger.debug('title antes de updates: %s' % title)
# logger.debug('title before updates: %s' % title)
title = re.sub(r'\[COLOR .*?\]', '[COLOR %s]' % color_scheme[category], title)
else:
if category not in ['movie', 'tvshow', 'library', 'otro']:
title = "[COLOR %s][%s][/COLOR]" % (color_scheme[category], title)
title = title
else:
title = "[COLOR %s]%s[/COLOR]" % (color_scheme[category], title)
title = title
return title
@@ -317,17 +310,17 @@ def title_format(item):
language_color = 'otro'
simple_language = ''
# logger.debug('item.title antes de formatear: %s' % item.title.lower())
# logger.debug('item.title before formatting: %s' % item.title.lower())
# TODO se deberia quitar cualquier elemento que no sea un enlace de la lista de findvideos para quitar esto
# TODO any item other than a link should be removed from the findvideos list to remove this
# Palabras "prohibidas" en los titulos (cualquier titulo que contengas estas no se procesara en unify)
# Words "prohibited" in the titles (any title that contains these will not be processed in unify)
excluded_words = ['online', 'descarga', 'downloads', 'trailer', 'videoteca', 'gb', 'autoplay']
# Actions excluidos, (se define canal y action) los titulos que contengan ambos valores no se procesaran en unify
# Excluded actions, (channel and action are defined) the titles that contain both values will not be processed in unify
excluded_actions = [('videolibrary', 'get_episodes')]
# Verifica el item sea valido para ser formateado por unify
# Verify the item is valid to be formatted by unify
if item.channel == 'trailertools' or (item.channel.lower(), item.action.lower()) in excluded_actions or \
item.action == '':
@@ -340,37 +333,36 @@ def title_format(item):
if not valid:
return item
# Verifica si hay marca de visto de trakt
# Check for trakt tick marks
visto = False
# logger.debug('titlo con visto? %s' % item.title)
# logger.debug('I titlo with visa? %s' % item.title)
if '[[I]v[/I]]' in item.title or '[COLOR limegreen][v][/COLOR]' in item.title:
visto = True
# Se elimina cualquier formato previo en el titulo
# Any previous format in the title is eliminated
if item.action != '' and item.action != 'mainlist' and item.unify:
item.title = remove_format(item.title)
# logger.debug('visto? %s' % visto)
# logger.debug('seen? %s' % visto)
# Evita que aparezcan los idiomas en los mainlist de cada canal
# Prevents languages from appearing in the main lists of each channel
if item.action == 'mainlist':
item.language = ''
info = item.infoLabels
# logger.debug('item antes de formatear: %s'%item)
# logger.debug('item before formatr: %s'%item)
if hasattr(item, 'text_color'):
item.text_color = ''
if valid and item.unify != False:
# Formamos el titulo para serie, se debe definir contentSerieName
# o show en el item para que esto funcione.
# We form the title for series, contentSerieName or show must be defined in the item for this to work.
if item.contentSerieName:
# Si se tiene la informacion en infolabels se utiliza
# If you have the information in infolabels it is used
if item.contentType == 'episode' and info['episode'] != '':
if info['title'] == '':
info['title'] = '%s - Episodio %s' % (info['tvshowtitle'], info['episode'])
@@ -391,12 +383,12 @@ def title_format(item):
else:
# En caso contrario se utiliza el titulo proporcionado por el canal
# Otherwise the title provided by the channel is used
# logger.debug ('color_scheme[tvshow]: %s' % color_scheme['tvshow'])
item.title = '%s' % set_color(item.title, 'tvshow')
elif item.contentTitle:
# Si el titulo no tiene contentSerieName entonces se formatea como pelicula
# If the title does not have contentSerieName then it is formatted as a movie
saga = False
if 'saga' in item.title.lower():
item.title = '%s [Saga]' % set_color(item.contentTitle, 'movie')
@@ -415,11 +407,10 @@ def title_format(item):
# logger.debug('novedades')
item.title = '%s [%s]' % (item.title, item.channel)
# Verificamos si item.language es una lista, si lo es se toma
# cada valor y se normaliza formado una nueva lista
# We check if item.language is a list, if it is, each value is taken and normalized, forming a new list
if hasattr(item, 'language') and item.language != '':
# logger.debug('tiene language: %s'%item.language)
# logger.debug('has language: %s'%item.language)
if isinstance(item.language, list):
language_list = []
for language in item.language:
@@ -429,7 +420,7 @@ def title_format(item):
# logger.debug('language_list: %s' % language_list)
simple_language = language_list
else:
# Si item.language es un string se normaliza
# If item.language is a string it is normalized
if item.language != '':
lang = True
simple_language = set_lang(item.language).upper()
@@ -438,8 +429,7 @@ def title_format(item):
# item.language = simple_language
# Damos formato al año si existiera y lo agregamos
# al titulo excepto que sea un episodio
# We format the year if it exists and add it to the title except that it is an episode
if info and info.get("year", "") not in ["", " "] and item.contentType != 'episode' and not info['season']:
try:
year = '%s' % set_color(info['year'], 'year')
@@ -447,14 +437,14 @@ def title_format(item):
except:
logger.debug('infoLabels: %s' % info)
# Damos formato al puntaje si existiera y lo agregamos al titulo
# We format the score if it exists and add it to the title
if info and info['rating'] and info['rating'] != '0.0' and not info['season']:
# Se normaliza el puntaje del rating
# The rating score is normalized
rating_value = check_rating(info['rating'])
# Asignamos el color dependiendo el puntaje, malo, bueno, muy bueno, en caso de que exista
# We assign the color depending on the score, bad, good, very good, in case it exists
if rating_value:
value = float(rating_value)
@@ -471,13 +461,13 @@ def title_format(item):
color_rating = 'otro'
item.title = '%s %s' % (item.title, set_color(rating, color_rating))
# Damos formato a la calidad si existiera y lo agregamos al titulo
# We format the quality if it exists and add it to the title
if item.quality and isinstance(item.quality, str):
quality = item.quality.strip()
else:
quality = ''
# Damos formato al idioma-calidad si existieran y los agregamos al plot
# We format the language-quality if they exist and add them to the plot
quality_ = set_color(quality, 'quality')
if (lang or quality) and item.action == "play":
@@ -498,14 +488,14 @@ def title_format(item):
plot_ = add_info_plot('', simple_language, quality_)
item.contentPlot = plot_
# Para las busquedas por canal
# For channel searches
if item.from_channel != '':
from core import channeltools
channel_parameters = channeltools.get_channel_parameters(item.from_channel)
logger.debug(channel_parameters)
item.title = '%s [%s]' % (item.title, channel_parameters['title'])
# Formato para actualizaciones de series en la videoteca sobreescribe los colores anteriores
# Format for series updates in the video library overwrites the previous colors
if item.channel == 'videolibrary' and item.context != '':
if item.action == 'get_seasons':
@@ -514,15 +504,14 @@ def title_format(item):
if 'Activar' in item.context[1]['title']:
item.title = '%s' % (set_color(item.title, 'no_update'))
# logger.debug('Despues del formato: %s' % item)
# Damos formato al servidor si existiera
# logger.debug('After the format: %s' % item)
# We format the server if it exists
if item.server:
server = '%s' % set_color(item.server.strip().capitalize(), 'server')
# Compureba si estamos en findvideos, y si hay server, si es asi no se muestra el
# titulo sino el server, en caso contrario se muestra el titulo normalmente.
# Check if we are in findvideos, and if there is a server, if so, the title is not shown but the server, otherwise the title is normally shown.
# logger.debug('item.title antes de server: %s'%item.title)
# logger.debug('item.title before server: %s'%item.title)
if item.action != 'play' and item.server:
item.title = '%s %s' % (item.title, server.strip())
@@ -544,7 +533,7 @@ def title_format(item):
if item.channel == 'videolibrary':
item.title += ' [%s]' % item.contentChannel
# si hay verificacion de enlaces
# if there is verification of links
if item.alive != '':
if item.alive.lower() == 'no':
item.title = '[[COLOR red][B]X[/B][/COLOR]] %s' % item.title
@@ -553,14 +542,14 @@ def title_format(item):
else:
item.title = '%s' % item.title
# logger.debug('item.title despues de server: %s' % item.title)
# logger.debug('item.title after server: %s' % item.title)
elif 'library' in item.action:
item.title = '%s' % set_color(item.title, 'library')
elif item.action == '' and item.title != '':
item.title = '**- %s -**' % item.title
elif item.unify:
item.title = '%s' % set_color(item.title, 'otro')
# logger.debug('antes de salir %s' % item.title)
# logger.debug('before leaving %s' % item.title)
if visto:
try:
check = u'\u221a'
@@ -579,8 +568,7 @@ def title_format(item):
def thumbnail_type(item):
# logger.info()
# Se comprueba que tipo de thumbnail se utilizara en findvideos,
# Poster o Logo del servidor
# Check what type of thumbnail will be used in findvideos, Poster or Logo of the server
thumb_type = config.get_setting('video_thumbnail_type')
info = item.infoLabels
@@ -612,16 +600,16 @@ def check_rating(rating):
def check_decimal_length(_rating):
"""
Dejamos que el float solo tenga un elemento en su parte decimal, "7.10" --> "7.1"
@param _rating: valor del rating
We let the float only have one element in its decimal part, "7.10" --> "7.1"
@param _rating: rating value
@type _rating: float
@return: devuelve el valor modificado si es correcto, si no devuelve None
@return: returns the modified value if it is correct, if it does not return None
@rtype: float|None
"""
# logger.debug("rating %s" % _rating)
try:
# convertimos los deciamles p.e. 7.1
# we convert the deciamles ex. 7.1
return "%.1f" % round(_rating, 1)
except Exception as ex_dl:
template = "An exception of type %s occured. Arguments:\n%r"
@@ -631,20 +619,20 @@ def check_rating(rating):
def check_range(_rating):
"""
Comprobamos que el rango de rating sea entre 0.0 y 10.0
@param _rating: valor del rating
We check that the rating range is between 0.0 and 10.0
@param _rating: rating value
@type _rating: float
@return: devuelve el valor si está dentro del rango, si no devuelve None
@return: returns the value if it is within the range, if it does not return None
@rtype: float|None
"""
# logger.debug("rating %s" % _rating)
# fix para comparacion float
# fix for float comparison
dec = Decimal(_rating)
if 0.0 <= dec <= 10.0:
# logger.debug("estoy en el rango!")
# logger.debug("i'm in range!")
return _rating
else:
# logger.debug("NOOO estoy en el rango!")
# logger.debug("NOOO I'm in range!")
return None
def convert_float(_rating):
@@ -657,26 +645,26 @@ def check_rating(rating):
return None
if not isinstance(rating, float):
# logger.debug("no soy float")
# logger.debug("I'm not float")
if isinstance(rating, int):
# logger.debug("soy int")
# logger.debug("I am int")
rating = convert_float(rating)
elif isinstance(rating, str):
# logger.debug("soy str")
# logger.debug("I'm str")
rating = rating.replace("<", "")
rating = convert_float(rating)
if rating is None:
# logger.debug("error al convertir str, rating no es un float")
# obtenemos los valores de numericos
# logger.debug("error converting str, rating is not a float")
# we get the numerical values
new_rating = scrapertools.find_single_match(rating, "(\d+)[,|:](\d+)")
if len(new_rating) > 0:
rating = convert_float("%s.%s" % (new_rating[0], new_rating[1]))
else:
logger.error("no se que soy!!")
# obtenemos un valor desconocido no devolvemos nada
# we get an unknown value we don't return anything
return None
if rating:

View File

@@ -5,21 +5,12 @@
from future import standard_library
standard_library.install_aliases()
#from builtins import str
import sys
import sys, os, threading, time, re, math, xbmc
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import os
import threading
import time
import re
import math
import xbmc
from core import filetools
from core import jsontools
from platformcode import config, logger
from platformcode import platformtools
from core import filetools, jsontools
from platformcode import config, logger, platformtools
from core import scrapertools
from xml.dom import minidom
@@ -82,25 +73,25 @@ def mark_auto_as_watched(item):
time.sleep(5)
# Sincronizacion silenciosa con Trakt
# Silent sync with Trakt
if sync_with_trakt and config.get_setting("trakt_sync"):
sync_trakt_kodi()
# logger.debug("Fin del hilo")
# Si esta configurado para marcar como visto
# If it is configured to mark as seen
if config.get_setting("mark_as_watched", "videolibrary"):
threading.Thread(target=mark_as_watched_subThread, args=[item]).start()
def sync_trakt_addon(path_folder):
"""
Actualiza los valores de episodios vistos si
Updates the values of episodes seen if
"""
logger.info()
# si existe el addon hacemos la busqueda
# if the addon exists we do the search
if xbmc.getCondVisibility('System.HasAddon("script.trakt")'):
# importamos dependencias
# we import dependencies
paths = ["special://home/addons/script.module.dateutil/lib/", "special://home/addons/script.module.six/lib/",
"special://home/addons/script.module.arrow/lib/", "special://home/addons/script.module.trakt/lib/",
"special://home/addons/script.trakt/"]
@@ -108,7 +99,7 @@ def sync_trakt_addon(path_folder):
for path in paths:
sys.path.append(xbmc.translatePath(path))
# se obtiene las series vistas
# the series seen is obtained
try:
from resources.lib.traktapi import traktAPI
traktapi = traktAPI()
@@ -118,9 +109,9 @@ def sync_trakt_addon(path_folder):
shows = traktapi.getShowsWatched({})
shows = list(shows.items())
# obtenemos el id de la serie para comparar
# we get the series id to compare
_id = re.findall("\[(.*?)\]", path_folder, flags=re.DOTALL)[0]
logger.debug("el id es %s" % _id)
logger.debug("the id is %s" % _id)
if "tt" in _id:
type_id = "imdb"
@@ -131,15 +122,15 @@ def sync_trakt_addon(path_folder):
type_id = "tmdb"
_id = _id.strip("tmdb_")
else:
logger.error("No hay _id de la serie")
logger.error("There is no _id of the series")
return
# obtenemos los valores de la serie
# we obtain the values of the series
from core import videolibrarytools
tvshow_file = filetools.join(path_folder, "tvshow.nfo")
head_nfo, serie = videolibrarytools.read_nfo(tvshow_file)
# buscamos en las series de trakt
# we look in the trakt series
for show in shows:
show_aux = show[1].to_dict()
@@ -148,30 +139,27 @@ def sync_trakt_addon(path_folder):
# logger.debug("ID ES %s" % _id_trakt)
if _id_trakt:
if _id == _id_trakt:
logger.debug("ENCONTRADO!! %s" % show_aux)
logger.debug("FOUND! %s" % show_aux)
# creamos el diccionario de trakt para la serie encontrada con el valor que tiene "visto"
# we create the trakt dictionary for the found series with the value that has "seen"
dict_trakt_show = {}
for idx_season, season in enumerate(show_aux['seasons']):
for idx_episode, episode in enumerate(show_aux['seasons'][idx_season]['episodes']):
sea_epi = "%sx%s" % (show_aux['seasons'][idx_season]['number'],
str(show_aux['seasons'][idx_season]['episodes'][idx_episode][
'number']).zfill(2))
sea_epi = "%sx%s" % (show_aux['seasons'][idx_season]['number'], str(show_aux['seasons'][idx_season]['episodes'][idx_episode]['number']).zfill(2))
dict_trakt_show[sea_epi] = show_aux['seasons'][idx_season]['episodes'][idx_episode][
'watched']
dict_trakt_show[sea_epi] = show_aux['seasons'][idx_season]['episodes'][idx_episode]['watched']
logger.debug("dict_trakt_show %s " % dict_trakt_show)
# obtenemos las keys que son episodios
# we get the keys that are episodes
regex_epi = re.compile('\d+x\d+')
keys_episodes = [key for key in serie.library_playcounts if regex_epi.match(key)]
# obtenemos las keys que son temporadas
# we get the keys that are seasons
keys_seasons = [key for key in serie.library_playcounts if 'season ' in key]
# obtenemos los numeros de las keys temporadas
# we get the numbers of the seasons keys
seasons = [key.strip('season ') for key in keys_seasons]
# marcamos los episodios vistos
# we mark the episodes watched
for k in keys_episodes:
serie.library_playcounts[k] = dict_trakt_show.get(k, 0)
@@ -179,7 +167,7 @@ def sync_trakt_addon(path_folder):
episodios_temporada = 0
episodios_vistos_temporada = 0
# obtenemos las keys de los episodios de una determinada temporada
# we obtain the keys of the episodes of a certain season
keys_season_episodes = [key for key in keys_episodes if key.startswith("%sx" % season)]
for k in keys_season_episodes:
@@ -187,7 +175,7 @@ def sync_trakt_addon(path_folder):
if serie.library_playcounts[k] > 0:
episodios_vistos_temporada += 1
# se comprueba que si todos los episodios están vistos, se marque la temporada como vista
# it is verified that if all the episodes are watched, the season is marked as watched
if episodios_temporada == episodios_vistos_temporada:
serie.library_playcounts.update({"season %s" % season: 1})
@@ -199,11 +187,11 @@ def sync_trakt_addon(path_folder):
if serie.library_playcounts[k] > 0:
temporada_vista += 1
# se comprueba que si todas las temporadas están vistas, se marque la serie como vista
# sCheck that if all seasons are viewed, the series is marked as view
if temporada == temporada_vista:
serie.library_playcounts.update({serie.title: 1})
logger.debug("los valores nuevos %s " % serie.library_playcounts)
logger.debug("the new values %s " % serie.library_playcounts)
filetools.write(tvshow_file, head_nfo + serie.tojson())
break
@@ -211,7 +199,7 @@ def sync_trakt_addon(path_folder):
continue
else:
logger.error("no se ha podido obtener el id, trakt tiene: %s" % show_aux['ids'])
logger.error("could not get id, trakt has: %s" % show_aux['ids'])
except:
import traceback
@@ -219,7 +207,7 @@ def sync_trakt_addon(path_folder):
def sync_trakt_kodi(silent=True):
# Para que la sincronizacion no sea silenciosa vale con silent=False
# So that the synchronization is not silent it is worth with silent = False
if xbmc.getCondVisibility('System.HasAddon("script.trakt")'):
notificacion = True
if (not config.get_setting("sync_trakt_notification", "videolibrary") and platformtools.is_playing()):
@@ -234,11 +222,11 @@ def sync_trakt_kodi(silent=True):
def mark_content_as_watched_on_kodi(item, value=1):
"""
marca el contenido como visto o no visto en la libreria de Kodi
mark the content as seen or not seen in the Kodi library
@type item: item
@param item: elemento a marcar
@param item: element to mark
@type value: int
@param value: >0 para visto, 0 para no visto
@param value: > 0 for seen, 0 for not seen
"""
logger.info()
# logger.debug("item:\n" + item.tostring('\n'))
@@ -253,23 +241,22 @@ def mark_content_as_watched_on_kodi(item, value=1):
data = get_data(payload)
if 'result' in data and "movies" in data['result']:
if item.strm_path: #Si Item es de un episodio
if item.strm_path: # If Item is from an episode
filename = filetools.basename(item.strm_path)
head, tail = filetools.split(filetools.split(item.strm_path)[0])
else: #Si Item es de la Serie
else: # If Item is from the Series
filename = filetools.basename(item.path)
head, tail = filetools.split(filetools.split(item.path)[0])
path = filetools.join(tail, filename)
for d in data['result']['movies']:
if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
# logger.debug("marco la pelicula como vista")
# logger.debug("I mark the movie as a view")
movieid = d['movieid']
break
if movieid != 0:
payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {
"movieid": movieid, "playcount": value}, "id": 1}
payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": movieid, "playcount": value}, "id": 1}
else: # item.contentType != 'movie'
episodeid = 0
@@ -280,10 +267,10 @@ def mark_content_as_watched_on_kodi(item, value=1):
data = get_data(payload)
if 'result' in data and "episodes" in data['result']:
if item.strm_path: #Si Item es de un episodio
if item.strm_path: # If Item is from an episode
filename = filetools.basename(item.strm_path)
head, tail = filetools.split(filetools.split(item.strm_path)[0])
else: #Si Item es de la Serie
else: # If Item is from the Series
filename = filetools.basename(item.path)
head, tail = filetools.split(filetools.split(item.path)[0])
path = filetools.join(tail, filename)
@@ -291,35 +278,33 @@ def mark_content_as_watched_on_kodi(item, value=1):
for d in data['result']['episodes']:
if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
# logger.debug("marco el episodio como visto")
# logger.debug("I mark the episode as seen")
episodeid = d['episodeid']
break
if episodeid != 0:
payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {
"episodeid": episodeid, "playcount": value}, "id": 1}
payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid": episodeid, "playcount": value}, "id": 1}
if payload_f:
# Marcar como visto
# Mark as seen
data = get_data(payload_f)
# logger.debug(str(data))
if data['result'] != 'OK':
logger.error("ERROR al poner el contenido como visto")
logger.error("ERROR putting content as viewed")
def mark_season_as_watched_on_kodi(item, value=1):
"""
marca toda la temporada como vista o no vista en la libreria de Kodi
mark the entire season as seen or unseen in the Kodi library
@type item: item
@param item: elemento a marcar
@param item: element to mark
@type value: int
@param value: >0 para visto, 0 para no visto
@param value: > 0 for seen, 0 for not seen
"""
logger.info()
# logger.debug("item:\n" + item.tostring('\n'))
# Solo podemos marcar la temporada como vista en la BBDD de Kodi si la BBDD es local,
# en caso de compartir BBDD esta funcionalidad no funcionara
# We can only mark the season as seen in the Kodi database if the database is local, in case of sharing database this functionality will not work
if config.get_setting("db_mode", "videolibrary"):
return
@@ -336,9 +321,7 @@ def mark_season_as_watched_on_kodi(item, value=1):
item_path1 += "\\"
item_path2 = item_path1.replace("\\", "/")
sql = 'update files set playCount= %s where idFile in ' \
'(select idfile from episode_view where (strPath like "%s" or strPath like "%s")%s)' % \
(value, item_path1, item_path2, request_season)
sql = 'update files set playCount= %s where idFile in (select idfile from episode_view where (strPath like "%s" or strPath like "%s")%s)' % (value, item_path1, item_path2, request_season)
execute_sql_kodi(sql)
@@ -348,9 +331,9 @@ def mark_content_as_watched_on_kod(path):
from core import videolibrarytools
"""
marca toda la serie o película como vista o no vista en la Videoteca de Alfa basado en su estado en la Videoteca de Kodi
mark the entire series or movie as viewed or unseen in the Alpha Video Library based on their status in the Kodi Video Library
@type str: path
@param path: carpeta de contenido a marcar
@param path: content folder to mark
"""
logger.info()
#logger.debug("path: " + path)
@@ -361,9 +344,8 @@ def mark_content_as_watched_on_kod(path):
if not VIDEOLIBRARY_PATH:
return
# Solo podemos marcar el contenido como vista en la BBDD de Kodi si la BBDD es local,
# en caso de compartir BBDD esta funcionalidad no funcionara
#if config.get_setting("db_mode", "videolibrary"):
# We can only mark the content as a view in the Kodi database if the database is local, in case of sharing database this functionality will not work
# if config.get_setting("db_mode", "videolibrary"):
# return
path2 = ''
@@ -375,60 +357,60 @@ def mark_content_as_watched_on_kod(path):
if "\\" in path:
path = path.replace("/", "\\")
head_nfo, item = videolibrarytools.read_nfo(path) #Leo el .nfo del contenido
head_nfo, item = videolibrarytools.read_nfo(path) # I read the content .nfo
if not item:
logger.error('.NFO no encontrado: ' + path)
logger.error('.NFO not found: ' + path)
return
if FOLDER_TVSHOWS in path: #Compruebo si es CINE o SERIE
contentType = "episode_view" #Marco la tabla de BBDD de Kodi Video
nfo_name = "tvshow.nfo" #Construyo el nombre del .nfo
path1 = path.replace("\\\\", "\\").replace(nfo_name, '') #para la SQL solo necesito la carpeta
if FOLDER_TVSHOWS in path: # I check if it is CINEMA or SERIES
contentType = "episode_view" # I mark the Kodi Video BBDD table
nfo_name = "tvshow.nfo" # I build the name of the .nfo
path1 = path.replace("\\\\", "\\").replace(nfo_name, '') # for SQL I just need the folder
if not path2:
path2 = path1.replace("\\", "/") #Formato no Windows
path2 = path1.replace("\\", "/") # Format no Windows
else:
path2 = path2.replace(nfo_name, '')
else:
contentType = "movie_view" #Marco la tabla de BBDD de Kodi Video
path1 = path.replace("\\\\", "\\") #Formato Windows
contentType = "movie_view" # I mark the Kodi Video BBDD table
path1 = path.replace("\\\\", "\\") # Windows format
if not path2:
path2 = path1.replace("\\", "/") #Formato no Windows
nfo_name = scrapertools.find_single_match(path2, '\]\/(.*?)$') #Construyo el nombre del .nfo
path1 = path1.replace(nfo_name, '') #para la SQL solo necesito la carpeta
path2 = path2.replace(nfo_name, '') #para la SQL solo necesito la carpeta
path2 = filetools.remove_smb_credential(path2) #Si el archivo está en un servidor SMB, quitamos las credenciales
path2 = path1.replace("\\", "/") # Format no Windows
nfo_name = scrapertools.find_single_match(path2, '\]\/(.*?)$') # I build the name of the .nfo
path1 = path1.replace(nfo_name, '') # for SQL I just need the folder
path2 = path2.replace(nfo_name, '') # for SQL I just need the folder
path2 = filetools.remove_smb_credential(path2) # If the file is on an SMB server, we remove the credentials
#Ejecutmos la sentencia SQL
# Let's execute the SQL statement
sql = 'select strFileName, playCount from %s where (strPath like "%s" or strPath like "%s")' % (contentType, path1, path2)
nun_records = 0
records = None
nun_records, records = execute_sql_kodi(sql) #ejecución de la SQL
if nun_records == 0: #hay error?
logger.error("Error en la SQL: " + sql + ": 0 registros")
return #salimos: o no está catalogado en Kodi, o hay un error en la SQL
nun_records, records = execute_sql_kodi(sql) # SQL execution
if nun_records == 0: # is there an error?
logger.error("SQL error: " + sql + ": 0 registros")
return # we quit: either it is not cataloged in Kodi, or there is an error in the SQL
for title, playCount in records: #Ahora recorremos todos los registros obtenidos
for title, playCount in records: # Now we go through all the records obtained
if contentType == "episode_view":
title_plain = title.replace('.strm', '') #Si es Serie, quitamos el sufijo .strm
title_plain = title.replace('.strm', '') # If it is Serial, we remove the suffix .strm
else:
title_plain = scrapertools.find_single_match(item.strm_path, '.(.*?\s\[.*?\])') #si es peli, quitamos el título
if playCount is None or playCount == 0: #todavía no se ha visto, lo ponemos a 0
title_plain = scrapertools.find_single_match(item.strm_path, '.(.*?\s\[.*?\])') # if it's a movie, we remove the title
if playCount is None or playCount == 0: # not yet seen, we set it to 0
playCount_final = 0
elif playCount >= 1:
playCount_final = 1
elif not PY3 and isinstance(title_plain, (str, unicode)):
title_plain = title_plain.decode("utf-8").encode("utf-8") #Hacemos esto porque si no genera esto: u'title_plain'
title_plain = title_plain.decode("utf-8").encode("utf-8") # We do this because if it doesn't generate this: u'title_plain '
elif PY3 and isinstance(title_plain, bytes):
title_plain = title_plain.decode('utf-8')
item.library_playcounts.update({title_plain: playCount_final}) #actualizamos el playCount del .nfo
item.library_playcounts.update({title_plain: playCount_final}) # update the .nfo playCount
if item.infoLabels['mediatype'] == "tvshow": #Actualizamos los playCounts de temporadas y Serie
if item.infoLabels['mediatype'] == "tvshow": # We update the Season and Series playCounts
for season in item.library_playcounts:
if "season" in season: #buscamos las etiquetas "season" dentro de playCounts
season_num = int(scrapertools.find_single_match(season, 'season (\d+)')) #salvamos el núm, de Temporada
item = videolibrary.check_season_playcount(item, season_num) #llamamos al método que actualiza Temps. y Series
if "season" in season: # we look for the tags "season" inside playCounts
season_num = int(scrapertools.find_single_match(season, 'season (\d+)')) # we save the season number
item = videolibrary.check_season_playcount(item, season_num) # We call the method that updates Temps. and series
filetools.write(path, head_nfo + item.tojson())
@@ -437,7 +419,7 @@ def mark_content_as_watched_on_kod(path):
def get_data(payload):
"""
obtiene la información de la llamada JSON-RPC con la información pasada en payload
get the information of the JSON-RPC call with the information passed in payload
@type payload: dict
@param payload: data
:return:
@@ -483,12 +465,12 @@ def get_data(payload):
def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
"""
Actualiza la libreria dependiendo del tipo de contenido y la ruta que se le pase.
Update the library depending on the type of content and the path passed to it.
@type folder_content: str
@param folder_content: tipo de contenido para actualizar, series o peliculas
@param folder_content: type of content to update, series or movies
@type folder: str
@param folder: nombre de la carpeta a escanear.
@param folder: name of the folder to scan.
"""
logger.info(folder)
@@ -512,7 +494,7 @@ def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
videolibrarypath = videolibrarypath[:-1]
update_path = videolibrarypath + "/" + folder_content + "/" + folder + "/"
else:
#update_path = filetools.join(videolibrarypath, folder_content, folder) + "/" # Problemas de encode en "folder"
# update_path = filetools.join(videolibrarypath, folder_content, folder) + "/" # Encoder problems in "folder"
update_path = filetools.join(videolibrarypath, folder_content, ' ').rstrip()
if videolibrarypath.startswith("special:") or not scrapertools.find_single_match(update_path, '(^\w+:\/\/)'):
@@ -535,9 +517,9 @@ def search_library_path():
def set_content(content_type, silent=False, custom=False):
"""
Procedimiento para auto-configurar la videoteca de kodi con los valores por defecto
Procedure to auto-configure the kodi video library with the default values
@type content_type: str ('movie' o 'tvshow')
@param content_type: tipo de contenido para configurar, series o peliculas
@param content_type: content type to configure, series or movies
"""
logger.info()
continuar = True
@@ -556,14 +538,14 @@ def set_content(content_type, silent=False, custom=False):
if seleccion == -1 or seleccion == 0:
if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
if not silent:
# Preguntar si queremos instalar metadata.themoviedb.org
# Ask if we want to install metadata.themoviedb.org
install = platformtools.dialog_yesno(config.get_localized_string(60046))
else:
install = True
if install:
try:
# Instalar metadata.themoviedb.org
# Install metadata.themoviedb.org
xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
logger.info("Instalado el Scraper de películas de TheMovieDB")
except:
@@ -580,7 +562,7 @@ def set_content(content_type, silent=False, custom=False):
if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.universal)'):
continuar = False
if not silent:
# Preguntar si queremos instalar metadata.universal
# Ask if we want to install metadata.universal
install = platformtools.dialog_yesno(config.get_localized_string(70095))
else:
install = True
@@ -610,16 +592,16 @@ def set_content(content_type, silent=False, custom=False):
if seleccion == -1 or seleccion == 0:
if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
if not silent:
# Preguntar si queremos instalar metadata.tvdb.com
#Ask if we want to install metadata.tvdb.com
install = platformtools.dialog_yesno(config.get_localized_string(60048))
else:
install = True
if install:
try:
# Instalar metadata.tvdb.com
# Install metadata.tvdb.com
xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
logger.info("Instalado el Scraper de series de The TVDB")
logger.info("The TVDB series Scraper installed ")
except:
pass
@@ -634,14 +616,14 @@ def set_content(content_type, silent=False, custom=False):
if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
continuar = False
if not silent:
# Preguntar si queremos instalar metadata.tvshows.themoviedb.org
# Ask if we want to install metadata.tvshows.themoviedb.org
install = platformtools.dialog_yesno(config.get_localized_string(60050))
else:
install = True
if install:
try:
# Instalar metadata.tvshows.themoviedb.org
# Install metadata.tvshows.themoviedb.org
xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
if xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
continuar = True
@@ -659,7 +641,7 @@ def set_content(content_type, silent=False, custom=False):
if continuar:
continuar = False
# Buscamos el idPath
# We look for the idPath
sql = 'SELECT MAX(idPath) FROM path'
nun_records, records = execute_sql_kodi(sql)
if nun_records == 1:
@@ -677,7 +659,7 @@ def set_content(content_type, silent=False, custom=False):
if not sql_videolibrarypath.endswith(sep):
sql_videolibrarypath += sep
# Buscamos el idParentPath
# We are looking for the idParentPath
sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_videolibrarypath
nun_records, records = execute_sql_kodi(sql)
if nun_records == 1:
@@ -685,7 +667,7 @@ def set_content(content_type, silent=False, custom=False):
videolibrarypath = records[0][1][:-1]
continuar = True
else:
# No existe videolibrarypath en la BD: la insertamos
# There is no videolibrarypath in the DB: we insert it
sql_videolibrarypath = videolibrarypath
if not sql_videolibrarypath.endswith(sep):
sql_videolibrarypath += sep
@@ -703,7 +685,7 @@ def set_content(content_type, silent=False, custom=False):
if continuar:
continuar = False
# Fijamos strContent, strScraper, scanRecursive y strSettings
# We set strContent, strScraper, scanRecursive and strSettings
if content_type == 'movie':
strContent = 'movies'
scanRecursive = 2147483647
@@ -719,7 +701,7 @@ def set_content(content_type, silent=False, custom=False):
settings_data = filetools.read(path_settings)
strSettings = ' '.join(settings_data.split()).replace("> <", "><")
strSettings = strSettings.replace("\"","\'")
strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para películas?"
strActualizar = "Do you want to set this Scraper in Spanish as the default option for movies?"
if not videolibrarypath.endswith(sep):
videolibrarypath += sep
strPath = videolibrarypath + config.get_setting("folder_movies") + sep
@@ -738,13 +720,13 @@ def set_content(content_type, silent=False, custom=False):
settings_data = filetools.read(path_settings)
strSettings = ' '.join(settings_data.split()).replace("> <", "><")
strSettings = strSettings.replace("\"","\'")
strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para series?"
strActualizar = "Do you want to configure this Scraper in Spanish as a default option for series?"
if not videolibrarypath.endswith(sep):
videolibrarypath += sep
strPath = videolibrarypath + config.get_setting("folder_tvshows") + sep
logger.info("%s: %s" % (content_type, strPath))
# Comprobamos si ya existe strPath en la BD para evitar duplicados
# We check if strPath already exists in the DB to avoid duplicates
sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
nun_records, records = execute_sql_kodi(sql)
sql = ""
@@ -1011,12 +993,12 @@ def clean(path_list=[]):
def execute_sql_kodi(sql):
"""
Ejecuta la consulta sql contra la base de datos de kodi
@param sql: Consulta sql valida
Run sql query against kodi database
@param sql: Valid sql query
@type sql: str
@return: Numero de registros modificados o devueltos por la consulta
@return: Number of records modified or returned by the query
@rtype nun_records: int
@return: lista con el resultado de la consulta
@return: list with the query result
@rtype records: list of tuples
"""
logger.info()
@@ -1024,12 +1006,12 @@ def execute_sql_kodi(sql):
nun_records = 0
records = None
# Buscamos el archivo de la BBDD de videos segun la version de kodi
# We look for the archive of the video database according to the version of kodi
video_db = config.get_platform(True)['video_db']
if video_db:
file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)
# metodo alternativo para localizar la BBDD
# alternative method to locate the database
if not file_db or not filetools.exists(file_db):
file_db = ""
for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")):
@@ -1040,14 +1022,14 @@ def execute_sql_kodi(sql):
break
if file_db:
logger.info("Archivo de BD: %s" % file_db)
logger.info("DB file: %s" % file_db)
conn = None
try:
import sqlite3
conn = sqlite3.connect(file_db)
cursor = conn.cursor()
logger.info("Ejecutando sql: %s" % sql)
logger.info("Running sql: %s" % sql)
cursor.execute(sql)
conn.commit()
@@ -1061,15 +1043,15 @@ def execute_sql_kodi(sql):
nun_records = conn.total_changes
conn.close()
logger.info("Consulta ejecutada. Registros: %s" % nun_records)
logger.info("Query executed. Records: %s" % nun_records)
except:
logger.error("Error al ejecutar la consulta sql")
logger.error("Error executing sql query")
if conn:
conn.close()
else:
logger.debug("Base de datos no encontrada")
logger.debug("Database not found")
return nun_records, records