Modifiche del 26/11/2021

This commit is contained in:
Alhaziel01
2021-11-26 18:55:51 +01:00
parent 48996688a6
commit 5257183fb7
221 changed files with 4565 additions and 4807 deletions

View File

@@ -39,7 +39,7 @@ def check(item, itemlist=None):
def filename(item):
logger.debug()
name_file = item.channel + "_data.json"
path = filetools.join(config.get_data_path(), "settings_channels")
path = filetools.join(config.getDataPath(), "settings_channels")
fname = filetools.join(path, name_file)
return fname
@@ -70,7 +70,7 @@ def b64(json, mode = 'encode'):
def find_episodes(item):
logger.debug()
ch = platformtools.channel_import(item.channel)
ch = platformtools.channelImport(item.channel)
itemlist = getattr(ch, item.action)(item)
return itemlist
@@ -113,7 +113,7 @@ class autorenumber():
from core.videolibrarytools import check_renumber_options
check_renumber_options(self.item)
self.renumberdict = load(item)
self.auto = config.get_setting('autorenumber', item.channel)
self.auto = config.getSetting('autorenumber', item.channel)
self.title = self.item.fulltitle.strip()
if item.contentSeason:
item.exit = True
@@ -137,7 +137,7 @@ class autorenumber():
self.renumberdict = {}
for item in self.itemlist:
if item.contentType != 'movie':
item.context = [{"title": typo(config.get_localized_string(70585), 'bold'),
item.context = [{"title": typo(config.getLocalizedString(70585), 'bold'),
"action": "start",
"channel": "autorenumber",
"from_channel": item.channel,
@@ -161,7 +161,7 @@ class autorenumber():
while not self.item.exit:
tmdb.find_and_set_infoLabels(self.item)
if self.item.infoLabels['tmdb_id']: self.item.exit = True
else:self.item = platformtools.dialog_info(self.item, 'tmdb')
else:self.item = platformtools.dialogInfo(self.item, 'tmdb')
# Rinumerazione Automatica
if (not self.id and self.auto) or self.item.setrenumber:
@@ -313,7 +313,7 @@ def SelectreNumeration(opt, itemlist, manual=False):
def onInit(self):
# Compatibility with Kodi 18
if config.get_platform(True)['num_version'] < 18: self.setCoordinateResolution(2)
if config.getXBMCPlatform(True)['num_version'] < 18: self.setCoordinateResolution(2)
fanart = self.item.fanart
thumb = self.item.thumbnail
self.getControl(SELECT).setVisible(False)
@@ -324,7 +324,7 @@ def SelectreNumeration(opt, itemlist, manual=False):
self.getControl(MANUAL).setVisible(True)
self.getControl(MPOSTER).setImage(thumb)
if fanart: self.getControl(MBACKGROUND).setImage(fanart)
self.getControl(INFO).setLabel(typo(config.get_localized_string(70822) + self.title, 'bold'))
self.getControl(INFO).setLabel(typo(config.getLocalizedString(70822) + self.title, 'bold'))
self.manual = True
@@ -366,7 +366,7 @@ def SelectreNumeration(opt, itemlist, manual=False):
if fanart:
self.getControl(BACKGROUND).setImage(fanart)
self.getControl(MBACKGROUND).setImage(fanart)
self.getControl(INFO).setLabel(typo(config.get_localized_string(70824) + self.title, 'bold'))
self.getControl(INFO).setLabel(typo(config.getLocalizedString(70824) + self.title, 'bold'))
self.getControl(LIST).addItems(self.items)
self.getControl(SELECTED).addItems(self.selected)
@@ -383,19 +383,19 @@ def SelectreNumeration(opt, itemlist, manual=False):
def onFocus(self, focus):
if focus in [S]:
self.getControl(108).setLabel(typo(config.get_localized_string(70825), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70825), 'bold'))
elif focus in [E]:
self.getControl(108).setLabel(typo(config.get_localized_string(70826), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70826), 'bold'))
elif focus in [O]:
self.getControl(108).setLabel(typo(config.get_localized_string(70001), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70001), 'bold'))
elif focus in [SS]:
self.getControl(108).setLabel(typo(config.get_localized_string(70827), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70827), 'bold'))
elif focus in [M]:
self.getControl(108).setLabel(typo(config.get_localized_string(70828), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70828), 'bold'))
elif focus in [D]:
self.getControl(108).setLabel(typo(config.get_localized_string(70829) + self.title, 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70829) + self.title, 'bold'))
elif focus in [C]:
self.getControl(108).setLabel(typo(config.get_localized_string(70002), 'bold'))
self.getControl(108).setLabel(typo(config.getLocalizedString(70002), 'bold'))
def onAction(self, action):
action = action.getId()
@@ -470,11 +470,11 @@ def SelectreNumeration(opt, itemlist, manual=False):
def onClick(self, control_id):
## FIRST SECTION
if control_id in [S]:
selected = platformtools.dialog_numeric(0, config.get_localized_string(70825),
selected = platformtools.dialogNumeric(0, config.getLocalizedString(70825),
self.getControl(S).getLabel())
if selected: s = self.getControl(S).setLabel(selected)
elif control_id in [E]:
selected = platformtools.dialog_numeric(0, config.get_localized_string(70826),
selected = platformtools.dialogNumeric(0, config.getLocalizedString(70826),
self.getControl(E).getLabel())
if selected: e = self.getControl(E).setLabel(selected)
# OPEN SPECIALS OR OK
@@ -491,7 +491,7 @@ def SelectreNumeration(opt, itemlist, manual=False):
self.setFocusId(OK)
# OPEN MANUAL
elif control_id in [M]:
self.getControl(INFO).setLabel(typo(config.get_localized_string(70823) + self.title, 'bold'))
self.getControl(INFO).setLabel(typo(config.getLocalizedString(70823) + self.title, 'bold'))
self.manual = True
if self.episodes:
items = []
@@ -588,7 +588,7 @@ def SelectreNumeration(opt, itemlist, manual=False):
self.getControl(SELECTED).selectItem(index)
# RELOAD SPECIALS
if control_id in [SELECTED]:
epnumber = platformtools.dialog_numeric(0, config.get_localized_string(60386))
epnumber = platformtools.dialogNumeric(0, config.getLocalizedString(60386))
if epnumber:
it = self.getControl(SELECTED).getSelectedItem()
it.setLabel(str(epnumber))
@@ -613,10 +613,10 @@ def SelectreNumeration(opt, itemlist, manual=False):
e = int(self.getControl(MLIST).getSelectedItem().getProperty('episode'))
pos = self.getControl(MLIST).getSelectedPosition()
if control_id in [MS]:
selected = platformtools.dialog_numeric(0, config.get_localized_string(70825), str(s))
selected = platformtools.dialogNumeric(0, config.getLocalizedString(70825), str(s))
if selected: s = int(selected)
elif control_id in [ME]:
selected = platformtools.dialog_numeric(0, config.get_localized_string(70826), str(e))
selected = platformtools.dialogNumeric(0, config.getLocalizedString(70826), str(e))
if selected: e = int(selected)
if s != self.season or e != self.episode:
self.season = s
@@ -740,4 +740,4 @@ DOWN = 4
EXIT = 10
BACKSPACE = 92
path = config.get_runtime_path()
path = config.getRuntimePath()

View File

@@ -25,12 +25,12 @@ videolibrary_tvshows_path = unicode(videolibrarytools.TVSHOWS_PATH)
def export_videolibrary(item):
logger.info()
zip_file_folder = platformtools.dialog_browse(3, config.get_localized_string(80002))
zip_file_folder = platformtools.dialogBrowse(3, config.getLocalizedString(80002))
if zip_file_folder == "":
return
zip_file = unicode(xbmc.translatePath(zip_file_folder + "KoD_video_library-" + str(datetime.date.today()) + ".zip"))
p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80003))
p_dialog = platformtools.dialogProgressBg(config.getLocalizedString(20000), config.getLocalizedString(80003))
# p_dialog.update(0)
if filetools.exists(videolibrary_temp_path):
@@ -50,19 +50,19 @@ def export_videolibrary(item):
p_dialog.update(100)
xbmc.sleep(1000)
p_dialog.close()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80004), time=5000, sound=False)
platformtools.dialogNotification(config.getLocalizedString(20000), config.getLocalizedString(80004), time=5000, sound=False)
def import_videolibrary(item):
logger.info()
zip_file = unicode(platformtools.dialog_browse(1, config.get_localized_string(80005), mask=".zip"))
zip_file = unicode(platformtools.dialogBrowse(1, config.getLocalizedString(80005), mask=".zip"))
if zip_file == "":
return
if not platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(80006)):
if not platformtools.dialogYesNo(config.getLocalizedString(20000), config.getLocalizedString(80006)):
return
p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80007))
p_dialog = platformtools.dialogProgressBg(config.getLocalizedString(20000), config.getLocalizedString(80007))
# p_dialog.update(0)
if filetools.exists(temp_path):
@@ -72,14 +72,14 @@ def import_videolibrary(item):
unzip(videolibrary_temp_path, zip_file)
p_dialog.update(20)
if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
if config.is_xbmc() and config.getSetting("videolibrary_kodi"):
xbmc_videolibrary.clean()
p_dialog.update(30)
shutil.rmtree(videolibrary_movies_path)
shutil.rmtree(videolibrary_tvshows_path)
p_dialog.update(50)
config.verify_directories_created()
config.verifyDirectoriesCreated()
if filetools.exists(movies_path):
copy_tree(movies_path, videolibrary_movies_path)
p_dialog.update(70)
@@ -91,10 +91,10 @@ def import_videolibrary(item):
p_dialog.update(100)
xbmc.sleep(1000)
p_dialog.close()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80008), time=5000, sound=False)
platformtools.dialogNotification(config.getLocalizedString(20000), config.getLocalizedString(80008), time=5000, sound=False)
videolibrary.update_videolibrary()
if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
if config.is_xbmc() and config.getSetting("videolibrary_kodi"):
xbmc_videolibrary.update()

View File

