def Main( settingID=None ): setfocusid = 200 if settingID == "use_intro_movie": xbmc.executebuiltin( "Skin.ToggleSetting(Use_Intro_Movie)" ) xbmc.sleep( 100 ) setting = ( "false", "true" )[ xbmc.getCondVisibility( "Skin.HasSetting(Use_Intro_Movie" ) ] Addon.setSetting( "use_intro_movie", setting ) xbmc.sleep( 100 ) setfocusid = ( 102, 103 )[ setting == "false" ] elif settingID == "splash": toggle = toggle_splash( Addon.getSetting( "splash" ) ) Addon.setSetting( "splash", toggle ) xbmc.sleep( 500 ) setfocusid = ( 110, 111 )[ toggle == "false" ] elif settingID == "intro": w = DialogSelect( "DialogSelect.xml", Addon.getAddonInfo( "path" ) ) w.doModal() del w setfocusid = 104 xbmc.executebuiltin( "Addon.openSettings(script.xbmc.intro.movie)" ) xbmc.executebuiltin( "SetFocus(200)" ) xbmc.executebuiltin( "SetFocus(%i)" % setfocusid )
def onClick(self, controlId): if controlId == schedulesListBoxId: self.goEditSchedule() elif controlId == refreshButtonId: self.xnewa.cleanCache('scheduledRecordings.p') self.render() elif controlId == sortButtonId: order = [ smartUTF8(__language__(30011)), smartUTF8(__language__(30012)), smartUTF8(__language__(30042)) ] ret = xbmcgui.Dialog().select(smartUTF8(__language__(30122)), order) if ret != -1: if ret == 0: self.sortkey = 'title' elif ret == 1: self.sortkey = 'channel' elif ret == 2: self.sortkey = 'priority' if self.sortkey != self.settings.XNEWA_SORT_RECURRING: self.settings.XNEWA_SORT_RECURRING = self.sortkey addon = Addon() addon.setSetting(id='recurringSort', value=self.sortkey) self.render()
def getSettings( self, id="repository.xbmc.builds" ): settings = {} try: from xbmcaddon import Addon addon = Addon( id ) usetempdir = addon.getSetting( "usetempdir" ) == "true" browsedir = addon.getSetting( "browsedir" ) == "true" settings[ "downloadpath" ] = ( addon.getSetting( "downloadpath" ), "" )[ browsedir ] if not usetempdir: #browse for save dir if not settings[ "downloadpath" ] or not os.path.exists( settings[ "downloadpath" ] ): dpath = xbmc.translatePath( self.get_browse_dialog( heading="Recordings folder" ) ) if dpath and os.path.exists( dpath ): settings[ "downloadpath" ] = dpath addon.setSetting( "downloadpath", settings[ "downloadpath" ] ) else: settings[ "downloadpath" ] = "" settings[ "downloadinbackground" ] = addon.getSetting( "downloadinbackground" ) == "true" settings[ "reportpercent" ] = int( "0|5|10|20|25|50|100".split( "|" )[ int( addon.getSetting( "reportpercent" ) ) ] ) PROFILE_PATH = xbmc.translatePath( addon.getAddonInfo( "profile" ) ) settings[ "iddl_data" ] = os.path.join( PROFILE_PATH, "iddl_data" ) if not os.path.exists( settings[ "iddl_data" ] ): os.makedirs( settings[ "iddl_data" ] ) except: pass return settings
def getSettings(self, id="repository.xbmc.builds"): settings = {} try: from xbmcaddon import Addon addon = Addon(id) usetempdir = addon.getSetting("usetempdir") == "true" browsedir = addon.getSetting("browsedir") == "true" settings["downloadpath"] = (addon.getSetting("downloadpath"), "")[browsedir] if not usetempdir: #browse for save dir if not settings["downloadpath"] or not os.path.exists( settings["downloadpath"]): dpath = xbmc.translatePath( self.get_browse_dialog(heading="Recordings folder")) if dpath and os.path.exists(dpath): settings["downloadpath"] = dpath addon.setSetting("downloadpath", settings["downloadpath"]) else: settings["downloadpath"] = "" settings["downloadinbackground"] = addon.getSetting( "downloadinbackground") == "true" settings["reportpercent"] = int( "0|5|10|20|25|50|100".split("|")[int( addon.getSetting("reportpercent"))]) PROFILE_PATH = xbmc.translatePath(addon.getAddonInfo("profile")) settings["iddl_data"] = os.path.join(PROFILE_PATH, "iddl_data") if not os.path.exists(settings["iddl_data"]): os.makedirs(settings["iddl_data"]) except: pass return settings
def getWeatherSettings( loc_index="1" ): try: location = Addon.getSetting( 'areacode%s' % loc_index ) SetProperty( "Location", location ) for i in range( 1, 4 ): SetProperty( "Location%i" % i, Addon.getSetting( "areacode%i" % i ) ) SetProperty( "Locations", str( i ) ) Addon.setSetting( 'currentlocation', loc_index ) except: print_exc() return location, loc_index
def onClick( self, controlID ): try: if controlID in [ 3, 6 ]: intro = self.control_list.getSelectedItem().getLabel() if intro: Addon.setSetting( "intro", intro ) self._close_dialog() elif controlID == 5: self._close_dialog() except: print_exc()
def getWeatherSettings(loc_index="1"): try: location = Addon.getSetting('areacode%s' % loc_index) SetProperty("Location", location) for i in range(1, 4): SetProperty("Location%i" % i, Addon.getSetting("areacode%i" % i)) SetProperty("Locations", str(i)) Addon.setSetting('currentlocation', loc_index) except: print_exc() return location, loc_index
def service(): from xml.dom.minidom import parseString has_splash = "true" dom = None try: dom = parseString( open( xbmc.translatePath( "special://userdata/advancedsettings.xml" ) ).read() ) has_splash = dom.getElementsByTagName( "splash" )[ 0 ].firstChild.nodeValue except: print_exc() if dom: dom.unlink() if Addon.getSetting( "splash" ) != has_splash: Addon.setSetting( "splash", has_splash )
def get_video_url(page_url, premium=False, user="", password="", video_password=""): import xbmc from xbmcaddon import Addon logger.debug("(page_url='%s')" % page_url) video_urls = [] video_id = scrapertools.find_single_match(page_url, '(?:v=|embed/)([A-z0-9_-]{11})') inputstream = platformtools.install_inputstream() try: __settings__ = Addon(name) if inputstream: __settings__.setSetting('kodion.video.quality.mpd', 'true') else: __settings__.setSetting('kodion.video.quality.mpd', 'false') # video_urls = [['con YouTube', 'plugin://plugin.video.youtube/play/?video_id=' + video_id ]] except: path = xbmc.translatePath('special://home/addons/' + name) if filetools.exists(path): if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70818)): xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "' + name + '", "enabled": true }}') else: return [['', '']] else: xbmc.executebuiltin('InstallAddon(' + name + ')', wait=True) try: Addon(name) except: return [['', '']] my_addon = xbmcaddon.Addon('plugin.video.youtube') addon_dir = xbmc.translatePath(my_addon.getAddonInfo('path')) sys.path.append(filetools.join(addon_dir, 'resources', 'lib')) from youtube_resolver import resolve for stream in resolve(page_url): # title = scrapertools.find_single_match(stream['title'], '(\d+p)') if scrapertools.find_single_match(stream['title'], r'(\d+p)'): video_urls.append( [re.sub(r'(\[[^\]]+\])', '', stream['title']), stream['url']]) video_urls.sort(key=lambda it: int(it[0].split("p", 1)[0])) return video_urls
def get_video_url(page_url, premium=False, user="", password="", video_password=""): import xbmc from xbmcaddon import Addon logger.info("(page_url='%s')" % page_url) video_urls = [] if not page_url.startswith("http"): page_url = "http://www.youtube.com/watch?v=%s" % page_url logger.info(" page_url->'%s'" % page_url) video_id = scrapertools.find_single_match(page_url, '(?:v=|embed/)([A-z0-9_-]{11})') inputstream = platformtools.install_inputstream() # from core.support import dbg;dbg() try: __settings__ = Addon(name) if inputstream: __settings__.setSetting('kodion.video.quality.mpd', 'true') else: __settings__.setSetting('kodion.video.quality.mpd', 'false') video_urls = [[ 'con YouTube', 'plugin://plugin.video.youtube/play/?video_id=' + video_id ]] except: if filetools.exists( xbmc.translatePath('special://profile/addon_data/' + name)): if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70818)): xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "' + name + '", "enabled": true }}') else: return [['', '']] else: xbmc.executebuiltin('InstallAddon(' + name + ')', wait=True) try: Addon(name) except: return [['', '']] return get_video_url(page_url) return video_urls
def onClick(self, controlId): if controlId == schedulesListBoxId: self.goEditSchedule() elif controlId == refreshButtonId: self.xnewa.cleanCache('scheduledRecordings.p') self.render() elif controlId == sortButton.Id: order = [smartUTF8(__language__(30011)),smartUTF8(__language__(30012)),smartUTF8(__language__(30042))] ret = xbmcgui.Dialog().select(smartUTF8(__language__(30122)), order); if ret != -1: if ret == 0: self.sortkey = 'title' elif ret == 1: self.sortkey = 'channel' elif ret == 2: self.sortkey = 'priority' if self.sortkey != self.settings.XNEWA_SORT_RECURRING: self.settings.XNEWA_SORT_RECURRING = self.sortkey addon = Addon() addon.setSetting(id='recurringSort',value=self.sortkey) self.render()
def migrate_from_3_to_4(addon: xbmcaddon.Addon) -> int: RANGE_ONCE_TIMERS = 7 TIMER_DAYS_PRESETS = [ [], # off [0], # mon [1], # tue [2], # wed [3], # thu [4], # fri [5], # sat [6], # sun [0], # mons [1], # tues [2], # weds [3], # thus [4], # fris [5], # sats [6], # suns [0, 1, 2, 3], # mon-thu [0, 1, 2, 3, 4], # mon-fri [0, 1, 2, 3, 4, 5], # mon-sat [1, 2, 3, 4], # tue-fri [3, 4, 5], # thu-sat [4, 5], # fri-sat [4, 5, 6], # fri-sun [5, 6], # sat-sun [5, 6, 0], # sat-mon [6, 0, 1, 2], # sun-wed [6, 0, 1, 2, 3], # sun-thu [0, 1, 2, 3, 4, 5, 6] # everyday ] xbmc.log("[script.timers] migrate settings to version 4", xbmc.LOGINFO) for i in range(TIMERS): # rename filename -> path path = addon.getSetting("timer_%i_filename" % i) addon.setSetting("timer_%i_path" % i, path) # days: enum -> multiselect schedule = int("0%s" % addon.getSetting("timer_%i" % i)) if schedule > 0: days = "|".join([str(d) for d in TIMER_DAYS_PRESETS[schedule]]) if days and schedule > RANGE_ONCE_TIMERS: days += "|7" addon.setSetting("timer_%i_days" % i, days) else: addon.setSetting("timer_%i_days" % i, "") return 4
else: DEVICE = "Unknown" try: MODEL = platform.release() or 'Unknown' except IOError: # E.g. iOS # It seems that Kodi doesn't allow python to spawn subprocesses in order to # determine the system name # See https://github.com/psf/requests/issues/4434 MODEL = 'Unknown' DEVICENAME = try_decode(_ADDON.getSetting('deviceName')) if not DEVICENAME: DEVICENAME = try_decode(xbmc.getInfoLabel('System.FriendlyName')) _ADDON.setSetting('deviceName', DEVICENAME) DEVICENAME = DEVICENAME.replace(":", "") DEVICENAME = DEVICENAME.replace("/", "-") DEVICENAME = DEVICENAME.replace("\\", "-") DEVICENAME = DEVICENAME.replace("<", "") DEVICENAME = DEVICENAME.replace(">", "") DEVICENAME = DEVICENAME.replace("*", "") DEVICENAME = DEVICENAME.replace("?", "") DEVICENAME = DEVICENAME.replace('|', "") DEVICENAME = DEVICENAME.replace('(', "") DEVICENAME = DEVICENAME.replace(')', "") DEVICENAME = DEVICENAME.replace(' ', "") COMPANION_PORT = int(_ADDON.getSetting('companionPort')) # Unique ID for this Plex client; also see clientinfo.py
# condition pour mettre a jour la base UpdateUserDB = False # initialize Keyboard kb = xbmc.Keyboard( default, heading, hidden ) # optional hidden pass kb.setHiddenInput( hidden ) # call Keyboard kb.doModal() # si confirmation on continue les changement if kb.isConfirmed(): # recup du text text = kb.getText() # si le text est pas vide et pas pareil que le default ou pas de token, on change if text:# and ( text != default or not hasToken ): Addon.setSetting( "scraper", "Media-Passion" ) # set our codes if settingId == "username": token = sha1( text.lower() + passw ).hexdigest() tokenb64 = b64encode( text ) login = text if not passw: xbmc.executebuiltin( "Action(Down)" ) else: token = sha1( login.lower() + text ).hexdigest() tokenb64 = b64encode( login ) passw = text # save cached settings infos Addon.setSetting( "token" , token ) Addon.setSetting( "tokenb64" , tokenb64 ) # save setting for visible infos
# condition pour mettre a jour la base UpdateUserDB = False # initialize Keyboard kb = xbmc.Keyboard( default, heading, hidden ) # optional hidden pass kb.setHiddenInput( hidden ) # call Keyboard kb.doModal() # si confirmation on continue les changement if kb.isConfirmed(): # recup du text text = kb.getText() # si le text est pas vide et pas pareil que le default ou pas de token, on change if text:# and ( text != default or not hasToken ): Addon.setSetting( "scraper", ( "Cine-Passion", "Media-Passion" )[ bool( settingMP ) ] ) # set our codes if settingId == "username" + settingMP: token = sha1( text.lower() + passw ).hexdigest() tokenb64 = b64encode( text ) login = text if not passw: xbmc.executebuiltin( "Action(Down)" ) else: token = sha1( login.lower() + text ).hexdigest() tokenb64 = b64encode( login ) passw = text # save cached settings infos Addon.setSetting( "token" + settingMP, token ) Addon.setSetting( "tokenb64" + settingMP, tokenb64 ) # save setting for visible infos
class NetflixCommon(object): """ Stuff shared between / used from service and addon""" def __init__(self, plugin_handle, base_url): self.addon = Addon() self.data_path = xbmc.translatePath(self.addon.getAddonInfo('profile')) self.cookie_path = self.data_path + 'COOKIE' self.plugin = self.addon.getAddonInfo('name') self.verb_log = self.addon.getSetting('logging') == 'true' self.plugin_handle = plugin_handle self.base_url = base_url self.version = self.addon.getAddonInfo('version') xbmcvfs.mkdir(path=self.data_path) def get_addon(self): """Return the current addon instance""" return self.addon def get_addon_info(self, name): """Return the current addon instance""" return self.addon.getAddonInfo(name) def set_setting(self, key, value): return self.addon.setSetting(key, value) def get_setting(self, key): return self.addon.getSetting(key) def flush_settings(self): self.addon = Addon() def get_esn(self): """ Returns the esn from settings """ return self.addon.getSetting('esn') def set_esn(self, esn): """ Returns True if MSL reset is required """ stored_esn = self.get_esn() if not stored_esn and esn: self.set_setting('esn', esn) return True return False def get_credentials(self): from NetflixCredentials import NetflixCredentials email = self.get_setting('email') password = self.get_setting('password') if '@' in email: self.set_credentials(email, password) return {'email': email, 'password': password} return NetflixCredentials().decode_credentials(email, password) def set_credentials(self, email, password): from NetflixCredentials import NetflixCredentials encoded = NetflixCredentials().encode_credentials(email, password) self.set_setting('email', encoded['email']) self.set_setting('password', encoded['password']) def log(self, msg, level=xbmc.LOGDEBUG): """Adds a log entry to the Kodi log Parameters ---------- msg : :obj:`str` Entry that should be turned into a list item level : :obj:`int` Kodi log level """ if isinstance(msg, unicode): msg = msg.encode('utf-8') xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level) @staticmethod def check_folder_path(path): """ Check if folderpath ends with path delimator If not correct it (makes sure xbmcvfs.exists is working correct) """ if isinstance(path, unicode): check = path.encode('ascii', 'ignore') if '/' in check and not str(check).endswith('/'): end = u'/' path = path + end return path if '\\' in check and not str(check).endswith('\\'): end = u'\\' path = path + end return path if '/' in path and not str(path).endswith('/'): path = path + '/' return path if '\\' in path and not str(path).endswith('\\'): path = path + '\\' return path @staticmethod def file_exists(data_path, filename): """ Checks if a given file exists :param filename: The filename :return: True if so """ return xbmcvfs.exists(path=data_path + filename) @staticmethod def save_file(data_path, filename, content): """ Saves the given content under given filename :param filename: The filename :param content: The content of the file """ file_handle = xbmcvfs.File(filepath=data_path + filename, mode='w') file_content = file_handle.write(content) file_handle.close() @staticmethod def load_file(data_path, filename): """ Loads the content of a given filename :param filename: The file to load :return: The content of the file """ file_handle = xbmcvfs.File(filepath=data_path + filename) file_content = file_handle.read() file_handle.close() return file_content @staticmethod def list_dir(data_path): return xbmcvfs.listdir(data_path)
class KodiWrapper: """ A wrapper around all Kodi functionality """ def __init__(self, routing=None): """ Initialize the Kodi wrapper """ self.routing = None if routing: self.routing = routing self._handle = self.routing.handle self._url = self.routing.base_url self._addon = Addon() self._system_locale_works = None self._addon_name = self._addon.getAddonInfo('name') self._addon_id = self._addon.getAddonInfo('id') self._global_debug_logging = self.get_global_setting( 'debug.showloginfo') # Returns a boolean self._debug_logging = self.get_setting_as_bool('debug_logging') self._cache_path = self.get_userdata_path() + 'cache/' def show_listing(self, title_items, category=None, sort='unsorted', content=None, cache=True): """ Show a virtual directory in Kodi """ if content: # content is one of: files, songs, artists, albums, movies, tvshows, episodes, musicvideos, videos, images, games xbmcplugin.setContent(self._handle, content=content) # Jump through hoops to get a stable breadcrumbs implementation category_label = '' if category: if not content: category_label = self._addon_name + ' / ' if self.kids_mode(): category_label += 'KIDS / ' if isinstance(category, int): category_label += self.localize(category) else: category_label += category elif not content: category_label = self._addon_name if self.kids_mode(): category_label += ' / KIDS' xbmcplugin.setPluginCategory(handle=self._handle, category=category_label) # Add all sort methods to GUI (start with preferred) xbmcplugin.addSortMethod(handle=self._handle, sortMethod=SORT_METHODS[sort]) for key in sorted(SORT_METHODS): if key != sort: xbmcplugin.addSortMethod(handle=self._handle, sortMethod=SORT_METHODS[key]) # Add the listings listing = [] for title_item in title_items: list_item = self._generate_listitem(title_item) is_folder = bool(not title_item.is_playable and title_item.path) url = title_item.path if title_item.path else None listing.append((url, list_item, is_folder)) succeeded = xbmcplugin.addDirectoryItems(self._handle, listing, len(listing)) xbmcplugin.endOfDirectory(self._handle, succeeded, cacheToDisc=cache) @staticmethod def _generate_listitem(title_item): """ Generate a ListItem from a TitleItem """ from xbmcgui import ListItem # Three options: # - item is a virtual directory/folder (not playable, path) # - item is a playable file (playable, path) # - item is non-actionable item (not playable, no path) is_folder = bool(not title_item.is_playable and title_item.path) is_playable = bool(title_item.is_playable and title_item.path) list_item = ListItem(label=title_item.title, path=title_item.path) if title_item.prop_dict: list_item.setProperties(title_item.prop_dict) list_item.setProperty(key='IsPlayable', value='true' if is_playable else 'false') list_item.setIsFolder(is_folder) if title_item.art_dict: list_item.setArt(title_item.art_dict) if title_item.info_dict: # type is one of: video, music, pictures, game list_item.setInfo(type='video', infoLabels=title_item.info_dict) if title_item.stream_dict: # type is one of: video, audio, subtitle list_item.addStreamInfo('video', title_item.stream_dict) if title_item.context_menu: list_item.addContextMenuItems(title_item.context_menu) return list_item def play(self, title_item, license_key=None): """ Play the passed TitleItem. :type title_item: TitleItem :type license_key: string """ play_item = self._generate_listitem(title_item) play_item.setProperty('inputstreamaddon', 'inputstream.adaptive') play_item.setProperty('inputstream.adaptive.max_bandwidth', str(self.get_max_bandwidth() * 1000)) play_item.setProperty('network.bandwidth', str(self.get_max_bandwidth() * 1000)) play_item.setProperty('inputstream.adaptive.manifest_type', 'mpd') play_item.setMimeType('application/dash+xml') play_item.setContentLookup(False) if license_key is not None: play_item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') play_item.setProperty('inputstream.adaptive.license_key', license_key) if title_item.subtitles_path: play_item.setSubtitles(title_item.subtitles_path) # To support video playback directly from RunPlugin() we need to use xbmc.Player().play instead of # setResolvedUrl that only works with PlayMedia() or with internal playable menu items xbmcplugin.setResolvedUrl(self._handle, True, listitem=play_item) if self.get_setting_as_bool('showsubtitles'): while not xbmc.Player().isPlaying() and not xbmc.Monitor( ).abortRequested(): xbmc.sleep(100) xbmc.Player().showSubtitles(True) @staticmethod def get_search_string(heading='', message=''): """ Ask the user for a search string """ search_string = None keyboard = xbmc.Keyboard(message, heading) keyboard.doModal() if keyboard.isConfirmed(): search_string = to_unicode(keyboard.getText()) return search_string def show_ok_dialog(self, heading='', message=''): """ Show Kodi's OK dialog """ from xbmcgui import Dialog if not heading: heading = self._addon.getAddonInfo('name') return Dialog().ok(heading=heading, line1=message) def show_notification(self, heading='', message='', icon='info', time=4000): """ Show a Kodi notification """ from xbmcgui import Dialog if not heading: heading = self._addon.getAddonInfo('name') Dialog().notification(heading=heading, message=message, icon=icon, time=time) def show_multiselect(self, heading='', options=None, autoclose=0, preselect=None, use_details=False): """ Show a Kodi multi-select dialog """ from xbmcgui import Dialog if not heading: heading = self._addon.getAddonInfo('name') return Dialog().multiselect(heading=heading, options=options, autoclose=autoclose, preselect=preselect, useDetails=use_details) def show_progress(self, heading='', message=''): """ Show a Kodi progress dialog """ from xbmcgui import DialogProgress if not heading: heading = self._addon.getAddonInfo('name') progress = DialogProgress() progress.create(heading=heading, line1=message) return progress def show_progress_background(self, heading='', message=''): """ Show a Kodi progress dialog """ from xbmcgui import DialogProgressBG if not heading: heading = self._addon.getAddonInfo('name') progress = DialogProgressBG() progress.create(heading=heading, message=message) return progress def set_locale(self): """ Load the proper locale for date strings """ import locale locale_lang = self.get_global_setting('locale.language').split('.')[-1] try: # NOTE: This only works if the platform supports the Kodi configured locale locale.setlocale(locale.LC_ALL, locale_lang) return True except Exception as exc: # pylint: disable=broad-except if locale_lang == 'en_gb': return True self.log("Your system does not support locale '{locale}': {error}", LOG_DEBUG, locale=locale_lang, error=exc) return False def localize(self, string_id, **kwargs): """ Return the translated string from the .po language files, optionally translating variables """ if kwargs: import string return string.Formatter().vformat( self._addon.getLocalizedString(string_id), (), SafeDict(**kwargs)) return self._addon.getLocalizedString(string_id) def get_setting(self, setting_id, default=None): """ Get an add-on setting """ value = to_unicode(self._addon.getSetting(setting_id)) if value == '' and default is not None: return default return value def get_setting_as_bool(self, setting): """ Get an add-on setting as a boolean value """ return self.get_setting(setting).lower() == "true" def set_setting(self, setting_id, setting_value): """ Set an add-on setting """ return self._addon.setSetting(setting_id, setting_value) def open_settings(self): """ Open the add-in settings window """ self._addon.openSettings() @staticmethod def get_global_setting(setting): """ Get a Kodi setting """ import json json_result = xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "Settings.GetSettingValue", "params": {"setting": "%s"}, "id": 1}' % setting) return json.loads(json_result).get('result', dict()).get('value') def get_cache(self, key, ttl=None): """ Get an item from the cache :type key: list[str] :type ttl: int """ import time fullpath = self._cache_path + '.'.join(key) if not self.check_if_path_exists(fullpath): return None if ttl and time.mktime( time.localtime()) - self.stat_file(fullpath).st_mtime() > ttl: return None with self.open_file(fullpath, 'r') as fdesc: try: import json value = json.load(fdesc) self.log('Fetching {file} from cache', file=fullpath) return value except (ValueError, TypeError): return None def set_cache(self, key, data): """ Store an item in the cache :type key: list[str] :type data: str """ if not self.check_if_path_exists(self._cache_path): self.mkdirs(self._cache_path) fullpath = self._cache_path + '.'.join(key) with self.open_file(fullpath, 'w') as fdesc: import json self.log('Storing to cache as {file}', file=fullpath) json.dump(data, fdesc) def invalidate_cache(self, ttl=None): """ Clear the cache """ if not self.check_if_path_exists(self._cache_path): return _, files = self.listdir(self._cache_path) import time now = time.mktime(time.localtime()) for filename in files: fullpath = self._cache_path + filename if ttl and now - self.stat_file(fullpath).st_mtime() < ttl: continue self.delete_file(fullpath) def get_max_bandwidth(self): """ Get the max bandwidth based on Kodi and add-on settings """ addon_max_bandwidth = int(self.get_setting('max_bandwidth', '0')) global_max_bandwidth = int( self.get_global_setting('network.bandwidth')) if addon_max_bandwidth != 0 and global_max_bandwidth != 0: return min(addon_max_bandwidth, global_max_bandwidth) if addon_max_bandwidth != 0: return addon_max_bandwidth if global_max_bandwidth != 0: return global_max_bandwidth return 0 def get_proxies(self): """ Return a usable proxies dictionary from Kodi proxy settings """ usehttpproxy = self.get_global_setting('network.usehttpproxy') if usehttpproxy is not True: return None try: httpproxytype = int( self.get_global_setting('network.httpproxytype')) except ValueError: httpproxytype = 0 socks_supported = has_socks() if httpproxytype != 0 and not socks_supported: # Only open the dialog the first time (to avoid multiple popups) if socks_supported is None: self.show_ok_dialog('', self.localize(30966)) # Requires PySocks return None proxy_types = ['http', 'socks4', 'socks4a', 'socks5', 'socks5h'] if 0 <= httpproxytype < 5: httpproxyscheme = proxy_types[httpproxytype] else: httpproxyscheme = 'http' httpproxyserver = self.get_global_setting('network.httpproxyserver') httpproxyport = self.get_global_setting('network.httpproxyport') httpproxyusername = self.get_global_setting( 'network.httpproxyusername') httpproxypassword = self.get_global_setting( 'network.httpproxypassword') if httpproxyserver and httpproxyport and httpproxyusername and httpproxypassword: proxy_address = '%s://%s:%s@%s:%s' % ( httpproxyscheme, httpproxyusername, httpproxypassword, httpproxyserver, httpproxyport) elif httpproxyserver and httpproxyport and httpproxyusername: proxy_address = '%s://%s@%s:%s' % (httpproxyscheme, httpproxyusername, httpproxyserver, httpproxyport) elif httpproxyserver and httpproxyport: proxy_address = '%s://%s:%s' % (httpproxyscheme, httpproxyserver, httpproxyport) elif httpproxyserver: proxy_address = '%s://%s' % (httpproxyscheme, httpproxyserver) else: return None return dict(http=proxy_address, https=proxy_address) @staticmethod def get_cond_visibility(condition): """ Test a condition in XBMC """ return xbmc.getCondVisibility(condition) def has_inputstream_adaptive(self): """ Whether InputStream Adaptive is installed and enabled in add-on settings """ return self.get_setting( 'useinputstreamadaptive', 'true') == 'true' and xbmc.getCondVisibility( 'System.HasAddon(inputstream.adaptive)') == 1 def credentials_filled_in(self): """ Whether the add-on has credentials filled in """ return bool( self.get_setting('username') and self.get_setting('password')) @staticmethod def kodi_version(): """ Returns major Kodi version """ return int(xbmc.getInfoLabel('System.BuildVersion').split('.')[0]) def can_play_drm(self): """ Whether this Kodi can do DRM using InputStream Adaptive """ return self.get_setting('usedrm', 'true') == 'true' and self.get_setting( 'useinputstreamadaptive', 'true') == 'true' and self.supports_drm() def supports_drm(self): """ Whether this Kodi version supports DRM decryption using InputStream Adaptive """ return self.kodi_version() > 17 def get_userdata_path(self): """ Return the profile's userdata path """ return to_unicode( xbmc.translatePath(self._addon.getAddonInfo('profile'))) def get_addon_path(self): """ Return the profile's addon path """ return to_unicode(xbmc.translatePath(self._addon.getAddonInfo('path'))) def get_addon_info(self, key): """ Return addon information """ return self._addon.getAddonInfo(key) @staticmethod def listdir(path): """ Return all files in a directory (using xbmcvfs)""" from xbmcvfs import listdir return listdir(path) def mkdir(self, path): """ Create a directory (using xbmcvfs) """ from xbmcvfs import mkdir self.log("Create directory '{path}'.", LOG_DEBUG, path=path) return mkdir(path) def mkdirs(self, path): """ Create directory including parents (using xbmcvfs) """ from xbmcvfs import mkdirs self.log("Recursively create directory '{path}'.", LOG_DEBUG, path=path) return mkdirs(path) @staticmethod def check_if_path_exists(path): """ Whether the path exists (using xbmcvfs)""" from xbmcvfs import exists return exists(path) @staticmethod @contextmanager def open_file(path, flags='r'): """ Open a file (using xbmcvfs) """ from xbmcvfs import File fdesc = File(path, flags) yield fdesc fdesc.close() @staticmethod def stat_file(path): """ Return information about a file (using xbmcvfs) """ from xbmcvfs import Stat return Stat(path) def delete_file(self, path): """ Remove a file (using xbmcvfs) """ from xbmcvfs import delete self.log("Delete file '{path}'.", LOG_DEBUG, path=path) return delete(path) def end_of_directory(self): """ Close a virtual directory, required to avoid a waiting Kodi """ xbmcplugin.endOfDirectory(handle=self._handle, succeeded=False, updateListing=False, cacheToDisc=False) def log(self, message, log_level=LOG_INFO, **kwargs): """ Log info messages to Kodi """ if not self._global_debug_logging and self._debug_logging and log_level in [ LOG_DEBUG, LOG_INFO ]: # If Debug Logging is not enabled, Kodi filters everything up to NOTICE out log_level = LOG_NOTICE if kwargs: import string message = string.Formatter().vformat(message, (), SafeDict(**kwargs)) message = '[{addon}] {message}'.format(addon=self._addon_id, message=message) xbmc.log(msg=from_unicode(message), level=log_level) def kids_mode(self): """ Returns if kids zone is active """ if self.get_setting_as_bool('force_kids_zone'): return True if self.routing and self.routing.path.startswith('/kids'): return True return False
text = kb.getText() # si le text est pas vide et pas pareil que le default ou pas de token, on change if text:# and ( text != default or not hasToken ): # set our codes if settingId == "username": token = sha1( text.lower() + passw ).hexdigest() tokenb64 = b64encode( text ) login = text if not passw: xbmc.executebuiltin( "Action(Down)" ) else: token = sha1( login.lower() + text ).hexdigest() tokenb64 = b64encode( login ) passw = text # save cached settings infos Addon.setSetting( "token", token ) Addon.setSetting( "tokenb64", tokenb64 ) # save setting for visible infos Addon.setSetting( settingId, text ) UpdateUserDB = True # reset hidden input kb.setHiddenInput( False ) if UpdateUserDB: # Modules General import time # temps du depart t1 = time.time() from re import findall, sub from urllib import quote_plus
kb.doModal() # si confirmation on continue les changement if kb.isConfirmed(): # recup du text text = kb.getText() # si le text est pas vide et pas pareil que le default ou pas de token, on change if text:# and ( text != default or not hasToken ): # set our codes if settingId == "username": token = sha.new( text.lower() + passw ).hexdigest() tokenb64 = b64encode( text ) else: token = sha.new( login.lower() + text ).hexdigest() tokenb64 = b64encode( login ) # save cached settings infos Addon.setSetting( "token", token ) Addon.setSetting( "tokenb64", tokenb64 ) # save setting for visible infos Addon.setSetting( settingId, text ) CloseDialogs = True UpdateUserDB = True # reset hidden input kb.setHiddenInput( False ) if CloseDialogs: if AddonInfoIsVisible: # fermeture du dialogue addon info xbmc.executebuiltin( "Dialog.Close(addoninformation)" ) xbmc.sleep( 200 ) if xbmc.getCondVisibility( "Window.IsVisible(addonsettings)" ):#AddonSettingsIsVisible:
# 8- write back data # def getFolders(): global watched_db, watched_pending_db watched_pending_db = os.path.join( ADDON_CACHE, "watched_pending_" + str(ADDON.getSetting("username")) + ".db") watched_db = os.path.join( ADDON_CACHE, "watched_" + str(ADDON.getSetting("username")) + ".db") if not ADDON.getSetting("setupOK"): ADDON.openSettings() ADDON.setSetting("setupOK", "True") def getPendingWatchFile(): global watched_db, watched_pending_db if os.path.exists(watched_pending_db): pendWatched = open(watched_pending_db).read() else: f = open(watched_pending_db, "w") f.write("{}") f.close() pendWatched = "{}" data = None try:
class Translator(xbmcgui.WindowXML): CONTROL_LIST_A = 50 def __init__(self, *args, **kwargs): self.RestartXBMC_ReloadLanguage = False self.IsModified = False self.googleTrans = False self.listitems = [] self.Addon = Addon(AddonId) self._get_settings() def _get_settings(self): self.settings = {} self.settings["LanguagePath"] = self.Addon.getSetting("LanguagePath") self.settings["viewmode"] = int(self.Addon.getSetting("viewmode")) self.settings["sortmethod"] = int(self.Addon.getSetting("sortmethod")) self.settings["sortorder"] = int(self.Addon.getSetting("sortorder")) self.settings["savefolderviews"] = ( self.Addon.getSetting("savefolderviews") == "true") def setListItems(self): self.DefaultLanguage = "English" self.CurrentLanguage = xbmc.getLanguage() self.FolderLanguage = self.settings["LanguagePath"] self.DefaultFolderLanguage = "special://xbmc/language/" if not os.path.exists(xbmc.translatePath(self.FolderLanguage)): print "Folder language not exists! '%s'" % self.FolderLanguage self.FolderLanguage = self.DefaultFolderLanguage if not self.FolderLanguage.startswith("special"): for folder in ["profile", "home", "xbmc"]: special = "special://%s/" % folder self.FolderLanguage = self.FolderLanguage.replace( xbmc.translatePath(special), special) if (xbmc.translatePath("special://skin/") in xbmc.translatePath(self.FolderLanguage)): self.FolderLanguage = "special://skin/language/" self.FolderLanguage = self.FolderLanguage.replace("\\", "/").rstrip("/") self.setContainerProperties() # get languages source self.language = Language(self) self.listitems = self.language.listitems def onInit(self): xbmc.executebuiltin("ActivateWindow(busydialog)") self.setSortMethodControl() self.setContainer(setviewmode=self.settings["viewmode"]) LOG("notice", "initialized took %s", time_took(START_TIME)) xbmc.executebuiltin("Dialog.Close(busydialog)") def setSortMethodControl(self): label = (20316, 103)[self.settings["sortmethod"]] self.getControl(13).setLabel(xbmc.getLocalizedString(label)) def setContainerProperties(self): self.setProperty("IsModified", ("", "Language file has been changed!")[self.IsModified]) self.setProperty("CurrentLanguage", self.CurrentLanguage) self.setProperty("FolderLanguage", self.FolderLanguage) self.setProperty("CurrentEnglishString", "") self.Addon = Addon(AddonId) self.setProperty("ExtraKeyboard_TopOrBottom", ("top", "bottom")[int(self.Addon.getSetting("ExtraKB"))]) def setContainer(self, filter="", SelectId="", setviewmode=None): if setviewmode is not None: self.ContainerId = (50, 51)[setviewmode] if setviewmode: xbmc.executebuiltin("SendClick(2)") else: self.ContainerId = ( 50, 51)[xbmc.getCondVisibility("Control.IsVisible(51)")] try: if not bool(self.listitems): if self.IsModified: # ask for save change self._save_change() self.IsModified = False self.googleTrans = False self.getControl(self.ContainerId).reset() self.setListItems() self.setContainerProperties() if self.listitems: selectitem = 0 additems = [] if not filter: additems = self.listitems else: for li in self.listitems: if filter == "UnTranslated" and li.getProperty( "UnTranslated") == "false": continue if filter == "Translated" and li.getProperty( "IsModified") != "true": continue additems.append(li) if additems: if self.settings["sortmethod"]: additems = sorted(additems, key=lambda li: normalize_string( li.getLabel(), True)) if self.settings["sortorder"]: additems = list(reversed(additems)) for count, li in enumerate(additems): if li.getProperty("id") == SelectId: selectitem = count # add listitems self.getControl(self.ContainerId).reset() self.getControl(self.ContainerId).addItems(additems) if additems: #self.getControl( self.ContainerId ).size(): self.getControl(self.ContainerId).selectItem(selectitem) self.setFocusId(self.ContainerId) # fixe view on xbox if UNDER_XBOX and setviewmode is not None: xbmc.executebuiltin("Container.SetViewMode(%i)" % self.ContainerId) xbmc.sleep(20) self.setFocusId(self.ContainerId) except: print_exc() def onFocus(self, controlID): pass def sendClick(self, controlID): try: self.onClick(controlID) except: print_exc() def getTranslate(self, text, minimal=2): translated = "" if text: if (len(text) <= minimal) or text.isdigit(): translated = text else: country = self.Addon.getSetting("country") if country.lower() == "auto": country = self.CurrentLanguage pDialog = xbmcgui.DialogProgress() pDialog.create("Google Translate", "English to %s" % country, text, "Please wait...") try: import LanguageTools translated = LanguageTools.translate_text( text, country, "google") except: print_exc() self.googleTrans = False xbmc.executebuiltin("Dialog.Close(progressdialog)") return translated def onClick(self, controlID): try: self.ContainerId = ( 50, 51)[xbmc.getCondVisibility("Control.IsVisible(51)")] if controlID == self.ContainerId: # get clicked listitem listitem = self.getControl(self.ContainerId).getSelectedItem() # get position pos = int(listitem.getProperty("Position")) # get id id = listitem.getProperty("id") if id: CurrentEnglishString = fixe_line_return( listitem.getLabel2(), True) DefaultText = fixe_line_return(listitem.getLabel(), True) old_text = DefaultText if self.googleTrans: old_text = self.getTranslate(CurrentEnglishString) old_text = old_text or DefaultText if (self.Addon.getSetting("BoldKB") == "true"): CurrentEnglishString = "[B]%s[/B]" % CurrentEnglishString self.setProperty("CurrentEnglishString", CurrentEnglishString) self.setProperty("ShowCurrentEnglishString", "true") kb = xbmc.Keyboard( old_text, self.CurrentLanguage + " (Enter desired string)", False) kb.doModal() if kb.isConfirmed(): new_text = kb.getText() if new_text != DefaultText: new_text = fixe_line_return(new_text) self.listitems[pos].setLabel(new_text) self.listitems[pos].setProperty( "IsModified", "true") self.setProperty( "IsModified", "Language file has been changed!") self.IsModified = True self.setProperty("ShowCurrentEnglishString", "") # PAS TRES BON COMME FILTRE :( UnTranslated = self.getControl(19).isSelected() Translated = self.getControl(20).isSelected() Changed = self.getControl(21).isSelected() filter = ("", "UnTranslated")[UnTranslated] filter = (filter, "Translated")[Translated] filter = (filter, "Changed")[Changed] # get selected id for selectitem again, if controlID 22 clicked SelectId = xbmc.getInfoLabel( "Container(50).ListItem.Property(id)") or xbmc.getInfoLabel( "Container(51).ListItem.Property(id)") if controlID == 19: # UNTRANSLATED BUTTON filter = ("", "UnTranslated")[UnTranslated] self.setContainer(filter, SelectId) self.getControl(19).setSelected(UnTranslated) self.getControl(20).setSelected(False) self.getControl(21).setSelected(False) elif controlID == 20: # TRANSLATED BUTTON filter = ("", "Translated")[Translated] self.setContainer(filter, SelectId) self.getControl(20).setSelected(Translated) self.getControl(19).setSelected(False) self.getControl(21).setSelected(False) elif controlID == 21: # CHANGED BUTTON filter = ("", "Changed")[Changed] self.setContainer(filter, SelectId) self.getControl(21).setSelected(Changed) self.getControl(19).setSelected(False) self.getControl(20).setSelected(False) elif controlID == 22: # VIEW AS BUTTON self.settings["viewmode"] = (1, 0)[self.settings["viewmode"]] xbmc.sleep(50) self.setContainer(filter, SelectId) elif controlID == 13: # SORT BY BUTTON self.settings["sortmethod"] = (1, 0)[self.settings["sortmethod"]] self.setSortMethodControl() self.setContainer(filter, SelectId) elif controlID == 14: # SORT ASC BUTTON self.settings["sortorder"] = (1, 0)[self.settings["sortorder"]] self.setContainer(filter, SelectId) elif controlID == 32: # SETTINGS BUTTON self.Addon = Addon(AddonId) self.Addon.openSettings() xbmc.sleep(10) if self.settings["LanguagePath"] != self.Addon.getSetting( "LanguagePath"): self.settings["LanguagePath"] = self.Addon.getSetting( "LanguagePath") self.listitems = [] self.setContainer(filter, SelectId) elif controlID == 33: # FIND BUTTON default = self.getControl(33).getLabel2() kb = xbmc.Keyboard(default, "Find what ...", False) kb.doModal() if kb.isConfirmed(): find_text = kb.getText() #self.getControl( 33 ).setLabel( "Find", label2=find_text ) self.setProperty("FindText", find_text) if find_text: # and find_text != default: for count, li in enumerate(self.listitems): #l_text = find_text.lower() #match = ( l_text in li.getLabel().lower() ) or ( l_text in li.getLabel2().lower() ) or ( l_text == li.getProperty( "id" ) ) #match = match or ( l_text == li.getLabel().lower() ) or ( l_text == li.getLabel2().lower() ) #if not match: continue if self.findText(find_text, li): self.getControl( self.ContainerId).selectItem(count) self.setFocusId(self.ContainerId) break elif controlID == 34: # FIND NEXT BUTTON find_next = self.getControl(33).getLabel2().encode("utf-8") pos = self.getControl(self.ContainerId).getSelectedPosition() for count, li in enumerate(self.listitems): if count <= pos: continue #if find_next in li.getLabel() or find_next == li.getProperty( "id" ): if self.findText(find_next, li): self.getControl(self.ContainerId).selectItem(count) break except: print_exc() def findText(self, text, listitem): return re.search( text.lower(), "|".join([ listitem.getLabel(), listitem.getLabel2(), listitem.getProperty("id") ]).lower()) def onAction(self, action): if action in [9, 10]: self._close_window() elif action == 117: try: cm = DialogContextMenu("Translator-DialogContextMenu.xml", CWD, parent=self) cm.doModal() del cm except: print_exc() else: try: bcode = action.getButtonCode() # keyboard press F3 if bcode == 127138: self.sendClick(34) # except: print_exc() def _close_window(self): xbmc.executebuiltin("ActivateWindow(busydialog)") if self.settings["savefolderviews"]: self.Addon.setSetting("viewmode", str(self.settings["viewmode"])) self.Addon.setSetting("sortmethod", str(self.settings["sortmethod"])) self.Addon.setSetting("sortorder", str(self.settings["sortorder"])) xbmc.sleep(10) if self.IsModified: # ask for save change xbmc.executebuiltin("Dialog.Close(busydialog)") self._save_change() try: del self.language except: pass self.close() def _save_change(self): if xbmcgui.Dialog().yesno("Confirm file save", "Language file has been changed!", self.language.current_xml, "Do you want save your change?", ""): xbmc.executebuiltin("ActivateWindow(busydialog)") OK = self.language.save_strings() xbmc.executebuiltin("Dialog.Close(busydialog)") if (self.DefaultFolderLanguage.rstrip("/") == self.FolderLanguage ) or (xbmc.translatePath("special://skin/") in xbmc.translatePath(self.FolderLanguage)): # if default xbmc language file has been changed, # set True, XBMC require Restart or reload language self.RestartXBMC_ReloadLanguage = OK or self.RestartXBMC_ReloadLanguage
# condition pour mettre a jour la base UpdateUserDB = False # initialize Keyboard kb = xbmc.Keyboard(default, heading, hidden) # optional hidden pass kb.setHiddenInput(hidden) # call Keyboard kb.doModal() # si confirmation on continue les changement if kb.isConfirmed(): # recup du text text = kb.getText() # si le text est pas vide et pas pareil que le default ou pas de token, on change if text: # and ( text != default or not hasToken ): Addon.setSetting("scraper", ("Cine-Passion", "Media-Passion")[bool(settingMP)]) # set our codes if settingId == "username" + settingMP: token = sha1(text.lower() + passw).hexdigest() tokenb64 = b64encode(text) login = text if not passw: xbmc.executebuiltin("Action(Down)") else: token = sha1(login.lower() + text).hexdigest() tokenb64 = b64encode(login) passw = text # save cached settings infos Addon.setSetting("token" + settingMP, token) Addon.setSetting("tokenb64" + settingMP, tokenb64) # save setting for visible infos
class NetflixCommon(object): """ Stuff shared between / used from service and addon""" def __init__(self, plugin_handle, base_url): self.addon = Addon() self.data_path = xbmc.translatePath(self.addon.getAddonInfo('profile')) self.cookie_path = self.data_path + 'COOKIE' self.plugin = self.addon.getAddonInfo('name') self.verb_log = self.addon.getSetting('logging') == 'true' self.plugin_handle = plugin_handle self.base_url = base_url self.version = self.addon.getAddonInfo('version') xbmcvfs.mkdir(path=self.data_path) def get_addon(self): """Return the current addon instance""" return self.addon def get_addon_info(self, name): """Return the current addon instance""" return self.addon.getAddonInfo(name) def set_setting(self, key, value): return self.addon.setSetting(key, value) def get_setting(self, key): return self.addon.getSetting(key) def flush_settings(self): self.addon = Addon() def get_esn(self): """ Returns the esn from settings """ return self.addon.getSetting('esn') def set_esn(self, esn): """ Returns True if MSL reset is required """ stored_esn = self.get_esn() if not stored_esn and esn: self.set_setting('esn', esn) return True return False def get_credentials(self): from NetflixCredentials import NetflixCredentials email = self.get_setting('email') password = self.get_setting('password') if '@' in email: self.set_credentials(email, password) return {'email' : email, 'password' : password } return NetflixCredentials().decode_credentials(email, password) def set_credentials(self, email, password): from NetflixCredentials import NetflixCredentials encoded = NetflixCredentials().encode_credentials(email, password) self.set_setting('email',encoded['email']) self.set_setting('password',encoded['password']) def log(self, msg, level=xbmc.LOGDEBUG): """Adds a log entry to the Kodi log Parameters ---------- msg : :obj:`str` Entry that should be turned into a list item level : :obj:`int` Kodi log level """ if isinstance(msg, unicode): msg = msg.encode('utf-8') xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level) @staticmethod def check_folder_path(path): """ Check if folderpath ends with path delimator If not correct it (makes sure xbmcvfs.exists is working correct) """ if isinstance(path, unicode): check = path.encode('ascii', 'ignore') if '/' in check and not str(check).endswith('/'): end = u'/' path = path + end return path if '\\' in check and not str(check).endswith('\\'): end = u'\\' path = path + end return path if '/' in path and not str(path).endswith('/'): path = path + '/' return path if '\\' in path and not str(path).endswith('\\'): path = path + '\\' return path @staticmethod def file_exists(data_path, filename): """ Checks if a given file exists :param filename: The filename :return: True if so """ return xbmcvfs.exists(path=data_path + filename) @staticmethod def save_file(data_path, filename, content): """ Saves the given content under given filename :param filename: The filename :param content: The content of the file """ file_handle = xbmcvfs.File( filepath=data_path + filename, mode='w') file_content = file_handle.write(content) file_handle.close() @staticmethod def load_file(data_path, filename): """ Loads the content of a given filename :param filename: The file to load :return: The content of the file """ file_handle = xbmcvfs.File( filepath=data_path + filename) file_content = file_handle.read() file_handle.close() return file_content @staticmethod def list_dir(data_path): return xbmcvfs.listdir(data_path)
intros_dir = os.path.join( Addon.getAddonInfo( "path" ), "resources", "intros" ) intro = Addon.getSetting( "intro" ) if Addon.getSetting( "use_custom_intro" ) == "true": c_intro = Addon.getSetting( "path_custom_intro" ) if c_intro and xbmcvfs.exists( c_intro ): intro = c_intro if intro == "Random": intros = os.listdir( intros_dir ) last = Addon.getSetting( "last_random" ) if last and last in intros: del intros[ intros.index( last ) ] random.shuffle( intros ) intro = random.choice( intros ) Addon.setSetting( "last_random", intro ) player = xbmc.Player() player.play( os.path.join( intros_dir, intro ) ) xbmcgui.Window( 10000 ).setProperty( "intro.isplayed", "true" ) if ReplaceWindowHome: xbmc.sleep( 1000 ) while player.isPlaying(): #continue time.sleep( .2 ) xbmc.executebuiltin( "ReplaceWindow(Home)" ) xbmc.sleep( 1000 )
def selectDevice(): import xbmc from xbmcgui import Dialog from xbmcaddon import Addon ADDON = Addon("script.samsung.remote") xbmc.executebuiltin('ActivateWindow(busydialog)') tv_devices = sorted(getSamDevices().items()) choices = ["%s (%s) @ %s" % (v[0], v[1], k) for k, v in tv_devices] + ["Manual", "Cancel"] xbmc.executebuiltin('Dialog.Close(busydialog,true)') selected = Dialog().select("Select your Samsung device", choices) device = None if selected >= 0 and selected < len(tv_devices): # auto and selected device = tv_devices[selected] ADDON.setSetting("autosam", "$LOCALIZE[13416]") ADDON.setSetting("manualsam", "false") ADDON.setSetting("tvmodel", device[1][1]) ADDON.setSetting("tvname", device[1][0]) ADDON.setSetting("tvip", device[0]) elif selected == len(tv_devices): # manual ADDON.setSetting("autosam", "$LOCALIZE[413]") ADDON.setSetting("manualsam", "true") xbmc.sleep(500) xbmc.executebuiltin('Action(Down)')
def onClick(self, controlId): if controlId == programsListBoxId: self.goEditSchedule() elif controlId == refreshButtonId: self.xnewa.cleanCache('recentRecordings*.p') self.xnewa.cleanCache('summary.List') self.render() elif controlId == importButtonId: dialog = xbmcgui.Dialog() ret = dialog.yesno(smartUTF8(__language__(30127)), '%s %s' % (smartUTF8(__language__(30121)), self.recentData[self.programsListBox.getSelectedPosition()]['title'])) elif controlId == actionButtonId: order = [__language__(30038),__language__(30039),__language__(32003),__language__(30054),__language__(32004),__language__(30033)] ret = xbmcgui.Dialog().select(__language__(32005), order); if ret > 0: self.processFile(order[ret]) if self.selections > 0: self.win.setProperty('tagged', 'true') else: self.win.setProperty('tagged', 'false') if self.mode ==0: self.render() elif controlId == filterButtonId: choices = list(self.xnewa.RecDirs.keys()) if self.filterButton.isSelected(): archive = xbmcgui.Dialog().select(smartUTF8(__language__(30115)), choices) if archive != -1: self.filtered = True self.win.setProperty('archive', choices[archive]) self.recDir = self.xnewa.RecDirs[choices[archive]] else: self.recDir = None archive = 0 self.win.setProperty('archive', __language__(30020)) if archive != -1: self.xnewa.cleanCache('recentRecordings*.p') self.xnewa.cleanCache('summary.List') self.render() elif controlId == sortButtonId: order = [smartUTF8(__language__(30011)),smartUTF8(__language__(30148)),smartUTF8(__language__(30149)),__language__(32006)] ret = xbmcgui.Dialog().select(smartUTF8(__language__(30122)), order); if ret != -1: if ret == 0: self.sortTitle[self.mode] = True self.sortDate[self.mode] = True elif ret == 1: self.sortTitle[self.mode] = False self.sortDate[self.mode] = True elif ret == 2: self.sortTitle[self.mode] = False self.sortDate[self.mode] = False if self.mode == 0: if ret != self.settings.XNEWA_SORT_RECORDING: addon = Addon() addon.setSetting(id='recordingSort',value=str(ret)) self.settings.XNEWA_SORT_RECORDING = ret self.xnewa.cleanCache('summary.List') else: if ret != self.settings.XNEWA_SORT_EPISODE: addon = Addon() addon.setSetting(id='episodeSort',value=str(ret)) self.settings.XNEWA_SORT_EPISODE = ret self.xnewa.cleanCache('recentRecordings*.p') self.render()
class Translator( xbmcgui.WindowXML ): CONTROL_LIST_A = 50 def __init__( self, *args, **kwargs ): self.RestartXBMC_ReloadLanguage = False self.IsModified = False self.googleTrans = False self.listitems = [] self.Addon = Addon( AddonId ) self._get_settings() def _get_settings( self ): self.settings = {} self.settings[ "LanguagePath" ] = self.Addon.getSetting( "LanguagePath" ) self.settings[ "viewmode" ] = int( self.Addon.getSetting( "viewmode" ) ) self.settings[ "sortmethod" ] = int( self.Addon.getSetting( "sortmethod" ) ) self.settings[ "sortorder" ] = int( self.Addon.getSetting( "sortorder" ) ) self.settings[ "savefolderviews" ] = ( self.Addon.getSetting( "savefolderviews" ) == "true" ) def setListItems( self ): self.DefaultLanguage = "English" self.CurrentLanguage = xbmc.getLanguage() self.FolderLanguage = self.settings[ "LanguagePath" ] self.DefaultFolderLanguage = "special://xbmc/language/" if not os.path.exists( xbmc.translatePath( self.FolderLanguage ) ): print "Folder language not exists! '%s'" % self.FolderLanguage self.FolderLanguage = self.DefaultFolderLanguage if not self.FolderLanguage.startswith( "special" ): for folder in [ "profile", "home", "xbmc" ]: special = "special://%s/" % folder self.FolderLanguage = self.FolderLanguage.replace( xbmc.translatePath( special ), special ) if ( xbmc.translatePath( "special://skin/" ) in xbmc.translatePath( self.FolderLanguage ) ): self.FolderLanguage = "special://skin/language/" self.FolderLanguage = self.FolderLanguage.replace( "\\", "/" ).rstrip( "/" ) self.setContainerProperties() # get languages source self.language = Language( self ) self.listitems = self.language.listitems def onInit( self ): xbmc.executebuiltin( "ActivateWindow(busydialog)" ) self.setSortMethodControl() self.setContainer( setviewmode=self.settings[ "viewmode" ] ) LOG( "notice", "initialized took %s", time_took( START_TIME ) ) xbmc.executebuiltin( "Dialog.Close(busydialog)" ) def setSortMethodControl( self ): label = ( 20316, 103 )[ self.settings[ "sortmethod" ] ] self.getControl( 13 ).setLabel( xbmc.getLocalizedString( label ) ) def setContainerProperties( self ): self.setProperty( "IsModified", ( "", "Language file has been changed!" )[ self.IsModified ] ) self.setProperty( "CurrentLanguage", self.CurrentLanguage ) self.setProperty( "FolderLanguage", self.FolderLanguage ) self.setProperty( "CurrentEnglishString", "" ) self.Addon = Addon( AddonId ) self.setProperty( "ExtraKeyboard_TopOrBottom", ( "top", "bottom" )[ int( self.Addon.getSetting( "ExtraKB" ) ) ] ) def setContainer( self, filter="", SelectId="", setviewmode=None ): if setviewmode is not None: self.ContainerId = ( 50, 51 )[ setviewmode ] if setviewmode: xbmc.executebuiltin( "SendClick(2)" ) else: self.ContainerId = ( 50, 51 )[ xbmc.getCondVisibility( "Control.IsVisible(51)" ) ] try: if not bool( self.listitems ): if self.IsModified: # ask for save change self._save_change() self.IsModified = False self.googleTrans = False self.getControl( self.ContainerId ).reset() self.setListItems() self.setContainerProperties() if self.listitems: selectitem = 0 additems = [] if not filter: additems = self.listitems else: for li in self.listitems: if filter == "UnTranslated" and li.getProperty( "UnTranslated" ) == "false": continue if filter == "Translated" and li.getProperty( "IsModified" ) != "true": continue additems.append( li ) if additems: if self.settings[ "sortmethod" ]: additems = sorted( additems, key=lambda li: normalize_string( li.getLabel(), True ) ) if self.settings[ "sortorder" ]: additems = list( reversed( additems ) ) for count, li in enumerate( additems ): if li.getProperty( "id" ) == SelectId: selectitem = count # add listitems self.getControl( self.ContainerId ).reset() self.getControl( self.ContainerId ).addItems( additems ) if additems: #self.getControl( self.ContainerId ).size(): self.getControl( self.ContainerId ).selectItem( selectitem ) self.setFocusId( self.ContainerId ) # fixe view on xbox if UNDER_XBOX and setviewmode is not None: xbmc.executebuiltin( "Container.SetViewMode(%i)" % self.ContainerId ) xbmc.sleep( 20 ) self.setFocusId( self.ContainerId ) except: print_exc() def onFocus( self, controlID ): pass def sendClick( self, controlID ): try: self.onClick( controlID ) except: print_exc() def getTranslate( self, text, minimal=2 ): translated = "" if text: if ( len( text ) <= minimal ) or text.isdigit(): translated = text else: country = self.Addon.getSetting( "country" ) if country.lower() == "auto": country = self.CurrentLanguage pDialog = xbmcgui.DialogProgress() pDialog.create( "Google Translate", "English to %s" % country, text, "Please wait..." ) try: import LanguageTools translated = LanguageTools.translate_text( text, country, "google" ) except: print_exc() self.googleTrans = False xbmc.executebuiltin( "Dialog.Close(progressdialog)" ) return translated def onClick( self, controlID ): try: self.ContainerId = ( 50, 51 )[ xbmc.getCondVisibility( "Control.IsVisible(51)" ) ] if controlID == self.ContainerId: # get clicked listitem listitem = self.getControl( self.ContainerId ).getSelectedItem() # get position pos = int( listitem.getProperty( "Position" ) ) # get id id = listitem.getProperty( "id" ) if id: CurrentEnglishString = fixe_line_return( listitem.getLabel2(), True ) DefaultText = fixe_line_return( listitem.getLabel(), True ) old_text = DefaultText if self.googleTrans: old_text = self.getTranslate( CurrentEnglishString ) old_text = old_text or DefaultText if ( self.Addon.getSetting( "BoldKB" ) == "true" ): CurrentEnglishString = "[B]%s[/B]" % CurrentEnglishString self.setProperty( "CurrentEnglishString", CurrentEnglishString ) self.setProperty( "ShowCurrentEnglishString", "true" ) kb = xbmc.Keyboard( old_text, self.CurrentLanguage + " (Enter desired string)", False ) kb.doModal() if kb.isConfirmed(): new_text = kb.getText() if new_text != DefaultText: new_text = fixe_line_return( new_text ) self.listitems[ pos ].setLabel( new_text ) self.listitems[ pos ].setProperty( "IsModified", "true" ) self.setProperty( "IsModified", "Language file has been changed!" ) self.IsModified = True self.setProperty( "ShowCurrentEnglishString", "" ) # PAS TRES BON COMME FILTRE :( UnTranslated = self.getControl( 19 ).isSelected() Translated = self.getControl( 20 ).isSelected() Changed = self.getControl( 21 ).isSelected() filter = ( "", "UnTranslated" )[ UnTranslated ] filter = ( filter, "Translated" )[ Translated ] filter = ( filter, "Changed" )[ Changed ] # get selected id for selectitem again, if controlID 22 clicked SelectId = xbmc.getInfoLabel( "Container(50).ListItem.Property(id)" ) or xbmc.getInfoLabel( "Container(51).ListItem.Property(id)" ) if controlID == 19: # UNTRANSLATED BUTTON filter = ( "", "UnTranslated" )[ UnTranslated ] self.setContainer( filter, SelectId ) self.getControl( 19 ).setSelected( UnTranslated ) self.getControl( 20 ).setSelected( False ) self.getControl( 21 ).setSelected( False ) elif controlID == 20: # TRANSLATED BUTTON filter = ( "", "Translated" )[ Translated ] self.setContainer( filter, SelectId ) self.getControl( 20 ).setSelected( Translated ) self.getControl( 19 ).setSelected( False ) self.getControl( 21 ).setSelected( False ) elif controlID == 21: # CHANGED BUTTON filter = ( "", "Changed" )[ Changed ] self.setContainer( filter, SelectId ) self.getControl( 21 ).setSelected( Changed ) self.getControl( 19 ).setSelected( False ) self.getControl( 20 ).setSelected( False ) elif controlID == 22: # VIEW AS BUTTON self.settings[ "viewmode" ] = ( 1, 0 )[ self.settings[ "viewmode" ] ] xbmc.sleep( 50 ) self.setContainer( filter, SelectId ) elif controlID == 13: # SORT BY BUTTON self.settings[ "sortmethod" ] = ( 1, 0 )[ self.settings[ "sortmethod" ] ] self.setSortMethodControl() self.setContainer( filter, SelectId ) elif controlID == 14: # SORT ASC BUTTON self.settings[ "sortorder" ] = ( 1, 0 )[ self.settings[ "sortorder" ] ] self.setContainer( filter, SelectId ) elif controlID == 32: # SETTINGS BUTTON self.Addon = Addon( AddonId ) self.Addon.openSettings() xbmc.sleep( 10 ) if self.settings[ "LanguagePath" ] != self.Addon.getSetting( "LanguagePath" ): self.settings[ "LanguagePath" ] = self.Addon.getSetting( "LanguagePath" ) self.listitems = [] self.setContainer( filter, SelectId ) elif controlID == 33: # FIND BUTTON default = self.getControl( 33 ).getLabel2() kb = xbmc.Keyboard( default, "Find what ...", False ) kb.doModal() if kb.isConfirmed(): find_text = kb.getText() #self.getControl( 33 ).setLabel( "Find", label2=find_text ) self.setProperty( "FindText", find_text ) if find_text:# and find_text != default: for count, li in enumerate( self.listitems ): #l_text = find_text.lower() #match = ( l_text in li.getLabel().lower() ) or ( l_text in li.getLabel2().lower() ) or ( l_text == li.getProperty( "id" ) ) #match = match or ( l_text == li.getLabel().lower() ) or ( l_text == li.getLabel2().lower() ) #if not match: continue if self.findText( find_text, li ): self.getControl( self.ContainerId ).selectItem( count ) self.setFocusId( self.ContainerId ) break elif controlID == 34: # FIND NEXT BUTTON find_next = self.getControl( 33 ).getLabel2().encode( "utf-8" ) pos = self.getControl( self.ContainerId ).getSelectedPosition() for count, li in enumerate( self.listitems ): if count <= pos: continue #if find_next in li.getLabel() or find_next == li.getProperty( "id" ): if self.findText( find_next, li ): self.getControl( self.ContainerId ).selectItem( count ) break except: print_exc() def findText( self, text, listitem ): return re.search( text.lower(), "|".join( [ listitem.getLabel(), listitem.getLabel2(), listitem.getProperty( "id" ) ] ).lower() ) def onAction( self, action ): if action in [ 9, 10 ]: self._close_window() elif action == 117: try: cm = DialogContextMenu( "Translator-DialogContextMenu.xml", CWD, parent=self ) cm.doModal() del cm except: print_exc() else: try: bcode = action.getButtonCode() # keyboard press F3 if bcode == 127138: self.sendClick( 34 ) # except: print_exc() def _close_window( self ): xbmc.executebuiltin( "ActivateWindow(busydialog)" ) if self.settings[ "savefolderviews" ]: self.Addon.setSetting( "viewmode", str( self.settings[ "viewmode" ] ) ) self.Addon.setSetting( "sortmethod", str( self.settings[ "sortmethod" ] ) ) self.Addon.setSetting( "sortorder", str( self.settings[ "sortorder" ] ) ) xbmc.sleep( 10 ) if self.IsModified: # ask for save change xbmc.executebuiltin( "Dialog.Close(busydialog)" ) self._save_change() try: del self.language except: pass self.close() def _save_change( self ): if xbmcgui.Dialog().yesno( "Confirm file save", "Language file has been changed!", self.language.current_xml, "Do you want save your change?", "" ): xbmc.executebuiltin( "ActivateWindow(busydialog)" ) OK = self.language.save_strings() xbmc.executebuiltin( "Dialog.Close(busydialog)" ) if ( self.DefaultFolderLanguage.rstrip( "/" ) == self.FolderLanguage ) or ( xbmc.translatePath( "special://skin/" ) in xbmc.translatePath( self.FolderLanguage ) ): # if default xbmc language file has been changed, # set True, XBMC require Restart or reload language self.RestartXBMC_ReloadLanguage = OK or self.RestartXBMC_ReloadLanguage
def onClick(self, controlId): if controlId == programsListBoxId: self.goEditSchedule() elif controlId == refreshButtonId: self.xnewa.cleanCache('recentRecordings*.p') self.xnewa.cleanCache('summary.List') self.render() elif controlId == importButtonId: dialog = xbmcgui.Dialog() ret = dialog.yesno( smartUTF8(__language__(30127)), '%s %s' % (smartUTF8(__language__(30121)), self.recentData[ self.programsListBox.getSelectedPosition()]['title'])) elif controlId == actionButtonId: order = [ __language__(30038), __language__(30039), __language__(32003), __language__(30054), __language__(32004), __language__(30033) ] ret = xbmcgui.Dialog().select(__language__(32005), order) if ret > 0: self.processFile(order[ret]) if self.selections > 0: self.win.setProperty('tagged', 'true') else: self.win.setProperty('tagged', 'false') if self.mode == 0: self.render() elif controlId == filterButtonId: choices = list(self.xnewa.RecDirs.keys()) if self.filterButton.isSelected(): archive = xbmcgui.Dialog().select( smartUTF8(__language__(30115)), choices) if archive != -1: self.filtered = True self.win.setProperty('archive', choices[archive]) self.recDir = self.xnewa.RecDirs[choices[archive]] else: self.recDir = None archive = 0 self.win.setProperty('archive', __language__(30020)) if archive != -1: self.xnewa.cleanCache('recentRecordings*.p') self.xnewa.cleanCache('summary.List') self.render() elif controlId == sortButtonId: order = [ smartUTF8(__language__(30011)), smartUTF8(__language__(30148)), smartUTF8(__language__(30149)), __language__(32006) ] ret = xbmcgui.Dialog().select(smartUTF8(__language__(30122)), order) if ret != -1: if ret == 0: self.sortTitle[self.mode] = True self.sortDate[self.mode] = True elif ret == 1: self.sortTitle[self.mode] = False self.sortDate[self.mode] = True elif ret == 2: self.sortTitle[self.mode] = False self.sortDate[self.mode] = False if self.mode == 0: if ret != self.settings.XNEWA_SORT_RECORDING: addon = Addon() addon.setSetting(id='recordingSort', value=str(ret)) self.settings.XNEWA_SORT_RECORDING = ret self.xnewa.cleanCache('summary.List') else: if ret != self.settings.XNEWA_SORT_EPISODE: addon = Addon() addon.setSetting(id='episodeSort', value=str(ret)) self.settings.XNEWA_SORT_EPISODE = ret self.xnewa.cleanCache('recentRecordings*.p') self.render()