@@ -184,13 +184,13 @@ class Kdicc():
txt += '\nIP: %s' % self.ip_addr
dialog = xbmcgui.Dialog()
if config.get_setting('checkdns'):
risposta= dialog.yesno(addonname, txt, nolabel=config.get_localized_string(707403), yeslabel=config.get_localized_string(707404))
if config.getSetting('checkdns'):
risposta= dialog.yesno(addonname, txt, nolabel=config.getLocalizedString(707403), yeslabel=config.getLocalizedString(707404))
if risposta == False:
config.set_setting('checkdns', False)
dialog.textviewer(addonname+' '+config.get_localized_string(707405), config.get_localized_string(707406))
config.setSetting('checkdns', False)
dialog.textviewer(addonname+' '+config.getLocalizedString(707405), config.getLocalizedString(707406))
else:
txt = config.get_localized_string(707402)
txt = config.getLocalizedString(707402)
dialog.notification(addonname, txt, xbmcgui.NOTIFICATION_INFO, 10000)
"""
def called in launcher.py
@@ -204,20 +204,20 @@ def test_conn(is_exit, check_dns, view_msg,
# I don't let you get into the addon
# enter language code
if view_msg == True:
ktest.view_Advise(config.get_localized_string(70720))
ktest.view_Advise(config.getLocalizedString(70720))
if ktest.is_exit == True:
exit()
# if it has no ADSL connection, I will communicate it to the user
if not ktest.check_Adsl():
if view_msg == True:
ktest.view_Advise(config.get_localized_string(70721))
ktest.view_Advise(config.getLocalizedString(70721))
if ktest.is_exit == True:
exit()
# if it has DNS filtered, I will communicate it to the user
if check_dns == True:
if not ktest.check_Dns():
if view_msg == True:
ktest.view_Advise(config.get_localized_string(70722))
ktest.view_Advise(config.getLocalizedString(70722))
logger.info("############ Start Check DNS ############")
logger.info("## IP: %s" % (ktest.ip_addr))

View File

@@ -12,33 +12,35 @@ PLUGIN_NAME = "kod"
__settings__ = xbmcaddon.Addon(id="plugin.video." + PLUGIN_NAME)
__language__ = __settings__.getLocalizedString
__version_fix = None
__dev_mode = None
__devMode = None
channels_data = dict()
channelsData = dict()
changelogFile = xbmc.translatePath("special://profile/addon_data/plugin.video.kod/changelog.txt")
addonIcon = os.path.join(__settings__.getAddonInfo( "path" ),'resources', 'media', "logo.png" )
def get_addon_core():
def getAddonCore():
return __settings__
def get_addon_version(with_fix=True):
def getAddonVersion(with_fix=True):
'''
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()
return __settings__.getAddonInfo('version') + " " + getAddonVersionFix()
else:
return __settings__.getAddonInfo('version')
def get_addon_version_fix():
def getAddonVersionFix():
global __version_fix
ret = __version_fix
if not ret:
if not dev_mode():
if not devMode():
try:
sha = open(os.path.join(get_runtime_path(), 'last_commit.txt')).readline()
sha = open(os.path.join(getRuntimePath(), 'last_commit.txt')).readline()
ret = sha[:7]
except:
ret = '??'
@@ -47,14 +49,14 @@ def get_addon_version_fix():
return ret
def dev_mode():
global __dev_mode
if not __dev_mode:
__dev_mode = os.path.isdir(get_runtime_path() + '/.git')
return __dev_mode
def devMode():
global __devMode
if not __devMode:
__devMode = os.path.isdir(getRuntimePath() + '/.git')
return __devMode
def get_platform(full_version=False):
def getXBMCPlatform(full_version=False):
"""
Returns the information the version of xbmc or kodi on which the plugin is run
@@ -95,6 +97,57 @@ def get_platform(full_version=False):
else:
return ret['platform']
def getPlatform():
import platform
build = xbmc.getInfoLabel("System.BuildVersion")
kodi_version = int(build.split()[0][:2])
ret = {
"auto_arch": sys.maxsize > 2 ** 32 and "64-bit" or "32-bit",
"arch": sys.maxsize > 2 ** 32 and "x64" or "ia32",
"os": "",
"version": platform.release(),
"kodi": kodi_version,
"build": build
}
if xbmc.getCondVisibility("system.platform.android"):
ret["os"] = "android"
if "arm" in platform.machine() or "aarch" in platform.machine():
ret["arch"] = "arm"
if "64" in platform.machine() and ret["auto_arch"] == "64-bit":
ret["arch"] = "arm64"
elif xbmc.getCondVisibility("system.platform.linux"):
ret["os"] = "linux"
if "aarch" in platform.machine() or "arm64" in platform.machine():
if xbmc.getCondVisibility("system.platform.linux.raspberrypi"):
ret["arch"] = "armv7"
elif ret["auto_arch"] == "32-bit":
ret["arch"] = "armv7"
elif ret["auto_arch"] == "64-bit":
ret["arch"] = "arm64"
elif platform.architecture()[0].startswith("32"):
ret["arch"] = "arm"
else:
ret["arch"] = "arm64"
elif "armv7" in platform.machine():
ret["arch"] = "armv7"
elif "arm" in platform.machine():
ret["arch"] = "arm"
elif xbmc.getCondVisibility("system.platform.xbox"):
ret["os"] = "win"
ret["arch"] = "x64"
elif xbmc.getCondVisibility("system.platform.windows"):
ret["os"] = "win"
if platform.machine().endswith('64'):
ret["arch"] = "x64"
elif xbmc.getCondVisibility("system.platform.osx"):
ret["os"] = "mac"
ret["arch"] = "x64"
elif xbmc.getCondVisibility("system.platform.ios"):
ret["os"] = "ios"
ret["arch"] = "arm"
return ret
def is_xbmc():
return True
@@ -108,26 +161,26 @@ def get_channel_url(findhostMethod=None, name=None, forceFindhost=False):
from core import jsontools
import inspect
LOCAL_FILE = os.path.join(get_runtime_path(), "channels.json")
global channels_data
if not channels_data:
LOCAL_FILE = os.path.join(getRuntimePath(), "channels.json")
global channelsData
if not channelsData:
with open(LOCAL_FILE) as f:
channels_data = jsontools.load(f.read())
channelsData = jsontools.load(f.read())
frame = inspect.stack()[1]
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')
url = jsontools.getNodeFromFile(name, 'url')
if not url or forceFindhost:
url = findhostMethod(channels_data['findhost'][name])
jsontools.update_node(url, name, 'url')
url = findhostMethod(channelsData['findhost'][name])
jsontools.updateNode(url, name, 'url')
return url
else:
return channels_data['direct'][name]
return channelsData['direct'][name]
def get_system_platform():
def getSystemPlatform():
""" function: to recover the platform that xbmc is running """
platform = "unknown"
if xbmc.getCondVisibility("system.platform.linux"):
@@ -139,35 +192,35 @@ def get_system_platform():
return platform
def get_all_settings_addon():
def getAllSettingsAddon():
# Read the settings.xml file and return a dictionary with {id: value}
from core import scrapertools
with open(os.path.join(get_data_path(), "settings.xml"), "rb") as infile:
with open(os.path.join(getDataPath(), "settings.xml"), "rb") as infile:
data = infile.read().decode('utf-8')
ret = {}
matches = scrapertools.find_multiple_matches(data, '<setting id=\"([^\"]+)\"[^>]*>')
matches = scrapertools.findMultipleMatches(data, '<setting id=\"([^\"]+)\"[^>]*>')
for _id in matches:
ret[_id] = get_setting(_id)
ret[_id] = getSetting(_id)
return ret
def open_settings():
def openSettings():
xbmc.executebuiltin('Addon.OpenSettings(plugin.video.%s)' % PLUGIN_NAME)
def get_setting(name, channel="", server="", default=None):
def getSetting(name, channel="", server="", default=None):
"""
Returns the configuration value of the requested parameter.
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'.
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
the result of calling channeltools.getChannelSetting (name, channel, default). If the name of the
server will return the result of calling servertools.getChannelSetting (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.
@@ -187,23 +240,23 @@ def get_setting(name, channel="", server="", default=None):
# Specific channel setting
if channel:
# logger.info("get_setting reading channel setting '"+name+"' from channel json")
# logger.info("getSetting reading channel setting '"+name+"' from channel json")
from core import channeltools
value = channeltools.get_channel_setting(name, channel, default)
# logger.info("get_setting -> '"+repr(value)+"'")
value = channeltools.getChannelSetting(name, channel, default)
# logger.info("getSetting -> '"+repr(value)+"'")
return value
# Specific server setting
elif server:
# logger.info("get_setting reading server setting '"+name+"' from server json")
# logger.info("getSetting reading server setting '"+name+"' from server json")
from core import servertools
value = servertools.get_server_setting(name, server, default)
# logger.info("get_setting -> '"+repr(value)+"'")
value = servertools.getServerSetting(name, server, default)
# logger.info("getSetting -> '"+repr(value)+"'")
return value
# Global setting
else:
# logger.info("get_setting reading main setting '"+name+"'")
# logger.info("getSetting reading main setting '"+name+"'")
value = __settings__.getSetting(name)
if not value:
return default
@@ -225,7 +278,7 @@ def get_setting(name, channel="", server="", default=None):
return value
def set_setting(name, value, channel="", server=""):
def setSetting(name, value, channel="", server=""):
"""
Sets the configuration value of the indicated parameter.
@@ -249,10 +302,10 @@ def set_setting(name, value, channel="", server=""):
"""
if channel:
from core import channeltools
return channeltools.set_channel_setting(name, value, channel)
return channeltools.setChannelSetting(name, value, channel)
elif server:
from core import servertools
return servertools.set_server_setting(name, value, server)
return servertools.setServerSetting(name, value, server)
else:
try:
if isinstance(value, bool):
@@ -274,7 +327,7 @@ def set_setting(name, value, channel="", server=""):
return value
def get_localized_string(code):
def getLocalizedString(code):
dev = __language__(code)
try:
@@ -295,43 +348,43 @@ def get_localized_string(code):
return dev
def get_localized_category(categ):
categories = {'movie': get_localized_string(30122), 'tvshow': get_localized_string(30123),
'anime': get_localized_string(30124), 'documentary': get_localized_string(30125),
'vos': get_localized_string(30136), 'sub': get_localized_string(30136),
'direct': get_localized_string(30137), 'torrent': get_localized_string(70015),
'live': get_localized_string(30138), 'music': get_localized_string(30139)
def getLocalizedCategory(categ):
categories = {'movie': getLocalizedString(30122), 'tvshow': getLocalizedString(30123),
'anime': getLocalizedString(30124), 'documentary': getLocalizedString(30125),
'vos': getLocalizedString(30136), 'sub': getLocalizedString(30136),
'direct': getLocalizedString(30137), 'torrent': getLocalizedString(70015),
'live': getLocalizedString(30138), 'music': getLocalizedString(30139)
}
return categories[categ] if categ in categories else categ
def get_localized_language(lang):
def getLocalizedLanguage(lang):
languages = {'ita': 'ITA', 'sub-ita': 'Sub-ITA'}
return languages[lang] if lang in languages else lang
def get_videolibrary_config_path():
value = get_setting("videolibrarypath")
def getVideolibraryConfigPath():
value = getSetting("videolibrarypath")
if value == "":
verify_directories_created()
value = get_setting("videolibrarypath")
verifyDirectoriesCreated()
value = getSetting("videolibrarypath")
return value
def get_videolibrary_path():
return xbmc.translatePath(get_videolibrary_config_path())
def getVideolibraryPath():
return xbmc.translatePath(getVideolibraryConfigPath())
def get_temp_file(filename):
def getTempFile(filename):
return xbmc.translatePath(os.path.join("special://temp/", filename))
def get_runtime_path():
def getRuntimePath():
return xbmc.translatePath(__settings__.getAddonInfo('Path'))
def get_data_path():
def getDataPath():
dev = xbmc.translatePath(__settings__.getAddonInfo('Profile'))
# Create the directory if it doesn't exist
@@ -341,17 +394,17 @@ def get_data_path():
return dev
def get_icon():
def getIcon():
return xbmc.translatePath(__settings__.getAddonInfo('icon'))
def get_fanart():
def getFanart():
return xbmc.translatePath(__settings__.getAddonInfo('fanart'))
def get_cookie_data():
def getCookieData():
import os
ficherocookies = os.path.join(get_data_path(), 'cookies.dat')
ficherocookies = os.path.join(getDataPath(), 'cookies.dat')
cookiedatafile = open(ficherocookies, 'r')
cookiedata = cookiedatafile.read()
@@ -361,7 +414,7 @@ def get_cookie_data():
# Test if all the required directories are created
def verify_directories_created():
def verifyDirectoriesCreated():
from platformcode import logger
from core import filetools
from platformcode import xbmc_videolibrary
@@ -372,18 +425,18 @@ def verify_directories_created():
["settings_path", "settings_channels"]]
for path, default in config_paths:
saved_path = get_setting(path)
saved_path = getSetting(path)
# video store
if path == "videolibrarypath":
if not saved_path:
saved_path = xbmc_videolibrary.search_library_path()
if saved_path:
set_setting(path, saved_path)
setSetting(path, saved_path)
if not saved_path:
saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
set_setting(path, saved_path)
setSetting(path, saved_path)
saved_path = xbmc.translatePath(saved_path)
if not filetools.exists(saved_path):
@@ -394,13 +447,13 @@ def verify_directories_created():
["folder_tvshows", "Serie TV"]]
for path, default in config_paths:
saved_path = get_setting(path)
saved_path = getSetting(path)
if not saved_path:
saved_path = default
set_setting(path, saved_path)
setSetting(path, saved_path)
content_path = filetools.join(get_videolibrary_path(), saved_path)
content_path = filetools.join(getVideolibraryPath(), saved_path)
if not filetools.exists(content_path):
logger.debug("Creating %s: %s" % (path, content_path))
@@ -408,8 +461,8 @@ def verify_directories_created():
filetools.mkdir(content_path)
from platformcode import xbmc_videolibrary
xbmc_videolibrary.update_sources(get_setting("videolibrarypath"))
xbmc_videolibrary.update_sources(get_setting("downloadpath"))
xbmc_videolibrary.update_sources(getSetting("videolibrarypath"))
xbmc_videolibrary.update_sources(getSetting("downloadpath"))
try:
from core import scrapertools
@@ -419,14 +472,14 @@ def verify_directories_created():
# We extract the name of the default resolution folder
folder = ""
data = filetools.read(skindir)
res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
res = scrapertools.findMultipleMatches(data, '(<res .*?>)')
for r in res:
if 'default="true"' in r:
folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
break
# We check if it exists in the addon and if not, we create it
default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default')
default = filetools.join(getRuntimePath(), 'resources', 'skins', 'Default')
if folder and not filetools.exists(filetools.join(default, folder)):
filetools.mkdir(filetools.join(default, folder))
@@ -442,5 +495,5 @@ def verify_directories_created():
logger.error(traceback.format_exc())
def get_online_server_thumb(server):
def getOnlineServerThumb(server):
return "https://raw.github.com/kodiondemand/media/master/resources/servers/" + server.lower().replace('_server','') + '.png'

View File

@@ -2,14 +2,14 @@ import xbmc, sys, os
from platformcode import config, logger
import re
# incliuding folder libraries
librerias = xbmc.translatePath(os.path.join(config.get_runtime_path(), 'lib'))
librerias = xbmc.translatePath(os.path.join(config.getRuntimePath(), 'lib'))
sys.path.insert(0, librerias)
from core import tmdb
from core.item import Item
addon_id = config.get_addon_core().getAddonInfo('id')
addon_id = config.getAddonCore().getAddonInfo('id')
global item_is_coming_from_kod
@@ -26,10 +26,10 @@ def check_condition():
logger.debug('listitem mediatype:',mediatype )
logger.debug('filenamepath:', fileNameAndPath )
logger.info('filepath:', filePath )
item_is_coming_from_kod = addon_id in filePath
if not item_is_coming_from_kod:
videolibpath = config.get_setting("videolibrarypath")
videolibpath = config.getSetting("videolibrarypath")
if filePath.startswith(videolibpath):
pattern = re.compile("\[.*\][\\\/]?$")
item_is_coming_from_kod = pattern.search(filePath)
@@ -43,7 +43,7 @@ def check_condition():
def get_menu_items():
logger.debug('get menu item')
if check_condition():
return [(config.get_localized_string(90003 if item_is_coming_from_kod else 90005), execute)]
return [(config.getLocalizedString(90003 if item_is_coming_from_kod else 90005), execute)]
else:
return []

View File

@@ -5,7 +5,7 @@ from platformcode import config
def get_menu_items():
return [(config.get_localized_string(60359), execute)]
return [(config.getLocalizedString(60359), execute)]
def execute():

View File

@@ -2,7 +2,7 @@
import xbmc, sys, xbmcgui, os, xbmcvfs, traceback
from platformcode import config, logger
librerias = xbmc.translatePath(os.path.join(config.get_runtime_path(), 'lib'))
librerias = xbmc.translatePath(os.path.join(config.getRuntimePath(), 'lib'))
sys.path.insert(0, librerias)
from core.item import Item
@@ -52,7 +52,7 @@ def search_paths(Id):
for record in records:
path_records = execute_sql('SELECT strPath FROM path WHERE idPath LIKE "%s"' % record[0])
for path in path_records:
if config.get_setting('videolibrarypath') in path[0] and exists(join(path[0], 'tvshow.nfo')):
if config.getSetting('videolibrarypath') in path[0] and exists(join(path[0], 'tvshow.nfo')):
return path[0]
return ''
@@ -63,7 +63,7 @@ def execute_sql(sql):
records = None
# We look for the archive of the video database according to the version of kodi
video_db = config.get_platform(True)['video_db']
video_db = config.getXBMCPlatform(True)['video_db']
if video_db:
file_db = os.path.join(xbmc.translatePath("special://userdata/Database"), video_db)
@@ -130,7 +130,7 @@ def check_condition():
def get_menu_items():
logger.debug('get menu item')
if check_condition():
items = [(config.get_localized_string(70269), update)]
items = [(config.getLocalizedString(70269), update)]
from core.videolibrarytools import read_nfo
nfo = path + 'tvshow.nfo'
item = read_nfo(nfo)[1]
@@ -139,16 +139,16 @@ def get_menu_items():
item_url = item.tourl()
# Context menu: Automatically search for new episodes or not
if item.active and int(item.active) > 0:
update_text = config.get_localized_string(60022)
update_text = config.getLocalizedString(60022)
value = 0
else:
update_text = config.get_localized_string(60023)
update_text = config.getLocalizedString(60023)
value = 1
items.append((update_text, lambda: xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?{}&title={}&action=mark_tvshow_as_updatable&channel=videolibrary&active={})".format(item_url, update_text, str(value)))))
if item.local_episodes_path == "":
items.append((config.get_localized_string(80048), lambda: xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?{}&action=add_local_episodes&channel=videolibrary&path={})".format(item_url, path))))
items.append((config.getLocalizedString(80048), lambda: xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?{}&action=add_local_episodes&channel=videolibrary&path={})".format(item_url, path))))
else:
items.append((config.get_localized_string(80049), lambda: xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?{}&action=remove_local_episodes&channel=videolibrary&path={})".format(item_url, path))))
items.append((config.getLocalizedString(80049), lambda: xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?{}&action=remove_local_episodes&channel=videolibrary&path={})".format(item_url, path))))
return items
else:

View File

@@ -52,7 +52,7 @@ def reload():
def add_video(item):
global conn
conn = sqlite3.connect(get_file_db())
progress = platformtools.dialog_progress_bg('Sincronizzazione Libreria', item.title)
progress = platformtools.dialogProgressBg('Sincronizzazione Libreria', item.title)
progress.update(0)
if item.contentType == 'movie':
start = time()
@@ -70,10 +70,10 @@ def add_video(item):
def get_path(item):
logger.debug()
p = item.strm_path if item.strm_path else item.nfo_path
path = filetools.join(config.get_videolibrary_config_path(), config.get_setting("folder_{}s".format(item.contentType)), p.split('\\')[0].split('/')[0])
parent = filetools.join(config.get_videolibrary_config_path(), config.get_setting("folder_{}s".format(item.contentType)))
path = filetools.join(config.getVideolibraryConfigPath(), config.getSetting("folder_{}s".format(item.contentType)), p.split('\\')[0].split('/')[0])
parent = filetools.join(config.getVideolibraryConfigPath(), config.getSetting("folder_{}s".format(item.contentType)))
if item.contentType == 'movie':
filepath = filetools.join(config.get_videolibrary_config_path(), config.get_setting("folder_{}s".format(item.contentType)), p)
filepath = filetools.join(config.getVideolibraryConfigPath(), config.getSetting("folder_{}s".format(item.contentType)), p)
file = item.strm_path.split('\\')[-1].split('/')[-1]
return process_path(path), process_path(parent), file, filepath
else:

View File

@@ -37,14 +37,14 @@ def download_and_play(url, file_name, download_path):
while True:
cancelled = False
dialog = xbmcgui.DialogProgress()
dialog.create(config.get_localized_string(60200), config.get_localized_string(60312))
dialog.create(config.getLocalizedString(60200), config.getLocalizedString(60312))
dialog.update(0)
while not cancelled and download_thread.is_alive():
dialog.update(download_thread.get_progress(), config.get_localized_string(60313) + '\n' +
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",
config.get_localized_string(60202) % (str(downloadtools.sec_to_hms(download_thread.get_remaining_time()))))
dialog.update(download_thread.get_progress(), config.getLocalizedString(60313) + '\n' +
config.getLocalizedString(60314) + str(int(old_div(download_thread.get_speed(), 1024))) + " KB/s " + str(
download_thread.get_actual_size()) + config.getLocalizedString(60316) + str( download_thread.get_total_size()) + "MB",
config.getLocalizedString(60202) % (str(downloadtools.sec_to_hms(download_thread.get_remaining_time()))))
xbmc.sleep(1000)
if dialog.iscanceled():
@@ -189,7 +189,7 @@ class DownloadThread(threading.Thread):
oldcwd = os.getcwd()
logger.info("oldcwd= " + oldcwd)
cwd = os.path.join(config.get_runtime_path(), "tools")
cwd = os.path.join(config.getRuntimePath(), "tools")
logger.info("cwd= " + cwd)
os.chdir(cwd)
logger.info("directory changed to= " + os.getcwd())
@@ -286,7 +286,7 @@ class DownloadThread(threading.Thread):
logger.info("Force_stop file detected, download is interrupted")
f.close()
xbmc.executebuiltin("Notification(%s,%s,300)" % (config.get_localized_string(60319),config.get_localized_string(60320)))
xbmc.executebuiltin("Notification(%s,%s,300)" % (config.getLocalizedString(60319),config.getLocalizedString(60320)))
return

View File

@@ -5,7 +5,7 @@ import xbmc, xbmcaddon, sys, platform
host = 'https://github.com'
elementum_url = host + '/elgatito/plugin.video.elementum/releases'
filename = filetools.join(config.get_data_path(),'elementum.zip')
filename = filetools.join(config.getDataPath(),'elementum.zip')
addon_path = xbmc.translatePath('special://home/addons/')
setting_path = xbmc.translatePath('special://profile/addon_data/')
elementum_path = filetools.join(addon_path,'plugin.video.elementum')
@@ -17,16 +17,16 @@ kod_setting_file = filetools.join(addon_path,'plugin.video.kod', 'resources', 's
def download(item=None):
if filetools.exists(elementum_path):
if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70783)):
if platformtools.dialogYesNo(config.getLocalizedString(70784), config.getLocalizedString(70783)):
addon_file = filetools.file_open(filetools.join(elementum_path,'addon.xml')).read()
required = support.match(addon_file, patron=r'addon="([^"]+)').matches
for r in required: xbmc.executebuiltin('InstallAddon(' + r + ')', wait=True)
setting()
platformtools.dialog_ok('Elementum', config.get_localized_string(70783))
platformtools.dialogOk('Elementum', config.getLocalizedString(70783))
else:
if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70782)):
pform = get_platform()
if platformtools.dialogYesNo(config.getLocalizedString(70784), config.getLocalizedString(70782)):
pform = getPlatform()
url = support.match(elementum_url, patronBlock=r'<div class="release-entry">(.*?)<!-- /.release-body -->', patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % pform).match
logger.debug('OS:', pform)
logger.debug('Extract IN:', elementum_path)
@@ -90,7 +90,7 @@ def setting():
filetools.remove(filename)
def get_platform():
def getPlatform():
build = xbmc.getInfoLabel("System.BuildVersion")
kodi_version = int(build.split()[0][:2])
ret = {

View File

@@ -32,7 +32,7 @@ def get_environment():
import base64
import ast
environment = config.get_platform(full_version=True)
environment = config.getXBMCPlatform(full_version=True)
environment['num_version'] = str(environment['num_version'])
environment['python_version'] = str(platform.python_version())
@@ -128,7 +128,7 @@ def get_environment():
except:
pass
environment['userdata_path'] = str(xbmc.translatePath(config.get_data_path()))
environment['userdata_path'] = str(xbmc.translatePath(config.getDataPath()))
try:
if environment['os_name'].lower() == 'windows':
free_bytes = ctypes.c_ulonglong(0)
@@ -145,21 +145,21 @@ def get_environment():
environment['videolab_series'] = '?'
environment['videolab_episodes'] = '?'
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")))))
environment['videolab_path'] = str(xbmc.translatePath(config.getVideolibraryPath()))
if filetools.exists(filetools.join(environment['videolab_path'], config.getSetting("folder_tvshows"))):
environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], config.getSetting("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.getSetting("folder_tvshows"))):
for file in files:
if file.endswith('.strm'): counter += 1
environment['videolab_episodes'] = 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.getSetting("folder_movies"))):
environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], config.getSetting("folder_movies")))))
except:
pass
try:
video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez']
environment['videolab_update'] = str(video_updates[config.get_setting("update", "videolibrary")])
environment['videolab_update'] = str(video_updates[config.getSetting("update", "videolibrary")])
except:
environment['videolab_update'] = '?'
try:
@@ -177,14 +177,14 @@ def get_environment():
# environment['torrent_list'] = []
# environment['torrentcli_option'] = ''
# environment['torrent_error'] = ''
# environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True)
# environment['torrentcli_backgr'] = config.get_setting("mct_background_download", server="torrent", default=True)
# environment['torrentcli_lib_path'] = config.get_setting("libtorrent_path", server="torrent", default="")
# environment['torrentcli_rar'] = config.getSetting("mct_rar_unpack", server="torrent", default=True)
# environment['torrentcli_backgr'] = config.getSetting("mct_background_download", server="torrent", default=True)
# environment['torrentcli_lib_path'] = config.getSetting("libtorrent_path", server="torrent", default="")
# if environment['torrentcli_lib_path']:
# lib_path = 'Activo'
# else:
# lib_path = 'Inactivo'
# environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="")
# environment['torrentcli_unrar'] = config.getSetting("unrar_path", server="torrent", default="")
# if environment['torrentcli_unrar']:
# if xbmc.getCondVisibility("system.platform.Android"):
# unrar = 'Android'
@@ -196,33 +196,33 @@ def get_environment():
# unrar = scrapertools.find_single_match(unrar, '\/([^\/]+)\/$').capitalize()
# else:
# unrar = 'Inactivo'
# torrent_id = config.get_setting("torrent_client", server="torrent", default=0)
# torrent_id = config.getSetting("torrent_client", server="torrent", default=0)
# environment['torrentcli_option'] = str(torrent_id)
# torrent_options = platformtools.torrent_client_installed()
# torrentOptions = platformtools.torrentClientInstalled()
# if lib_path == 'Activo':
# torrent_options = ['MCT'] + torrent_options
# torrent_options = ['BT'] + torrent_options
# torrentOptions = ['MCT'] + torrentOptions
# torrentOptions = ['BT'] + torrentOptions
# environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \
# 'RAR_Auto': str(environment['torrentcli_rar']), \
# 'RAR_backgr': str(environment['torrentcli_backgr']), \
# 'UnRAR': unrar})
# environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="")
# environment['torrent_error'] = config.getSetting("libtorrent_error", server="torrent", default="")
# if environment['torrent_error']:
# environment['torrent_list'].append({'Libtorrent_error': environment['torrent_error']})
# for torrent_option in torrent_options:
# for torrent_option in torrentOptions:
# cliente = dict()
# cliente['D_load_Path'] = ''
# cliente['Libre'] = '?'
# cliente['Plug_in'] = torrent_option.replace('Plugin externo: ', '')
# if cliente['Plug_in'] == 'BT':
# cliente['D_load_Path'] = str(config.get_setting("bt_download_path", server="torrent", default=''))
# cliente['D_load_Path'] = str(config.getSetting("bt_download_path", server="torrent", default=''))
# if not cliente['D_load_Path']: continue
# cliente['Buffer'] = str(config.get_setting("bt_buffer", server="torrent", default=50))
# cliente['Buffer'] = str(config.getSetting("bt_buffer", server="torrent", default=50))
# elif cliente['Plug_in'] == 'MCT':
# cliente['D_load_Path'] = str(config.get_setting("mct_download_path", server="torrent", default=''))
# cliente['D_load_Path'] = str(config.getSetting("mct_download_path", server="torrent", default=''))
# if not cliente['D_load_Path']: continue
# cliente['Buffer'] = str(config.get_setting("mct_buffer", server="torrent", default=50))
# cliente['Buffer'] = str(config.getSetting("mct_buffer", server="torrent", default=50))
# elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % cliente['Plug_in']):
# __settings__ = xbmcaddon.Addon(id="plugin.video.%s" % cliente['Plug_in'])
# cliente['Plug_in'] = cliente['Plug_in'].capitalize()
@@ -258,7 +258,7 @@ def get_environment():
environment['proxy_active'] = ''
try:
proxy_channel_bloqued_str = base64.b64decode(config.get_setting('proxy_channel_bloqued')).decode('utf-8')
proxy_channel_bloqued_str = base64.b64decode(config.getSetting('proxy_channel_bloqued')).decode('utf-8')
proxy_channel_bloqued = dict()
proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str)
for channel_bloqued, proxy_active in list(proxy_channel_bloqued.items()):
@@ -289,8 +289,8 @@ def get_environment():
environment['log_size_bytes'] = ''
environment['log_size'] = ''
environment['debug'] = str(config.get_setting('debug'))
environment['addon_version'] = str(config.get_addon_version())
environment['debug'] = str(config.getSetting('debug'))
environment['addon_version'] = str(config.getAddonVersion())
except:
logger.error(traceback.format_exc())

View File

@@ -39,7 +39,7 @@ BACKSPACE = 92
def start(item):
xbmc.executebuiltin('Dialog.Close(all)')
InfoPlus('InfoPlus.xml', config.get_runtime_path(), item=item)
InfoPlus('InfoPlus.xml', config.getRuntimePath(), item=item)
class InfoPlus(xbmcgui.WindowXML):
def __init__(self, *args, **kwargs):
@@ -57,7 +57,7 @@ class InfoPlus(xbmcgui.WindowXML):
self.fanarts = []
self.collection = []
if not self.item.focus: self.item.focus = {}
platformtools.dialog_busy(True)
platformtools.dialogBusy(True)
if self.item:
# Find Video Info
@@ -88,7 +88,7 @@ class InfoPlus(xbmcgui.WindowXML):
self.listitem.setProperty('info',info)
# Set infoLabels
platformtools.set_infolabels(self.listitem, self.item)
platformtools.setInfolabels(self.listitem, self.item)
# Add Cast Info
for cast in self.info.get('castandrole',[]):
@@ -128,9 +128,9 @@ class InfoPlus(xbmcgui.WindowXML):
self.get_trailers()
# Add Fanart
self.get_fanarts()
self.getFanarts()
platformtools.dialog_busy(False)
platformtools.dialogBusy(False)
self.doModal()
@@ -199,10 +199,10 @@ class InfoPlus(xbmcgui.WindowXML):
self.item.text = self.item.contentTitle
titles = [self.item.text] + [original] if original else []
if original and original != self.item.text:
selection = platformtools.dialog_select(config.get_localized_string(90010), titles)
selection = platformtools.dialogSelect(config.getLocalizedString(90010), titles)
if selection > -1:
self.item.text = titles[selection]
self.item.mode = 'search_' + self.item.contentType
self.item.mode = 'search/' + self.item.contentType
item = self.item.clone(channel='globalsearch', action='new_search')
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.kod/?" + item.tourl() + ")")
# new_search(self.item.clone())
@@ -263,7 +263,7 @@ class InfoPlus(xbmcgui.WindowXML):
traileitem.setArt({'thumb':'http://img.youtube.com/vi/' + trailer['url'].split('=')[-1] + '/0.jpg'})
self.trailers.append(traileitem)
def get_fanarts(self):
def getFanarts(self):
_id = self.info.get('tmdb_id')
res = {}
fanarts = self.info.get('fanarts',[])
@@ -284,7 +284,7 @@ class InfoPlus(xbmcgui.WindowXML):
def showCast(item):
xbmc.executebuiltin('Dialog.Close(all)')
CastWindow('CastWindow.xml', config.get_runtime_path(), item=item)
CastWindow('CastWindow.xml', config.getRuntimePath(), item=item)
class CastWindow(xbmcgui.WindowXML):
def __init__(self, *args, **kwargs):
self.item = kwargs.get('item')
@@ -296,10 +296,10 @@ class CastWindow(xbmcgui.WindowXML):
self.tvshowItems = []
if not self.item.focus: self.item.focus = {}
if self.item:
platformtools.dialog_busy(True)
platformtools.dialogBusy(True)
self.get_person_info()
self.get_credits()
platformtools.dialog_busy(False)
platformtools.dialogBusy(False)
self.doModal()
def get_person_info(self):
@@ -413,7 +413,7 @@ class CastWindow(xbmcgui.WindowXML):
rating = video.get('vote_average', 'N/A')
color = 'FFFFFFFF' if rating == 'N/A' else 'FFDB2360' if rating < 4 else 'FFD2D531' if rating < 7 else 'FF21D07A'
videoitem.setProperties({'rating':str(int(video.get('vote_average',10) * 10)), 'color':color})
platformtools.set_infolabels(videoitem, item)
platformtools.setInfolabels(videoitem, item)
if video.get('media_type') == 'movie':
self.movies.append(videoitem)
self.movieItems.append(item)
@@ -424,7 +424,7 @@ class CastWindow(xbmcgui.WindowXML):
def showImages(images, position):
xbmc.executebuiltin('Dialog.Close(all)')
return ImagesWindow('imageWindow.xml', config.get_runtime_path()).start(images=images, position=position)
return ImagesWindow('imageWindow.xml', config.getRuntimePath()).start(images=images, position=position)
class ImagesWindow(xbmcgui.WindowXMLDialog):
def start(self, *args, **kwargs):
self.images = []

View File

@@ -7,13 +7,12 @@ from platformcode import config, logger, platformtools, launcher
from core import filetools
from core.item import Item
import channelselector
addon_icon = filetools.join( config.__settings__.getAddonInfo( "path" ),'resources', 'media', 'logo.png' )
background = 'FF232323'
overlay = '77232323'
text = 'FFFFFFFF'
select = 'FF0082C2'
if config.get_setting('icon_set') == 'dark':
if config.getSetting('icon_set') == 'dark':
background = 'FFDCDCDC'
overlay = '77DCDCDC'
text = 'FF232323'
@@ -37,13 +36,13 @@ class KeyListener(xbmcgui.WindowXMLDialog):
def onInit(self):
try:
self.getControl(400).setImage(addon_icon)
self.getControl(401).addLabel(config.get_localized_string(70698))
self.getControl(402).addLabel(config.get_localized_string(70699) % self.TIMEOUT)
self.getControl(400).setImage(config.addonIcon)
self.getControl(401).addLabel(config.getLocalizedString(70698))
self.getControl(402).addLabel(config.getLocalizedString(70699) % self.TIMEOUT)
except AttributeError:
self.getControl(400).setImage(addon_icon)
self.getControl(401).setLabel(config.get_localized_string(70698))
self.getControl(402).setLabel(config.get_localized_string(70699) % self.TIMEOUT)
self.getControl(400).setImage(config.addonIcon)
self.getControl(401).setLabel(config.getLocalizedString(70698))
self.getControl(402).setLabel(config.getLocalizedString(70699) % self.TIMEOUT)
def onAction(self, action):
@@ -68,7 +67,7 @@ class KeyListener(xbmcgui.WindowXMLDialog):
def set_key():
saved_key = config.get_setting("shortcut_key")
saved_key = config.getSetting("shortcut_key")
new_key = KeyListener().record_key()
if new_key and saved_key != new_key:
@@ -76,13 +75,14 @@ def set_key():
from platformcode import platformtools
import xbmc
file_xml = "special://profile/keymaps/kod.xml"
data = '<keymap><global><keyboard><key id="%s">' % new_key + 'runplugin(plugin://plugin.video.kod/?ew0KICAgICJhY3Rpb24iOiAia2V5bWFwIiwNCiAgICAib3BlbiI6IHRydWUNCn0=)</key></keyboard></global></keymap>'
data = '<keymap><global><keyboard><key id="%s">' % new_key + 'runplugin(plugin://plugin.video.kod/?channel=shortcuts&action=shortcut_menu)</key></keyboard></global></keymap>'
filetools.write(xbmc.translatePath(file_xml), data)
# platformtools.dialog_notification(config.get_localized_string(70700),config.get_localized_string(70702),4)
# platformtools.dialogNotification(config.getLocalizedString(70700),config.getLocalizedString(70702),4)
config.set_setting("shortcut_key", new_key)
config.setSetting("shortcut_key", new_key)
xbmc.executebuiltin('Action(reloadkeymaps)')
return
# return
def delete_key():
@@ -91,9 +91,9 @@ def delete_key():
import xbmc
filetools.remove(xbmc.translatePath( "special://profile/keymaps/kod.xml"))
# platformtools.dialog_notification(config.get_localized_string(70701),config.get_localized_string(70702),4)
# platformtools.dialogNotification(config.getLocalizedString(70701),config.getLocalizedString(70702),4)
config.set_setting("shortcut_key", '')
config.setSetting("shortcut_key", '')
xbmc.executebuiltin('Action(reloadkeymaps)')
LEFT = 1
@@ -113,7 +113,7 @@ class Main(xbmcgui.WindowXMLDialog):
self.MENU = self.getControl(1)
self.SUBMENU = self.getControl(2)
#### Compatibility with Kodi 18 ####
if config.get_platform(True)['num_version'] < 18:
if config.getXBMCPlatform(True)['num_version'] < 18:
self.setCoordinateResolution(2)
itemlist = self.menulist(channelselector.getmainlist())
@@ -160,7 +160,7 @@ class Main(xbmcgui.WindowXMLDialog):
def onAction(self, action):
if action.getButtonCode() == config.get_setting('shortcut_key'):
if action.getButtonCode() == config.getSetting('shortcut_key'):
self.close()
action = action.getId()
@@ -186,7 +186,7 @@ class Main(xbmcgui.WindowXMLDialog):
import channelselector
itemlist = self.menulist(channelselector.getchanneltypes())
elif channel_name not in ['downloads', 'setting', 'help']:
channel = platformtools.channel_import(channel_name)
channel = platformtools.channelImport(channel_name)
itemlist = self.menulist(channel.mainlist(Item().fromurl(self.MENU.getSelectedItem().getProperty('run'))))
self.SUBMENU.reset()
self.SUBMENU.addItems(itemlist)
@@ -196,7 +196,7 @@ class Main(xbmcgui.WindowXMLDialog):
focus = self.getFocusId()
item_url = self.MENU.getSelectedItem().getProperty('run')
item = Item().fromurl(item_url)
commands = platformtools.set_context_commands(item, item_url, Item())
commands = platformtools.setContextCommands(item, item_url, Item())
context = [c[0] for c in commands]
context_commands = [c[1].replace('Container.Refresh', 'RunPlugin').replace('Container.Update', 'RunPlugin') for c in commands]
index = xbmcgui.Dialog().contextmenu(context)
@@ -205,5 +205,5 @@ class Main(xbmcgui.WindowXMLDialog):
def open_shortcut_menu():
if xbmcgui.getCurrentWindowDialogId() == 9999:
main = Main('ShortCutMenu.xml', config.get_runtime_path())
main = Main('ShortCutMenu.xml', config.getRuntimePath())
main.doModal()

View File

@@ -3,33 +3,28 @@
# XBMC Launcher (xbmc / kodi)
# ------------------------------------------------------------
from specials import videolibrary
import sys, os
PY3 = False
if sys.version_info[0] >= 3:PY3 = True; unicode = str; unichr = chr; long = int
import sys
from core.item import Item
from core import filetools, videolibrarydb
from core import filetools
from platformcode import config, logger, platformtools
from platformcode.logger import WebErrorException
temp_search_file = config.get_temp_file('temp-search')
def start():
""" First function that is executed when entering the 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.debug()
if not config.dev_mode():
if not config.devMode():
try:
with open(config.changelogFile, 'r') as fileC:
changelog = fileC.read()
if changelog.strip():
platformtools.dialog_ok('Kodi on Demand', 'Aggiornamenti applicati:\n' + changelog)
os.remove(config.changelogFile)
platformtools.dialogOk('Kodi on Demand', 'Aggiornamenti applicati:\n' + changelog)
filetools.remove(config.changelogFile)
except:
pass
@@ -37,297 +32,57 @@ def start():
def run(item=None):
logger.debug()
if not item:
# Extract item from sys.argv
if sys.argv[2]:
sp = sys.argv[2].split('&')
url = sp[0]
item = Item().fromurl(url)
if len(sp) > 1:
for e in sp[1:]:
key, val = e.split('=')
if val.lower() == 'false': val = False
elif val.lower() == 'true': val = True
item.__setattr__(key, val)
# If no item, this is mainlist
else:
item = Item(channel="channelselector", action="getmainlist", viewmode="movie")
if not config.get_setting('show_once'):
if not config.get_all_settings_addon():
logger.error('corrupted settings.xml!!')
settings_xml = os.path.join(config.get_data_path(), "settings.xml")
settings_bak = os.path.join(config.get_data_path(), "settings.bak")
if filetools.exists(settings_bak):
filetools.copy(settings_bak, settings_xml, True)
logger.info('restored settings.xml from backup')
else:
filetools.write(settings_xml, '<settings version="2">\n</settings>') # resetted settings
else:
from platformcode import xbmc_videolibrary
xbmc_videolibrary.ask_set_content(silent=False)
config.set_setting('show_once', True)
# Extract item from sys.argv
if not item: item = makeItem()
logger.info(item.tostring())
# Load or Repare Settings
if not config.getSetting('show_once'): showOnce()
# Acrions
logger.debug(item.tostring())
try:
if not config.get_setting('tmdb_active'):
config.set_setting('tmdb_active', True)
# Active tmdb
if not config.getSetting('tmdb_active'):
config.setSetting('tmdb_active', True)
# If item has no action, stops here
if item.action == "":
logger.debug("Item without action")
if item.action == '':
logger.debug('Item without action')
return
# Action for main menu in channelselector
elif item.action == "getmainlist":
# Channel Selector
if item.channel == 'channelselector':
itemlist = []
import channelselector
if item.action == 'getmainlist': # Action for main menu in channelselector
itemlist = channelselector.getmainlist()
elif item.action == 'getchanneltypes': # Action for channel types on channelselector: movies, series, etc.
itemlist = channelselector.getchanneltypes()
elif item.action == 'filterchannels': # Action for channel listing on channelselector
itemlist = channelselector.filterchannels(item.channel_type)
platformtools.renderItems(itemlist, item)
itemlist = channelselector.getmainlist()
platformtools.render_items(itemlist, item)
# Action for channel types on channelselector: movies, series, etc.
elif item.action == "getchanneltypes":
import channelselector
itemlist = channelselector.getchanneltypes()
platformtools.render_items(itemlist, item)
# Action for channel listing on channelselector
elif item.action == "filterchannels":
import channelselector
itemlist = channelselector.filterchannels(item.channel_type)
platformtools.render_items(itemlist, item)
# Special action for playing a video from the library
elif item.action == "play_from_library":
play_from_library(item)
return
elif item.action in ['playFromLibrary', 'play_from_library']:
return playFromLibrary(item)
elif item.action == "keymap":
from platformcode import keymaptools
if item.open:
return keymaptools.open_shortcut_menu()
else:
return keymaptools.set_key()
# Special play action
elif item.action == 'play': play(item)
elif item.channel == "infoplus":
from platformcode import infoplus
return getattr(infoplus, item.action)(item)
# Special findvideos Action
elif item.action == 'findvideos': findvideos(item)
elif item.channel == 'trakt_tools':
from core import trakt_tools
action = getattr(trakt_tools, item.action)
return action(item)
# Special action for adding a movie or serie to the library
elif item.action == 'add_to_library': addToLibrary(item)
elif item.channel == "backup":
from platformcode import backup
return getattr(backup, item.action)(item)
# Special action for searching, first asks for the words then call the "search" function
elif item.action == 'search': search(item)
elif item.channel == "elementum_download":
from platformcode import elementum_download
return getattr(elementum_download, item.action)(item)
# For all other actions
else: actions(item)
elif item.channel == "shortcuts":
from platformcode import shortcuts
return getattr(shortcuts, item.action)(item)
elif item.channel == "autorenumber":
from platformcode import autorenumber
return getattr(autorenumber, item.action)(item)
elif item.action == "delete_key":
from platformcode import keymaptools
return keymaptools.delete_key()
elif item.action == "script":
from core import tmdb
tmdb.clean_cache()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False)
elif item.action == "itemInfo":
platformtools.dialog_textviewer('Item info', item.parent)
elif item.action == "open_browser":
import webbrowser
if not webbrowser.open(item.url):
import xbmc
if xbmc.getCondVisibility('system.platform.linux') and xbmc.getCondVisibility('system.platform.android'): # android
xbmc.executebuiltin('StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % item.url)
else:
platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(70740) % "\n".join([item.url[j:j+57] for j in range(0, len(item.url), 57)]))
elif item.action == "gotopage":
from core import scrapertools
head = config.get_localized_string(70511)
scraped_page = scrapertools.find_single_match(item.url,'[=/]([0-9]+)')
if item.total_pages and (item.page or scraped_page.isdigit()):
pages = [str(p) for p in range(1, item.total_pages + 1)]
page = item.page if item.page else int(scraped_page)
page = platformtools.dialog_select(head, pages, page - 2) + 1
else:
page = platformtools.dialog_numeric(0, head)
if page and int(page) > -1:
import xbmc
item.action = item.real_action
item.page = int(page)
import re
item.url = re.sub('([=/])[0-9]+(/?)$', '\g<1>{}\g<2>'.format(page), item.url)
xbmc.executebuiltin("Container.Update(%s?%s)" % (sys.argv[0], item.tourl()))
elif item.action == "gotoseason":
head = 'Seleziona la stagione'
seasons = [str(s) for s in item.allSeasons]
season = platformtools.dialog_select(head, seasons, item.nextSeason - 1)
if int(season) > -1:
import xbmc
item.action = item.real_action
item.nextSeason = season
xbmc.executebuiltin("Container.Update(%s?%s)" % (sys.argv[0], item.tourl()))
else:
channel = platformtools.channel_import(item.channel)
if not channel:
return
logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__))
# Special play action
if item.action == "play":
# define la info para trakt
try:
from core import trakt_tools
trakt_tools.set_trakt_info(item)
except:
pass
logger.debug("item.action=%s" % item.action.upper())
# logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))
# First checks if channel has a "play" function
if hasattr(channel, 'play'):
logger.debug("Executing channel 'play' method")
itemlist = channel.play(item)
b_favourite = item.isFavourite
# Play should return a list of playable URLS
if len(itemlist) > 0 and isinstance(itemlist[0], Item):
item = itemlist[0]
if b_favourite:
item.isFavourite = True
platformtools.play_video(item)
# Permitir varias calidades desde play en el Channel
elif len(itemlist) > 0 and isinstance(itemlist[0], list):
item.video_urls = itemlist
platformtools.play_video(item)
# If not, shows user an error message
else:
platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(60339))
# If player don't have a "play" function, not uses the standard play from platformtools
else:
logger.debug("Executing core 'play' method")
platformtools.play_video(item)
# Special action for findvideos, where the plugin looks for known urls
elif item.action == "findvideos":
# logger.dbg()
from core import servertools
p_dialog = None
if item.window:
p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(60683))
p_dialog.update(0)
# First checks if channel has a "findvideos" function
if hasattr(channel, 'findvideos'):
itemlist = getattr(channel, item.action)(item)
# If not, uses the generic findvideos function
else:
logger.debug("No channel 'findvideos' method, " "executing core method")
itemlist = servertools.find_video_items(item)
if config.get_setting("max_links", "videolibrary") != 0:
itemlist = limit_itemlist(itemlist)
if p_dialog:
p_dialog.update(100)
p_dialog.close()
platformtools.serverwindow(item, itemlist)
else:
platformtools.render_items(itemlist, item)
# Special action for adding a movie to the library
elif item.action == "add_movie_to_library":
from core import videolibrarytools
videolibrarytools.add_movie(item)
# Special action for adding a serie to the library
elif item.action == "add_serie_to_library":
from core import videolibrarytools
videolibrarytools.add_tvshow(item, channel)
# Special action for adding a serie to the library
elif item.action == "add_to_library":
from core import videolibrarytools
videolibrarytools.add_to_videolibrary(item, channel)
# Special action for downloading all episodes from a serie
elif item.action == "download_all_episodes":
from specials import downloads
item.action = item.extra
del item.extra
downloads.save_download(item)
# Special action for searching, first asks for the words then call the "search" function
elif item.action == "search":
if filetools.isfile(temp_search_file) and config.get_setting('videolibrary_kodi'):
itemlist = []
f = filetools.read(temp_search_file)
strList = f.split(',')
if strList[0] == '[V]' and strList[1] == item.channel:
for it in strList:
if it and it not in ['[V]', item.channel]:
itemlist.append(Item().fromurl(it))
filetools.write(temp_search_file, f[4:])
return platformtools.render_items(itemlist, item)
else:
filetools.remove(temp_search_file)
logger.debug("item.action=%s" % item.action.upper())
from core import channeltools
if config.get_setting('last_search'):
last_search = channeltools.get_channel_setting('Last_searched', 'search', '')
else:
last_search = ''
search_text = platformtools.dialog_input(last_search)
if search_text is not None:
channeltools.set_channel_setting('Last_searched', search_text, 'search')
itemlist = new_search(item.clone(text=search_text), channel)
else:
return
platformtools.render_items(itemlist, item)
# For all other actions
else:
# import web_pdb; web_pdb.set_trace()
logger.debug("Executing channel '%s' method" % item.action)
itemlist = getattr(channel, item.action)(item)
if config.get_setting('trakt_sync'):
from core import trakt_tools
token_auth = config.get_setting("token_trakt", "trakt")
if not token_auth:
trakt_tools.auth_trakt()
else:
import xbmc
if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.get_setting('install_trakt'):
trakt_tools.ask_install_script()
itemlist = trakt_tools.trakt_check(itemlist)
else:
config.set_setting('install_trakt', True)
platformtools.render_items(itemlist, item)
except WebErrorException as e:
@@ -336,27 +91,28 @@ def run(item=None):
logger.error(traceback.format_exc())
platformtools.dialog_ok(
config.get_localized_string(59985) % e.channel,
config.get_localized_string(60013) % e.url)
platformtools.dialogOk(
config.getLocalizedString(59985) % e.channel,
config.getLocalizedString(60013) % e.url)
except Exception as e:
import traceback
from core import scrapertools
logger.error(traceback.format_exc())
patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + r'([^.]+)\.py"'
patron = r'File "{}([^.]+)\.py"'.format(filetools.join(config.getRuntimePath(), 'channels', '').replace('\\', '\\\\'))
Channel = scrapertools.find_single_match(traceback.format_exc(), patron)
if Channel or e.__class__ == logger.ChannelScraperException:
if item.url:
if platformtools.dialog_yesno(config.get_localized_string(60087) % Channel, config.get_localized_string(60014), nolabel='ok', yeslabel=config.get_localized_string(70739)):
run(Item(action="open_browser", url=item.url))
if platformtools.dialogYesNo(config.getLocalizedString(60087) % Channel, config.getLocalizedString(60014), nolabel='ok', yeslabel=config.getLocalizedString(70739)):
run(Item(action='open_browser', url=item.url))
else:
platformtools.dialog_ok(config.get_localized_string(60087) % Channel, config.get_localized_string(60014))
platformtools.dialogOk(config.getLocalizedString(60087) % Channel, config.getLocalizedString(60014))
else:
if platformtools.dialog_yesno(config.get_localized_string(60038), config.get_localized_string(60015)):
platformtools.itemlist_update(Item(channel="setting", action="report_menu"), True)
if platformtools.dialogYesNo(config.getLocalizedString(60038), config.getLocalizedString(60015)):
platformtools.itemlistUpdate(Item(channel='setting', action='report_menu'), True)
finally:
# db need to be closed when not used, it will cause freezes
from core import db
@@ -374,112 +130,185 @@ def new_search(item, channel=None):
writelist = item.channel
for it in itemlist:
writelist += ',' + it.tourl()
filetools.write(temp_search_file, writelist)
# filetools.write(temp_search_file, writelist)
return itemlist
def set_search_temp(item):
if filetools.isfile(temp_search_file) and config.get_setting('videolibrary_kodi'):
f = '[V],' + filetools.read(temp_search_file)
filetools.write(temp_search_file, f)
# def set_search_temp(item):
# if filetools.isfile(temp_search_file) and config.getSetting('videolibrary_kodi'):
# f = '[V],' + filetools.read(temp_search_file)
# filetools.write(temp_search_file, f)
def reorder_itemlist(itemlist):
def limitItemlist(itemlist):
logger.debug()
# logger.debug("Inlet itemlist size: %i" % len(itemlist))
new_list = []
mod_list = []
not_mod_list = []
modified = 0
not_modified = 0
to_change = [[config.get_localized_string(60335), '[V]'], [config.get_localized_string(60336), '[D]']]
for item in itemlist:
if not PY3:
old_title = unicode(item.title, "utf8").lower().encode("utf8")
else:
old_title = item.title.lower()
for before, after in to_change:
if before in item.title:
item.title = item.title.replace(before, after)
break
if not PY3:
new_title = unicode(item.title, "utf8").lower().encode("utf8")
else:
new_title = item.title.lower()
if old_title != new_title:
mod_list.append(item)
modified += 1
else:
not_mod_list.append(item)
not_modified += 1
# logger.debug("OLD: %s | NEW: %s" % (old_title, new_title))
new_list.extend(mod_list)
new_list.extend(not_mod_list)
logger.debug("Modified Titles:%i |Unmodified:%i" % (modified, not_modified))
if len(new_list) == 0:
new_list = itemlist
# logger.debug("Outlet itemlist size: %i" % len(new_list))
return new_list
def limit_itemlist(itemlist):
logger.debug()
# logger.debug("Inlet itemlist size: %i" % len(itemlist))
try:
opt = config.get_setting("max_links", "videolibrary")
if opt == 0:
value = config.getSetting('max_links', 'videolibrary')
if value == 0:
new_list = itemlist
else:
i_max = 30 * opt
new_list = itemlist[:i_max]
# logger.debug("Outlet itemlist size: %i" % len(new_list))
new_list = itemlist[:value]
return new_list
except:
return itemlist
def play_from_library(item):
"""
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: item with information
"""
import xbmc, xbmcgui, xbmcplugin
platformtools.window_type(item)
platformtools.prevent_busy(item)
item.action = item.next_action if item.next_action else 'findvideos'
if not item.videolibrary_id:
if item.window and item.action == 'findvideos':
return run(item)
else:
xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")")
elif xbmc.getCondVisibility('Window.IsMedia') and not item.window:
if item.contentType == 'episode':
it = videolibrarydb[item.contentType][item.videolibrary_id]['{}x{:02d}'.format(item.infoLabels['season'], item.infoLabels['episode'])]['item']
else:
it = videolibrarydb[item.contentType][item.videolibrary_id]['item']
it.from_library = True
xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + it.tourl() + ")")
videolibrarydb.close()
def makeItem():
logger.debug()
if sys.argv[2]:
sp = sys.argv[2].split('&')
url = sp[0]
item = Item().fromurl(url)
if len(sp) > 1:
for e in sp[1:]:
key, val = e.split('=')
if val.lower() == 'false': val = False
elif val.lower() == 'true': val = True
item.__setattr__(key, val)
# If no item, this is mainlist
else:
item.window = True
return run(item)
item = Item(channel='channelselector', action='getmainlist', viewmode='movie')
return item
def showOnce():
if not config.getAllSettingsAddon():
logger.error('corrupted settings.xml!!')
settings_xml = filetools.join(config.getDataPath(), 'settings.xml')
settings_bak = filetools.join(config.getDataPath(), 'settings.bak')
if filetools.exists(settings_bak):
filetools.copy(settings_bak, settings_xml, True)
logger.info('restored settings.xml from backup')
else:
filetools.write(settings_xml, '<settings version="2">\n</settings>') # resetted settings
else:
from platformcode import xbmc_videolibrary
xbmc_videolibrary.ask_set_content(silent=False)
config.setSetting('show_once', True)
def play(item):
channel = importChannel(item)
# platformtools.fakeVideo()
# define la info para trakt
try:
from core import trakt_tools
trakt_tools.set_trakt_info(item)
except:
pass
logger.debug('item.action=', item.action.upper())
# First checks if channel has a "play" function
if hasattr(channel, 'play'):
logger.debug('Executing channel "play" method')
itemlist = channel.play(item)
# Play should return a list of playable URLS
if len(itemlist) > 0 and isinstance(itemlist[0], Item):
item = itemlist[0]
platformtools.playVideo(item)
# Allow several qualities from Play in El Channel
elif len(itemlist) > 0 and isinstance(itemlist[0], list):
item.videoUrls = itemlist
platformtools.playVideo(item)
# If not, shows user an error message
else:
platformtools.dialogOk(config.getLocalizedString(20000), config.getLocalizedString(60339))
# If player don't have a "play" function, not uses the standard play from platformtools
else:
logger.debug('Executing core "play" method')
platformtools.playVideo(item)
def findvideos(item):
logger.debug('Executing channel', item.channel, 'method', item.action)
channel = importChannel(item)
from core import servertools
p_dialog = platformtools.dialogProgressBg(config.getLocalizedString(20000), config.getLocalizedString(60683))
p_dialog.update(0)
# First checks if channel has a "findvideos" function
if hasattr(channel, 'findvideos'):
itemlist = getattr(channel, item.action)(item)
# If not, uses the generic findvideos function
else:
logger.debug('No channel "findvideos" method, executing core method')
itemlist = servertools.find_video_items(item)
itemlist = limitItemlist(itemlist)
p_dialog.update(100)
p_dialog.close()
# If there is only one server play it immediately
if len(itemlist) == 1 or len(itemlist) > 1 and not itemlist[1].server:
play(itemlist[0].clone(no_return=True))
else:
platformtools.serverWindow(item, itemlist)
def search(item):
channel = importChannel(item)
from core import channeltools
if config.getSetting('last_search'):
last_search = channeltools.getChannelSetting('Last_searched', 'search', '')
else:
last_search = ''
search_text = platformtools.dialogInput(last_search)
if search_text is not None:
channeltools.setChannelSetting('Last_searched', search_text, 'search')
itemlist = new_search(item.clone(text=search_text), channel)
else:
return
platformtools.renderItems(itemlist, item)
def addToLibrary(item):
channel = importChannel(item)
from core import videolibrarytools
videolibrarytools.add_to_videolibrary(item, channel)
def importChannel(item):
channel = platformtools.channelImport(item.channel)
if not channel:
logger.debug('Channel', item.channel, 'not exist!')
return
logger.debug('Running channel', channel.__name__, '|', channel.__file__)
return channel
def actions(item):
logger.debug('Executing channel', item.channel, 'method', item.action)
channel = importChannel(item)
itemlist = getattr(channel, item.action)(item)
if config.getSetting('trakt_sync'):
from core import trakt_tools
token_auth = config.getSetting('token_trakt', 'trakt')
if not token_auth:
trakt_tools.auth_trakt()
else:
import xbmc
if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.getSetting('install_trakt'):
trakt_tools.ask_install_script()
itemlist = trakt_tools.trakt_check(itemlist)
else:
config.setSetting('install_trakt', True)
platformtools.renderItems(itemlist, item)
def playFromLibrary(item):
platformtools.fakeVideo()
item.action = item.next_action if item.next_action else 'findvideos'
logger.debug('Executing channel', item.channel, 'method', item.action)
return run(item)

View File

@@ -16,7 +16,7 @@ try:
except:
testMode = False
LOG_FORMAT = '{addname}[{filename}.{function}:{line}]{sep} {message}'
DEBUG_ENABLED = config.get_setting("debug")
DEBUG_ENABLED = config.getSetting("debug")
DEF_LEVEL = xbmc.LOGINFO if sys.version_info[0] >= 3 else xbmc.LOGNOTICE
@@ -52,7 +52,7 @@ def log(*args, **kwargs):
message=msg), kwargs.get('level', DEF_LEVEL))
def dbg(open=True):
if config.dev_mode():
if config.devMode():
try:
import web_pdb
if not web_pdb.WebPdb.active_instance and open:

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ class Recaptcha(xbmcgui.WindowXMLDialog):
self.doModal()
# Reload
if self.result == {}:
self.result = Recaptcha("Recaptcha.xml", config.get_runtime_path()).Start(self.key, self.referer)
self.result = Recaptcha("Recaptcha.xml", config.getRuntimePath()).Start(self.key, self.referer)
return self.result
@@ -43,7 +43,7 @@ class Recaptcha(xbmcgui.WindowXMLDialog):
def onInit(self):
#### Kodi 18 compatibility ####
if config.get_platform(True)['num_version'] < 18:
if config.getXBMCPlatform(True)['num_version'] < 18:
self.setCoordinateResolution(2)
self.update_window()
@@ -68,7 +68,7 @@ class Recaptcha(xbmcgui.WindowXMLDialog):
logger.debug(data)
self.result = scrapertools.find_single_match(data, '<div class="fbc-verification-token">.*?>([^<]+)<')
if self.result:
platformtools.dialog_notification("Captcha corretto", "Verifica conclusa")
platformtools.dialogNotification("Captcha corretto", "Verifica conclusa")
self.close()
else:
self.result = {}

View File

@@ -1,150 +1,197 @@
# -*- coding: utf-8 -*-
from platformcode import logger, platformtools
import sys
from platformcode import logger, platformtools, config
def context():
from platformcode import config
context = []
# original
# if config.get_setting('quick_menu'): context.append((config.get_localized_string(60360).upper(), "RunPlugin(plugin://plugin.video.kod/?%s)" % Item(channel='shortcuts', action="shortcut_menu").tourl()))
# if config.get_setting('kod_menu'): context.append((config.get_localized_string(60026), "RunPlugin(plugin://plugin.video.kod/?%s)" % Item(channel='shortcuts', action="settings_menu").tourl()))
from platformcode import config
context = []
# original
# if config.getSetting('quick_menu'): context.append((config.getLocalizedString(60360).upper(), "RunPlugin(plugin://plugin.video.kod/?%s)" % Item(channel='shortcuts', action="shortcut_menu").tourl()))
# if config.getSetting('kod_menu'): context.append((config.getLocalizedString(60026), "RunPlugin(plugin://plugin.video.kod/?%s)" % Item(channel='shortcuts', action="settings_menu").tourl()))
# pre-serialised
if config.get_setting('quick_menu'): context.append((config.get_localized_string(60360), 'RunPlugin(plugin://plugin.video.kod/?ewogICAgImFjdGlvbiI6ICJzaG9ydGN1dF9tZW51IiwgCiAgICAiY2hhbm5lbCI6ICJzaG9ydGN1dHMiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D)'))
# if config.get_setting('kod_menu'): context.append((config.get_localized_string(60026), 'RunPlugin(plugin://plugin.video.kod/?ewogICAgImFjdGlvbiI6ICJzZXR0aW5nc19tZW51IiwgCiAgICAiY2hhbm5lbCI6ICJzaG9ydGN1dHMiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D)'))
# pre-serialised
if config.getSetting('quick_menu'): context.append((config.getLocalizedString(60360), 'RunPlugin(plugin://plugin.video.kod/?channel=shortcuts&action=shortcut_menu)'))
# if config.getSetting('kod_menu'): context.append((config.getLocalizedString(60026), 'RunPlugin(plugin://plugin.video.kod/?ewogICAgImFjdGlvbiI6ICJzZXR0aW5nc19tZW51IiwgCiAgICAiY2hhbm5lbCI6ICJzaG9ydGN1dHMiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D)'))
return context
def open_browser(item):
import webbrowser
if not webbrowser.open(item.url):
import xbmc
if xbmc.getCondVisibility('system.platform.linux') and xbmc.getCondVisibility('system.platform.android'): # android
xbmc.executebuiltin('StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % item.url)
else:
platformtools.dialogOk(config.getLocalizedString(20000), config.getLocalizedString(70740) % "\n".join([item.url[j:j+57] for j in range(0, len(item.url), 57)]))
def gotopage(item):
item.channel = item.from_cannel
from core import scrapertools
head = config.getLocalizedString(70511)
scraped_page = scrapertools.find_single_match(item.url,'[=/]([0-9]+)')
if item.total_pages and (item.page or scraped_page.isdigit()):
pages = [str(p) for p in range(1, item.total_pages + 1)]
page = item.page if item.page else int(scraped_page)
page = platformtools.dialogSelect(head, pages, page - 2) + 1
else:
page = platformtools.dialogNumeric(0, head)
if page and int(page) > -1:
import xbmc
item.action = item.real_action
item.page = int(page)
item.update = True
import re
item.url = re.sub('([=/])[0-9]+(/?)$', '\g<1>{}\g<2>'.format(page), item.url)
xbmc.executebuiltin("Container.Update(%s?%s)" % (sys.argv[0], item.tourl()))
def gotoseason(item):
item.channel = item.from_cannel
head = 'Seleziona la stagione'
seasons = [str(s) for s in item.allSeasons]
season = platformtools.dialogSelect(head, seasons, item.nextSeason - 1)
if int(season) > -1:
import xbmc
item.action = item.real_action
item.nextSeason = season
item.update = True
xbmc.executebuiltin("Container.Update(%s?%s)" % (sys.argv[0], item.tourl()))
return context
def shortcut_menu(item):
from platformcode import keymaptools
keymaptools.open_shortcut_menu()
from platformcode import keymaptools
if item.add:
keymaptools.set_key()
elif item.delete:
keymaptools.delete_key()
else:
keymaptools.open_shortcut_menu()
def settings_menu(item):
from platformcode import config
config.open_settings()
from platformcode import config
config.openSettings()
def servers_menu(item):
from core import servertools
from core.item import Item
from platformcode import config, platformtools
from specials import setting
from core import servertools
from core.item import Item
from platformcode import config, platformtools
from specials import setting
names = []
ids = []
names = []
ids = []
if item.type == 'debriders':
action = 'server_debrid_config'
server_list = list(servertools.get_debriders_list().keys())
for server in server_list:
server_parameters = servertools.get_server_parameters(server)
if server_parameters['has_settings'] and server_parameters['active']:
names.append(server_parameters['name'])
ids.append(server)
if item.type == 'debriders':
action = 'server_debrid_config'
server_list = list(servertools.get_debriders_list().keys())
for server in server_list:
server_parameters = servertools.get_server_parameters(server)
if server_parameters['has_settings'] and server_parameters['active']:
names.append(server_parameters['name'])
ids.append(server)
select = platformtools.dialog_select(config.get_localized_string(60552), names)
if select != -1:
ID = ids[select]
select = platformtools.dialogSelect(config.getLocalizedString(60552), names)
if select != -1:
ID = ids[select]
it = Item(channel = 'settings',
action = action,
config = ID)
setting.server_debrid_config(it)
else:
action = 'server_config'
server_list = list(servertools.get_servers_list().keys())
for server in sorted(server_list):
server_parameters = servertools.get_server_parameters(server)
if server_parameters["has_settings"] and [x for x in server_parameters["settings"]] and server_parameters['active']:
names.append(server_parameters['name'])
ids.append(server)
it = Item(channel = 'settings',
action = action,
config = ID)
setting.server_debrid_config(it)
else:
action = 'server_config'
server_list = list(servertools.get_servers_list().keys())
for server in sorted(server_list):
server_parameters = servertools.get_server_parameters(server)
if server_parameters["has_settings"] and [x for x in server_parameters["settings"]] and server_parameters['active']:
names.append(server_parameters['name'])
ids.append(server)
select = platformtools.dialog_select(config.get_localized_string(60538), names)
if select != -1:
ID = ids[select]
select = platformtools.dialogSelect(config.getLocalizedString(60538), names)
if select != -1:
ID = ids[select]
it = Item(channel = 'settings',
action = action,
config = ID)
it = Item(channel = 'settings',
action = action,
config = ID)
setting.server_config(it)
if select != -1:
servers_menu(item)
setting.server_config(it)
if select != -1:
servers_menu(item)
def channels_menu(item):
import channelselector
from core import channeltools
from core.item import Item
from platformcode import config, platformtools
from specials import setting
import channelselector
from core import channeltools
from core.item import Item
from platformcode import config, platformtools
from specials import setting
names = []
ids = []
names = []
ids = []
channel_list = channelselector.filterchannels("all")
for channel in channel_list:
if not channel.channel:
continue
channel_parameters = channeltools.get_channel_parameters(channel.channel)
if channel_parameters["has_settings"]:
names.append(channel.title)
ids.append(channel.channel)
channel_list = channelselector.filterchannels("all")
for channel in channel_list:
if not channel.channel:
continue
channel_parameters = channeltools.get_channel_parameters(channel.channel)
if channel_parameters["has_settings"]:
names.append(channel.title)
ids.append(channel.channel)
select = platformtools.dialog_select(config.get_localized_string(60537), names)
if select != -1:
ID = ids[select]
select = platformtools.dialogSelect(config.getLocalizedString(60537), names)
if select != -1:
ID = ids[select]
it = Item(channel='settings',
action="channel_config",
config=ID)
it = Item(channel='settings',
action="channel_config",
config=ID)
setting.channel_config(it)
return channels_menu(item)
setting.channel_config(it)
return channels_menu(item)
def check_channels(item):
from specials import setting
from platformcode import config, platformtools
item.channel = 'setting'
item.extra = 'lib_check_datajson'
itemlist = setting.conf_tools(item)
text = ''
for item in itemlist:
text += item.title + '\n'
platformtools.dialog_textviewer(config.get_localized_string(60537), text)
from specials import setting
from platformcode import config, platformtools
item.channel = 'setting'
item.extra = 'lib_check_datajson'
itemlist = setting.conf_tools(item)
text = ''
for item in itemlist:
text += item.title + '\n'
platformtools.dialogTextviewer(config.getLocalizedString(60537), text)
def SettingOnPosition(item):
# addonId is the Addon ID
# item.category is the Category (Tab) offset (0=first, 1=second, 2...etc)
# item.setting is the Setting (Control) offse (0=first, 1=second, 2...etc)
# This will open settings dialog focusing on fourth setting (control) inside the third category (tab)
# addonId is the Addon ID
# item.category is the Category (Tab) offset (0=first, 1=second, 2...etc)
# item.setting is the Setting (Control) offse (0=first, 1=second, 2...etc)
# This will open settings dialog focusing on fourth setting (control) inside the third category (tab)
import xbmc
from platformcode import config
config.open_settings()
category = item.category if item.category else 0
setting = item.setting if item.setting else 0
logger.debug('SETTING= ' + str(setting))
xbmc.executebuiltin('SetFocus(%i)' % (category - 100))
xbmc.executebuiltin('SetFocus(%i)' % (setting - 80))
import xbmc
from platformcode import config
config.openSettings()
category = item.category if item.category else 0
setting = item.setting if item.setting else 0
logger.debug('SETTING= ' + str(setting))
xbmc.executebuiltin('SetFocus(%i)' % (category - 100))
xbmc.executebuiltin('SetFocus(%i)' % (setting - 80))
def select(item):
from platformcode import config, platformtools
# item.id = setting ID
# item.type = labels or values
# item.values = values separeted by |
# item.label = string or string id
from platformcode import config, platformtools
# item.id = setting ID
# item.type = labels or values
# item.values = values separeted by |
# item.label = string or string id
label = config.get_localized_string(int(item.label)) if item.label.isdigit() else item.label
values = []
label = config.getLocalizedString(int(item.label)) if item.label.isdigit() else item.label
values = []
if item.type == 'labels':
for val in item.values.split('|'):
values.append(config.get_localized_string(int(val)))
else:
values = item.values.split('|')
ID = config.get_setting(item.id) if config.get_setting(item.id) else 0
select = platformtools.dialog_select(label, values, ID)
if item.type == 'labels':
for val in item.values.split('|'):
values.append(config.getLocalizedString(int(val)))
else:
values = item.values.split('|')
ID = config.getSetting(item.id) if config.getSetting(item.id) else 0
select = platformtools.dialogSelect(label, values, ID)
config.set_setting(item.id, values[select])
config.setSetting(item.id, values[select])

View File

@@ -224,8 +224,8 @@ def set_color(title, category):
# logger.info()
from core import jsontools
styles_path = os.path.join(config.get_runtime_path(), 'resources', 'color_styles.json')
preset = config.get_setting("preset_style", default="Estilo 1")
styles_path = os.path.join(config.getRuntimePath(), 'resources', 'color_styles.json')
preset = config.getSetting("preset_style", default="Estilo 1")
color_setting = jsontools.load((open(styles_path, "r").read()))[preset]
color_scheme = {'otro': 'white', 'dual': 'white'}
@@ -238,14 +238,14 @@ def set_color(title, category):
'vos', 'vo', 'server', 'library', 'update', 'no_update']
# Check the status of the custom colors options
custom_colors = config.get_setting('title_color')
custom_colors = config.getSetting('title_color')
# 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:
if custom_colors:
color_scheme[element] = remove_format(config.get_setting('%s_color' % element))
color_scheme[element] = remove_format(config.getSetting('%s_color' % element))
else:
color_scheme[element] = remove_format(color_setting.get(element, 'white'))
# color_scheme[element] = 'white'
@@ -570,7 +570,7 @@ def thumbnail_type(item):
# logger.info()
# Check what type of thumbnail will be used in findvideos, Poster or Logo of the server
thumb_type = config.get_setting('video_thumbnail_type')
thumb_type = config.getSetting('video_thumbnail_type')
info = item.infoLabels
if not item.contentThumbnail:
item.contentThumbnail = item.thumbnail

View File

@@ -42,7 +42,7 @@ def loadCommits(page=1):
except:
xbmc.sleep(1000)
else:
platformtools.dialog_notification(addonname, config.get_localized_string(70675))
platformtools.dialogNotification(addonname, config.getLocalizedString(70675))
ret = None
return ret
@@ -158,7 +158,7 @@ def check(background=False):
if addon.getSetting("addon_update_message"):
if background:
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80040) % commits[0]['sha'][:7], time=3000, sound=False)
platformtools.dialogNotification(config.getLocalizedString(20000), config.getLocalizedString(80040) % commits[0]['sha'][:7], time=3000, sound=False)
try:
with open(config.changelogFile, 'a+') as fileC:
fileC.write(changelog)
@@ -166,7 +166,7 @@ def check(background=False):
import traceback
logger.error(traceback.format_exc())
elif changelog:
platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80041) + changelog)
platformtools.dialogOk(config.getLocalizedString(20000), config.getLocalizedString(80041) + changelog)
else:
logger.info('Nessun nuovo aggiornamento')
@@ -221,8 +221,8 @@ def getShaStr(str):
def updateFromZip(message=config.get_localized_string(80050)):
dp = platformtools.dialog_progress_bg(config.get_localized_string(20000), message)
def updateFromZip(message=config.getLocalizedString(80050)):
dp = platformtools.dialogProgressBg(config.getLocalizedString(20000), message)
dp.update(0)
remotefilename = 'https://github.com/' + user + "/" + repo + "/archive/" + branch + ".zip"
@@ -242,7 +242,7 @@ def updateFromZip(message=config.get_localized_string(80050)):
urllib.urlretrieve(remotefilename, localfilename,
lambda nb, bs, fs, url=remotefilename: _pbhook(nb, bs, fs, url, dp))
except Exception as e:
platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80031))
platformtools.dialogOk(config.getLocalizedString(20000), config.getLocalizedString(80031))
logger.info('Non sono riuscito a scaricare il file zip')
logger.info(e)
dp.close()
@@ -255,7 +255,7 @@ def updateFromZip(message=config.get_localized_string(80050)):
if os.path.isfile(localfilename):
logger.info('il file esiste')
dp.update(80, config.get_localized_string(20000) + '\n' + config.get_localized_string(80032))
dp.update(80, config.getLocalizedString(20000) + '\n' + config.getLocalizedString(80032))
import zipfile
try:
@@ -297,7 +297,7 @@ def updateFromZip(message=config.get_localized_string(80050)):
dp.update(100)
xbmc.sleep(1000)
dp.close()
if message != config.get_localized_string(80050):
if message != config.getLocalizedString(80050):
xbmc.executebuiltin("UpdateLocalAddons")
refreshLang()
@@ -306,7 +306,7 @@ def updateFromZip(message=config.get_localized_string(80050)):
def refreshLang():
from platformcode import config
language = config.get_localized_string(20001)
language = config.getLocalizedString(20001)
if language == 'eng':
xbmc.executebuiltin("SetGUILanguage(resource.language.it_it)")
xbmc.executebuiltin("SetGUILanguage(resource.language.en_en)")

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,7 @@ BACKSPACE = 92
def imagepath(image):
if len(image.split('.')) == 1: image += '.png'
path = filetools.join(config.get_runtime_path(), 'resources', 'skins' , 'Default', 'media', 'Infoplus', image)
path = filetools.join(config.getRuntimePath(), 'resources', 'skins' , 'Default', 'media', 'Infoplus', image)
return path
class InfoWindow(xbmcgui.WindowXMLDialog):
@@ -48,7 +48,7 @@ class InfoWindow(xbmcgui.WindowXMLDialog):
return it
def onInit(self):
if config.get_platform(True)['num_version'] < 18:
if config.getXBMCPlatform(True)['num_version'] < 18:
self.setCoordinateResolution(2)
results = []
with futures.ThreadPoolExecutor() as executor:

View File

@@ -18,15 +18,16 @@ from core import scrapertools
from xml.dom import minidom
def mark_auto_as_watched(item):
def mark_auto_as_watched():
def mark_as_watched_subThread(item):
logger.debug()
# logger.dbg()
actual_time = 0
total_time = 0
time_limit = time.time() + 10
while not platformtools.is_playing() and time.time() < time_limit:
time.sleep(1)
# time_limit = time.time() + 10
# while not platformtools.isPlaying() and time.time() < time_limit:
# time.sleep(1)
marked = False
sync = False
@@ -34,48 +35,46 @@ def mark_auto_as_watched(item):
show_server = True
mark_time = 100
percentage = float(config.get_setting("watched_setting")) / 100
time_from_end = config.get_setting('next_ep_seconds')
percentage = float(config.getSetting("watched_setting")) / 100
time_from_end = config.getSetting('next_ep_seconds')
if item.contentType != 'movie' and 0 < config.get_setting('next_ep') < 3:
if item.contentType != 'movie' and 0 < config.getSetting('next_ep') < 3:
next_dialogs = ['NextDialog.xml', 'NextDialogExtended.xml', 'NextDialogCompact.xml']
next_ep_type = config.get_setting('next_ep_type')
next_ep_type = config.getSetting('next_ep_type')
ND = next_dialogs[next_ep_type]
try: next_episode = next_ep(item)
except: next_episode = False
logger.debug(next_episode)
while not xbmc.Monitor().abortRequested():
if not platformtools.is_playing(): break
if not platformtools.isPlaying(): break
try: actual_time = xbmc.Player().getTime()
except: actual_time = 0
try: total_time = xbmc.Player().getTotalTime()
except: total_time = 0
if item.played_time and xbmcgui.getCurrentWindowId() == 12005:
if actual_time and item.played_time and xbmcgui.getCurrentWindowId() == 12005:
logger.debug('VAI A', item.played_time)
xbmc.Player().seekTime(item.played_time)
item.played_time = 0 # Fix for Slow Devices
item.played_time = 0
mark_time = total_time * percentage
difference = total_time - actual_time
# Mark as Watched
if actual_time > mark_time and not marked:
if actual_time > mark_time and mark_time > 0 and not marked:
logger.info("Marked as Watched")
item.playcount = 1
marked = True
item.played_time = 0
platformtools.set_played_time(item)
platformtools.setPlayedTime(item)
if item.options['strm'] : sync = True
show_server = False
# from specials import videolibrary
# videolibrary.mark_content_as_watched(item)
if not next_episode:
break
# check for next Episode
if next_episode and marked and time_from_end >= difference:
nextdialog = NextDialog(ND, config.get_runtime_path(), item=next_episode)
while platformtools.is_playing() and not nextdialog.is_exit():
nextdialog = NextDialog(ND, config.getRuntimePath(), item=next_episode)
while platformtools.isPlaying() and not nextdialog.is_exit():
xbmc.sleep(100)
if nextdialog.continuewatching:
next_episode.next_ep = True
@@ -83,27 +82,32 @@ def mark_auto_as_watched(item):
nextdialog.close()
break
# if item.options['continue']:
if actual_time < mark_time:
item.played_time = actual_time
else: item.played_time = 0
platformtools.set_played_time(item)
if mark_time:
logger.debug('Set Played Time', item.played_time)
platformtools.setPlayedTime(item)
# Silent sync with Trakt
if sync and config.get_setting("trakt_sync"): sync_trakt_kodi()
if sync and config.getSetting("trakt_sync"): sync_trakt_kodi()
while platformtools.is_playing():
xbmc.sleep(100)
while platformtools.isPlaying():
xbmc.sleep(10)
if not show_server and not item.no_return and not item.window:
xbmc.sleep(700)
xbmc.executebuiltin('Action(ParentDir)')
if not show_server and not item.no_return:
if item.window:
# xbmc.executebuiltin('ActivateWindow({})'.format(filetools.join(config.getRuntimePath(), 'resources', 'skins', 'Default', '720p', 'Servers.xml')))
xbmc.executebuiltin('Action(BackSpace)')
else:
xbmc.sleep(700)
xbmc.executebuiltin('Action(ParentDir)')
if marked:
from specials import videolibrary
videolibrary.mark_content_as_watched(item)
if next_episode and next_episode.next_ep and config.get_setting('next_ep') == 1:
if next_episode and next_episode.next_ep and config.getSetting('next_ep') == 1:
from platformcode.launcher import run
run(next_episode)
@@ -112,8 +116,15 @@ def mark_auto_as_watched(item):
db.close()
# 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()
if config.getSetting("mark_as_watched", "videolibrary"):
from core import db
item = db['playitem'].get('item')
db.close()
imdb_id = xbmc.Player().getVideoInfoTag().getIMDBNumber()
if item.infoLabels['imdb_id'] == imdb_id:
# mark_as_watched_subThread(item)
threading.Thread(target=mark_as_watched_subThread, args=[item]).start()
logger.debug('EXIT MONITOR')
def sync_trakt_addon(path_folder):
@@ -242,14 +253,14 @@ def sync_trakt_kodi(silent=True):
# 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():
if platformtools.isPlaying():
notificacion = False
xbmc.executebuiltin('RunScript(script.trakt,action=sync,silent=%s)' % silent)
logger.debug("Synchronization with Trakt started")
if notificacion:
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60045), sound=False, time=2000)
platformtools.dialogNotification(config.getLocalizedString(20000), config.getLocalizedString(60045), sound=False, time=2000)
def mark_content_as_watched_on_kodi(item, value=1):
@@ -261,7 +272,7 @@ def mark_content_as_watched_on_kodi(item, value=1):
@param value: > 0 for seen, 0 for not seen
"""
logger.debug()
logger.dbg()
# logger.dbg()
if item.contentType == 'movie':
path = '%{}%'.format(item.strm_path.split('\\')[0].split('/')[0] if item.strm_path else item.base_name)
@@ -369,14 +380,14 @@ def mark_content_as_watched_on_kod(path):
logger.debug()
#logger.debug("path: " + path)
FOLDER_MOVIES = config.get_setting("folder_movies")
FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
VIDEOLIBRARY_PATH = config.get_videolibrary_config_path()
FOLDER_MOVIES = config.getSetting("folder_movies")
FOLDER_TVSHOWS = config.getSetting("folder_tvshows")
VIDEOLIBRARY_PATH = config.getVideolibraryConfigPath()
if not VIDEOLIBRARY_PATH:
return
# set_watched_on_kod
# 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"):
# if config.getSetting("db_mode", "videolibrary"):
# return
path2 = ''
@@ -465,14 +476,14 @@ def get_data(payload):
# Required header for XBMC JSON-RPC calls, otherwise you'll get a 415 HTTP response code - Unsupported media type
headers = {'content-type': 'application/json'}
if config.get_setting("db_mode", "videolibrary"):
if config.getSetting("db_mode", "videolibrary"):
try:
try:
xbmc_port = config.get_setting("xbmc_puerto", "videolibrary")
xbmc_port = config.getSetting("xbmc_puerto", "videolibrary")
except:
xbmc_port = 0
xbmc_json_rpc_url = "http://" + config.get_setting("xbmc_host", "videolibrary") + ":" + str(xbmc_port) + "/jsonrpc"
xbmc_json_rpc_url = "http://" + config.getSetting("xbmc_host", "videolibrary") + ":" + str(xbmc_port) + "/jsonrpc"
req = urllib2.Request(xbmc_json_rpc_url, data=jsontools.dump(payload), headers=headers)
f = urllib.urlopen(req)
response = f.read()
@@ -499,7 +510,7 @@ def get_data(payload):
return data
def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
def update(folder_content=config.getSetting("folder_tvshows"), folder=""):
"""
Update the library depending on the type of content and the path passed to it.
@@ -518,7 +529,7 @@ def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
if folder:
folder = str(folder)
videolibrarypath = config.get_videolibrary_config_path()
videolibrarypath = config.getVideolibraryConfigPath()
if folder.endswith('/') or folder.endswith('\\'):
folder = folder[:-1]
@@ -561,17 +572,17 @@ def search_local_path(item):
for record in records:
num_path, path_records = execute_sql_kodi('SELECT strPath FROM path WHERE idPath LIKE "%s"' % record[0])
for path in path_records:
if config.get_setting('videolibrarypath') not in path[0]:
if config.getSetting('videolibrarypath') not in path[0]:
return path[0]
return ''
def set_content(silent=False):
logger.debug()
videolibrarypath = config.get_setting("videolibrarypath")
videolibrarypath = config.getSetting("videolibrarypath")
sep = '/' if '/' in videolibrarypath else '\\'
paths = {'movie': filetools.join(videolibrarypath, config.get_setting('folder_movies')) + sep,
'tvshow': filetools.join(videolibrarypath, config.get_setting('folder_tvshows')) + sep}
paths = {'movie': filetools.join(videolibrarypath, config.getSetting('folder_movies')) + sep,
'tvshow': filetools.join(videolibrarypath, config.getSetting('folder_tvshows')) + sep}
for k, v in paths.items():
sql = 'SELECT idPath, strPath FROM path where strPath= "{}"'.format(v)
n, records = execute_sql_kodi(sql)
@@ -631,7 +642,7 @@ def update_db(old_path, new_path, old_movies_folder, new_movies_folder, old_tvsh
return
p = 80
progress.update(p, config.get_localized_string(20000), config.get_localized_string(80013))
progress.update(p, config.getLocalizedString(20000), config.getLocalizedString(80013))
for OldFolder, NewFolder in [[old_movies_folder, new_movies_folder], [old_tvshows_folder, new_tvshows_folder]]:
sql_old_folder = sql_old_path + OldFolder
@@ -694,7 +705,7 @@ def update_db(old_path, new_path, old_movies_folder, new_movies_folder, old_tvsh
logger.debug('sql: ' + sql)
nun_records, records = execute_sql_kodi(sql)
p += 5
progress.update(p, config.get_localized_string(20000), config.get_localized_string(80013))
progress.update(p, config.getLocalizedString(20000), config.getLocalizedString(80013))
progress.update(100)
xbmc.sleep(1000)
@@ -718,14 +729,14 @@ def clean(path_list=[]):
logger.debug()
progress = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80025))
progress = platformtools.dialogProgressBg(config.getLocalizedString(20000), config.getLocalizedString(80025))
progress.update(0)
# if the path list is empty, clean the entire video library
if not path_list:
logger.debug('the path list is empty, clean the entire video library')
if not config.get_setting("videolibrary_kodi"):
sql_path, sep = sql_format(config.get_setting("videolibrarypath"))
if not config.getSetting("videolibrary_kodi"):
sql_path, sep = sql_format(config.getSetting("videolibrarypath"))
if not sql_path.endswith(sep): sql_path += sep
sql = 'SELECT idPath FROM path where strPath LIKE "%s"' % sql_path
logger.debug('sql: ' + sql)
@@ -742,13 +753,13 @@ def clean(path_list=[]):
from core import videolibrarytools
for path, folders, files in filetools.walk(videolibrarytools.MOVIES_PATH):
for folder in folders:
path_list.append(filetools.join(config.get_setting("videolibrarypath"), videolibrarytools.FOLDER_MOVIES, folder))
path_list.append(filetools.join(config.getSetting("videolibrarypath"), videolibrarytools.FOLDER_MOVIES, folder))
for path, folders, files in filetools.walk(videolibrarytools.TVSHOWS_PATH):
for folder in folders:
tvshow_nfo = filetools.join(path, folder, "tvshow.nfo")
if filetools.exists(tvshow_nfo):
path_list.append(filetools.join(config.get_setting("videolibrarypath"), videolibrarytools.FOLDER_TVSHOWS, folder))
path_list.append(filetools.join(config.getSetting("videolibrarypath"), videolibrarytools.FOLDER_TVSHOWS, folder))
logger.debug('path_list: ' + str(path_list))
if path_list: t = float(100) / len(path_list)
@@ -781,7 +792,7 @@ def clean(path_list=[]):
if records:
payload = {"jsonrpc": "2.0", "method": "VideoLibrary.RemoveTVShow", "id": 1, "params": {"tvshowid": records[0][0]}}
data = get_data(payload)
elif config.get_setting("folder_movies") in sql_path:
elif config.getSetting("folder_movies") in sql_path:
# search movie in the DB
sql = 'SELECT idMovie FROM movie where c22 LIKE "%s"' % sql_path
logger.debug('sql: ' + sql)
@@ -866,7 +877,7 @@ def get_file_db():
"""
file_db = ''
# We look for the archive of the video database according to the version of kodi
video_db = config.get_platform(True)['video_db']
video_db = config.getXBMCPlatform(True)['video_db']
if video_db:
file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)
@@ -1067,71 +1078,71 @@ def update_sources(new='', old=''):
def ask_set_content(silent=False):
logger.debug()
logger.debug("videolibrary_kodi %s" % config.get_setting("videolibrary_kodi"))
logger.debug("videolibrary_kodi %s" % config.getSetting("videolibrary_kodi"))
def do_config(custom=False):
if set_content("movie", True, custom) and set_content("tvshow", True, custom):
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(70104))
config.set_setting("videolibrary_kodi", True)
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(70104))
config.setSetting("videolibrary_kodi", True)
from specials import videolibrary
videolibrary.update_videolibrary()
update()
else:
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(80024))
config.set_setting("videolibrary_kodi", False)
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(80024))
config.setSetting("videolibrary_kodi", False)
# configuration during installation
if not silent:
# ask to configure Kodi video library
if platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(80015)):
if platformtools.dialogYesNo(config.getLocalizedString(20000), config.getLocalizedString(80015)):
# ask for custom or default settings
if not platformtools.dialog_yesno(config.get_localized_string(80026), config.get_localized_string(80016), config.get_localized_string(80017), config.get_localized_string(80018)):
if not platformtools.dialogYesNo(config.getLocalizedString(80026), config.getLocalizedString(80016), config.getLocalizedString(80017), config.getLocalizedString(80018)):
# input path and folders
path = platformtools.dialog_browse(3, config.get_localized_string(80019), config.get_setting("videolibrarypath"))
movies_folder = platformtools.dialog_input(config.get_setting("folder_movies"), config.get_localized_string(80020))
tvshows_folder = platformtools.dialog_input(config.get_setting("folder_tvshows"), config.get_localized_string(80021))
path = platformtools.dialogBrowse(3, config.getLocalizedString(80019), config.getSetting("videolibrarypath"))
movies_folder = platformtools.dialogInput(config.getSetting("folder_movies"), config.getLocalizedString(80020))
tvshows_folder = platformtools.dialogInput(config.getSetting("folder_tvshows"), config.getLocalizedString(80021))
if path != "" and movies_folder != "" and tvshows_folder != "":
movies_path, tvshows_path = check_sources(filetools.join(path, movies_folder), filetools.join(path, tvshows_folder))
# configure later
if movies_path or tvshows_path:
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(80029))
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(80029))
# set path and folders
else:
update_sources(path, config.get_setting("videolibrarypath"))
config.set_setting("videolibrarypath", path)
config.set_setting("folder_movies", movies_folder)
config.set_setting("folder_tvshows", tvshows_folder)
config.verify_directories_created()
update_sources(path, config.getSetting("videolibrarypath"))
config.setSetting("videolibrarypath", path)
config.setSetting("folder_movies", movies_folder)
config.setSetting("folder_tvshows", tvshows_folder)
config.verifyDirectoriesCreated()
do_config(False)
# default path and folders
else:
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(80030))
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(80030))
do_config(False)
# default settings
else:
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(80027))
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(80027))
do_config(False)
# configure later
else:
platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80022))
platformtools.dialogOk(config.getLocalizedString(20000), config.getLocalizedString(80022))
# configuration from the settings menu
else:
platformtools.dialog_ok(config.get_localized_string(80026), config.get_localized_string(80023))
platformtools.dialogOk(config.getLocalizedString(80026), config.getLocalizedString(80023))
do_config(False)
def next_ep(item):
logger.debug(item)
episode = '{}x{:02d}'.format(item.contentSeason, item.contentEpisodeNumber)
episodes = sorted(videolibrarydb.videolibrarydb['episode'][item.videolibrary_id].items())
videolibrarydb.videolibrarydb.close()
episodes = sorted(videolibrarydb['episode'][item.videolibrary_id].items())
videolibrarydb.close()
nextIndex = [k for k, v in episodes].index(episode) + 1
if nextIndex == 0 or nextIndex == len(episodes):
it = None
else:
it = episodes[nextIndex][1]['item']
if item.from_library: it.action = 'play_from_library'
if item.from_library: it.action = 'playFromLibrary'
logger.debug('Next File:' + '{}x{:02d}. {}'.format(it.contentSeason, it.contentEpisodeNumber, it.title))
return it
@@ -1150,7 +1161,7 @@ class NextDialog(xbmcgui.WindowXMLDialog):
info = kwargs.get('item').infoLabels
if "fanart" in info: img = info["fanart"]
elif "thumbnail" in info: img = info["thumbnail"]
else: img = filetools.join(config.get_runtime_path(), "resources", "noimage.png")
else: img = filetools.join(config.getRuntimePath(), "resources", "noimage.png")
self.setProperty("next_img", img)
self.setProperty("title", info["tvshowtitle"])
self.setProperty("ep_title", "{}x{:02d}. {}".format(info["season"], info["episode"], info["title"]))