Exemple #1
0
 def __init__(self):
     '''
     Initialised at every directory change in Kodi <= 17.6.
     '''
     self.window = Window(getCurrentWindowId())
     self.diskNamesSet = None
     self.dirtyNamesSet = None
Exemple #2
0
 def togglePreview(self):
     if self.toggledPreview():
         Window(10000).clearProperty('SR_togglePreview')
         utils.notify(utils.translation(32226))
     else:
         Window(10000).setProperty('SR_togglePreview', '1')
         utils.notify(utils.translation(32227))
Exemple #3
0
 def playingCamera(self, camera_number):
     allcameras = Window(10000).getProperty('SR_playingCamera_0')
     singlecamera = Window(10000).getProperty('SR_playingCamera_%s' %
                                              camera_number)
     if allcameras == '1' or singlecamera == '1':
         return True
     return False
    def __init__(self, w=0.5, h=0.15, y_offset=0, label_padding=15, label_h=43):
        window_width, window_height = get_resolution()
        self._window = Window(WINDOW_FULLSCREEN_VIDEO)
        self._shown = False

        logging.debug("Using window width=%d and height=%d", window_width, window_height)
        total_label_h = 3 * label_h
        w = int(w * window_width)
        h = max(int(h * window_height), total_label_h + 2 * label_padding)
        x = (window_width - w) // 2
        y = int((3 * window_height / 4) - (h / 2) + 0.5) + y_offset

        label_x = x + label_padding
        label_w = w - 2 * label_padding
        label_y = y + int((h - total_label_h) / 2 + 0.5)
        self._label1 = ControlLabel(label_x, label_y, label_w, label_h, "", alignment=0x2 | 0x4)
        label_y += label_h
        self._label2 = ControlLabel(label_x, label_y, label_w, label_h, "", alignment=0x2 | 0x4)
        label_y += label_h
        self._label3 = ControlLabel(label_x, label_y, label_w, label_h, "", alignment=0x2 | 0x4)
        self._background = ControlImage(
            x, y, 0, 0, os.path.join(ADDON_PATH, "resources", "images", "black.png"),
            colorDiffuse="0xD0000000")
        self._controls = [self._background, self._label1, self._label2, self._label3]
        self._window.addControls(self._controls)
        # We are only able to update visibility after adding elements, so to make them not visible
        # we have to create them with 0 width and height and then update the controls after adding
        # them to the window
        for c in self._controls:
            c.setVisible(self._shown)
        self._background.setWidth(w)
        self._background.setHeight(h)
    def __init__(self, base_url, handle, params):
        # type: (Text, int, Text) -> None

        self._base_url = base_url
        self._handle = handle
        self._params = self._params_to_dict(params)

        if not self._ADDON.getSetting("username"):
            self._ADDON.openSettings()

        username = self._ADDON.getSetting("username")
        password = self._ADDON.getSetting("password")
        access_token = (Window(10000).getProperty(self._ACCESS_TOKEN_PROPERTY)
                        or None)
        id_token = Window(10000).getProperty(self._ID_TOKEN_PROPERTY) or None
        cache_name = "special://profile/addon_data/{}/requests_cache".format(
            self._ADDON_ID)

        self._api = BouyguesTV(
            username,
            password,
            access_token=access_token,
            id_token=id_token,
            cache_name=xbmc.translatePath(cache_name),
        )
Exemple #6
0
class DemoOverlay():
    def __init__(self, windowid):
        self.window = Window(windowid)
        self._demolabel = None
        self.log('initialized')

    def log(self, msg, level=2):
        ulog(msg, name=self.__class__.__name__, level=level)

    def show(self):
        if self._demolabel is not None:
            return
        # FIXME: Using a different font does not seem to have much of an impact
        self._demolabel = ControlLabel(0, getScreenHeight() // 4, getScreenWidth(), 100, localize(30060) + '\n' + localize(30061), font='font36_title', textColor='0xddee9922', alignment=0x00000002)
        self.window.addControl(self._demolabel)
        self.log('show', 0)

    def hide(self):
        if self._demolabel is None:
            return
        self.window.removeControl(self._demolabel)
        self._demolabel = None
        self.log('hide', 0)

    def _close(self):
        self.hide()
        self.log('closed', 0)

    def __del__(self):
        self.hide()
        self.log('destroy', 0)
Exemple #7
0
 def __init__(self):
     self.window_cls = Window(10000)  # Kodi home window
     # If you use multiple Kodi profiles you need to distinguish the property of current profile
     self.prop_nf_service_status = g.py2_encode(
         'nf_service_status_' + get_current_kodi_profile_name())
     self.controller = None
     self.library_updater = None
     self.settings_monitor = None
Exemple #8
0
    def onNotification(self, sender, method, data):
        if method == 'Player.OnPlay':
            from xbmcgui import Window, getCurrentWindowId
            window_id = getCurrentWindowId()

            if getInfoLabel('Container.FolderPath').startswith(
                    self.addon_path):
                self.start_tracking = True
                asset_id = Window(window_id).getProperty('joyn_video_id')
                if asset_id is not None and len(asset_id) != 0:
                    self.asset_id = asset_id
                    xbmc_helper().log_debug('Track asset : {}', asset_id)
            else:
                self.reset_tracking()
            Window(window_id).clearProperty('joyn_video_id')

        elif method == 'Player.OnStop':
            if self.start_tracking is True and self.asset_id is not None and self.last_tracked_position is not None and self.duration is not None:
                try:
                    if lib_joyn().get_auth_token(force_reload_cache=True).get(
                            'has_account', False) is True:
                        xbmc_helper().log_debug(
                            'Set resume - asset: {} - pos {}', self.asset_id,
                            self.last_tracked_position)
                        if self.last_tracked_position >= (
                                self.duration - xbmc_helper().get_int_setting(
                                    'del_resume_pos_secs')):
                            lib_joyn().get_graphql_response(
                                'SET_RESUME_POSITION', {
                                    'assetId': self.asset_id,
                                    'position': 0
                                })
                        else:
                            lib_joyn().get_graphql_response(
                                'SET_RESUME_POSITION', {
                                    'assetId': self.asset_id,
                                    'position': self.last_tracked_position
                                })
                except Exception as e:
                    xbmc_helper().log_error(
                        'Exception when setting resume postion: {}', e)
                    pass

            # delete local mpd file - if exists
            xbmc_helper().log_debug('last played file: {}',
                                    self.last_played_file)
            if self.start_tracking is True and self.last_played_file is not None and (
                    self.last_played_file.startswith('/') or
                ((getCondVisibility(' System.Platform.Windows')
                  or getCondVisibility('System.Platform.UWP'))
                 and self.last_played_file[1:3] == ':/')):
                filename = self.last_played_file.split('/')[-1]
                xbmc_helper().log_debug('Delete local mpd file: {}',
                                        self.last_played_file)
                xbmc_helper().del_data(filename, 'TEMP_DIR')

            self.reset_tracking()
Exemple #9
0
    def run(self):
        okno = None
        try:
            okno = Window(xbmcgui.getCurrentWindowId())
            okno.setProperty('RSS.count', '0')
        except:
            pass
        unread_c = 0
        for set in self.sets:
            self.reader.ReadSet(set, True)
            for src in set.sources:
                for channel in src.channels:
                    unread_c += channel.unread_count
                    for item in channel.items:
                        if already_read.count(item.link) > 0:
                            item.read = True
                        else:
                            channel.unread_count += 1
                            channel.read = False

        log('All sets read from cache')

        if ui != None and ui.isReady: ui.updateChannelList()

        changes = False

        next_update = -1

        for set in self.sets:
            for source in set.sources:
                last_checking = time.time() - source.lastupdate
                interval = int(source.updateinterval) * 60
                if last_checking > interval:
                    for src in set.sources:
                        for channel in src.channels:
                            unread_c -= channel.unread_count

                    self.reader.ReadSource(source, False)
                    changes = True
                    for src in set.sources:
                        for channel in src.channels:
                            unread_c += channel.unread_count
                            for item in channel.items:
                                if already_read.count(item.link) > 0:
                                    item.read = True
                                else:
                                    channel.unread_count += 1
                                    channel.read = False

                    if next_update == -1 or interval < next_update:
                        next_update = interval
                elif next_update == -1 or interval - last_checking < next_update:
                    next_update = interval - last_checking

        if changes:
            log('Sets updated from URL')
            if ui != None and ui.isReady: ui.updateChannelList()
    def run(self):
        okno = None
        try:
            okno = Window(xbmcgui.getCurrentWindowId())
            okno.setProperty('RSS.count', '0');
        except:
            pass
        unread_c = 0
        for set in self.sets:
            self.reader.ReadSet(set, True)
            for src in set.sources:
                for channel in src.channels:
                    unread_c += channel.unread_count
                    for item in channel.items:
                        if already_read.count(item.link) > 0:
                            item.read = True
                        else:
                            channel.unread_count += 1
                            channel.read = False

        log('All sets read from cache')  
          
        if ui != None and ui.isReady: ui.updateChannelList()
        
        changes = False
        
        next_update = -1
        
        for set in self.sets:
            for source in set.sources:
                last_checking = time.time() - source.lastupdate
                interval = int(source.updateinterval) * 60
                if last_checking > interval:
                    for src in set.sources:
                        for channel in src.channels:
                            unread_c -= channel.unread_count
                            
                    self.reader.ReadSource(source, False)
                    changes = True
                    for src in set.sources:
                        for channel in src.channels:
                            unread_c += channel.unread_count
                            for item in channel.items:
                                if already_read.count(item.link) > 0:
                                    item.read = True
                                else:
                                    channel.unread_count += 1
                                    channel.read = False
                    
                    if next_update == -1 or interval < next_update:
                        next_update = interval
                elif next_update == -1 or interval - last_checking < next_update:
                    next_update = interval - last_checking
        
        if changes:
            log('Sets updated from URL')    
            if ui != None and ui.isReady: ui.updateChannelList()
Exemple #11
0
 def __init__(self):  # pylint: disable=super-on-old-class
     super(ProgressManager, self).__init__()
     self.event_data = {}
     self.is_event_start_sent = False
     self.last_tick_count = 0
     self.tick_elapsed = 0
     self.last_player_state = {}
     self.is_player_in_pause = False
     self.lock_events = False
     self.window_cls = Window(10000)  # Kodi home window
def run(argv):
    # pylint: disable=broad-except,ungrouped-imports
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    g.init_globals(argv)

    reset_log_level_global_var()
    info('Started (Version {})'.format(g.VERSION))
    info('URL is {}'.format(g.URL))
    success = True

    window_cls = Window(10000)  # Kodi home window

    # If you use multiple Kodi profiles you need to distinguish the property of current profile
    prop_nf_service_status = g.py2_encode('nf_service_status_' +
                                          get_current_kodi_profile_name())
    is_external_call = _check_addon_external_call(window_cls,
                                                  prop_nf_service_status)

    if window_cls.getProperty(prop_nf_service_status) != 'running':
        if not is_external_call:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
        success = False

    if success:
        try:
            if _check_valid_credentials():
                if g.IS_ADDON_FIRSTRUN:
                    if check_addon_upgrade():
                        from resources.lib.config_wizard import run_addon_configuration
                        run_addon_configuration()
                if not is_external_call:
                    update_cache_videoid_runtime(window_cls)
                route([part for part in g.PATH.split('/') if part])
            else:
                success = False
        except BackendNotReady:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
            success = False
        except Exception as exc:
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(traceback.format_exc())
            show_addon_error_info(exc)
            success = False

    if not success:
        _handle_endofdirectory()

    g.CACHE.commit()
    log_time_trace()
 def shutdown(self):
     """
     Stop the background services
     """
     from xbmcgui import Window
     window_cls = Window(10000)
     window_cls.setProperty('nf_service_status', 'stopped')
     for server in self.SERVERS:
         server['instance'].server_close()
         server['instance'].shutdown()
         server['instance'] = None
         server['thread'].join()
         server['thread'] = None
     info('Stopped MSL Service')
Exemple #14
0
def main():
    """
    Grabs kodi_id and kodi_type and sends a request to our main python instance
    that context menu needs to be displayed
    """
    window = Window(10000)
    kodi_id = listitem.getVideoInfoTag().getDbId()
    if kodi_id == -1:
        # There is no getDbId() method for getMusicInfoTag
        # YET TO BE IMPLEMENTED - lookup ID using path
        kodi_id = listitem.getMusicInfoTag().getURL()
    kodi_type = _get_kodi_type()
    args = {'kodi_id': kodi_id, 'kodi_type': kodi_type}
    while window.getProperty('plex_command'):
        sleep(20)
    window.setProperty('plex_command', 'CONTEXT_menu?%s' % urlencode(args))
Exemple #15
0
class Main:
    # grab the 1115 or 1116 window
    try:
        wid = getCurrentWindowDialogId()
    except:
        wid = 11115
    WINDOW = Window(wid)

    def __init__(self):
        self._clear_properties()
        self._set_properties()

    def _clear_properties(self):
        # Clear Feeds Properties
        for count in range(1, 31):
            self.WINDOW.clearProperty("feeds.%d.name" % (count + 1, ))
            self.WINDOW.clearProperty("feeds.%d.path" % (count + 1, ))

    def _set_properties(self):
        # recupere les rss existant de l'user
        for count, feeds in enumerate(
                sorted(parse_xml().items(), key=lambda x: str(x[0].zfill(3)))):
            idset, feeds = feeds
            # join par une virgule les liens. on va utiliser une virgule comme ceci " , " pour faire la différence des autre virgule dans les liens
            lien = " , ".join(feed["feed"] for feed in feeds["feed"])
            #print "feeds.%d.path" % ( count + 1 ), lien
            # name est le nom du site, car l'attribut name est pas supporter pour le moment dans le rssfeeds.xml
            name = " / ".join(set(findall('http://(.*?)/', lien)))
            #print "feeds.%d.name" % ( count + 1 ), name

            # set window properties
            self.WINDOW.setProperty("feeds.%d.name" % (count + 1, ), name)
            self.WINDOW.setProperty("feeds.%d.path" % (count + 1, ), lien)
def get_property(key, default=None, window_id=10000):
    """Get a Window property"""
    from xbmcgui import Window
    value = to_unicode(Window(window_id).getProperty(key))
    if value == '' and default is not None:
        return default
    return value
Exemple #17
0
    def maybe_stop_current(self):
        """ If there is a video playing, it will capture the source and current playback time """
        if settings.getSetting_bool('resume'):
            player = xbmc.Player()
            if player.isPlaying():
                Window(10000).setProperty('SR_resumeTime',
                                          str(player.getTime()))
                Window(10000).setProperty('SR_previousFile',
                                          player.getPlayingFile())
                player.stop()
                xbmc.executebuiltin(
                    'PlayerControl(Stop)'
                )  # Because player.stop() was losing the player and didn't work *sad face*

            else:
                Window(10000).clearProperty('SR_resumeTime')
                Window(10000).clearProperty('SR_previousFile')
def run(argv):
    # pylint: disable=broad-except,ungrouped-imports
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    g.init_globals(argv)

    reset_log_level_global_var()
    info('Started (Version {})'.format(g.VERSION))
    info('URL is {}'.format(g.URL))
    success = True

    window_cls = Window(10000)
    is_widget_skin_call = _skin_widget_call(window_cls)

    if window_cls.getProperty('nf_service_status') != 'running':
        if not is_widget_skin_call:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
        success = False

    if success:
        try:
            if _check_valid_credentials():
                check_addon_upgrade()
                g.initial_addon_configuration()
                route([part for part in g.PATH.split('/') if part])
            else:
                success = False
        except BackendNotReady:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
            success = False
        except Exception as exc:
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(traceback.format_exc())
            show_addon_error_info(exc)
            success = False

    if not success:
        _handle_endofdirectory()

    g.CACHE.commit()
    log_time_trace()
    def run(self):
        """Main loop. Runs until xbmc.Monitor requests abort"""
        # pylint: disable=broad-except
        try:
            self.start_services()
        except Exception as exc:
            from xbmcgui import Window
            window_cls = Window(10000)
            window_cls.setProperty('nf_service_status', 'stopped')
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(traceback.format_exc())
            show_addon_error_info(exc)
            return

        while not self.controller.abortRequested():
            if self._tick_and_wait_for_abort():
                break
        self.shutdown()
Exemple #20
0
 def reset(self):
     ''' Reinitializes monitor settings '''
     Window(10000).setProperty('SR_monitor', '1')
     self.dismissed_time = [0, 0, 0, 0, 0, 0, 0]
     self._dismissed_behavior = settings.getSetting_int(
         'dismissed_behavior'
     )  #0 - All dismissed, 1 - Just the window itself
     self._dismissed_duration = settings.getSetting_int(
         'dismissed_duration')
     self._preview_disabled_window_id = settings.getDisabledWindowIds()
Exemple #21
0
 def __init__(self):
     super(AMVideoEvents, self).__init__()
     self.event_data = {}
     self.videoid = None
     self.is_event_start_sent = False
     self.last_tick_count = 0
     self.tick_elapsed = 0
     self.is_player_in_pause = False
     self.lock_events = False
     self.allow_request_update_lolomo = False
     self.window_cls = Window(10000)  # Kodi home window
Exemple #22
0
    def maybe_resume_previous(self):
        """ If a video was playing previously, it will restart it at the resume time """
        if settings.getSetting_bool('resume'):
            try:
                previous_file = Window(10000).getProperty('SR_previousFile')
            except:
                previous_file = ''

            if previous_file != '':
                resume_time = float(Window(10000).getProperty('SR_resumeTime'))
                Window(10000).clearProperty('SR_resumeTime')
                Window(10000).clearProperty('SR_previousFile')

                resume_time_adjustment = settings.getSetting_int('resume_time')
                resume_time_str = "{0:.1f}".format(resume_time -
                                                   resume_time_adjustment)
                listitem = ListItem()
                listitem.setProperty('StartOffset', resume_time_str)

                player = xbmc.Player()
                player.play(previous_file, listitem)
Exemple #23
0
def run(argv):
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    G.init_globals(argv)

    LOG.info('Started (Version {})'.format(G.VERSION_RAW))
    LOG.info('URL is {}'.format(G.URL))
    success = True

    window_cls = Window(10000)  # Kodi home window

    # If you use multiple Kodi profiles you need to distinguish the property of current profile
    prop_nf_service_status = G.py2_encode('nf_service_status_' +
                                          get_current_kodi_profile_name())
    is_external_call = _check_addon_external_call(window_cls,
                                                  prop_nf_service_status)
    service_status = _get_service_status(window_cls, prop_nf_service_status)

    if service_status.get('status') != 'running':
        if not is_external_call:
            if service_status.get('status') == 'error':
                # The services are not started due to an error exception
                from resources.lib.kodi.ui import show_error_info
                show_error_info(
                    get_local_string(30105),
                    get_local_string(30240).format(
                        service_status.get('message')), False, False)
            else:
                # The services are not started yet
                from resources.lib.kodi.ui import show_backend_not_ready
                show_backend_not_ready()
        success = False
    if success:
        cancel_playback = False
        pathitems = [part for part in G.REQUEST_PATH.split('/') if part]
        if G.IS_ADDON_FIRSTRUN:
            is_first_run_install, cancel_playback = check_addon_upgrade()
            if is_first_run_install:
                from resources.lib.config_wizard import run_addon_configuration
                run_addon_configuration()
        if cancel_playback and G.MODE_PLAY in pathitems[:1]:
            # Temporary for migration library STRM to new format. todo: to be removed in future releases
            # When a user do the add-on upgrade, the first time that the add-on will be opened will be executed
            # the library migration. But if a user instead to open the add-on, try to play a video from Kodi
            # library, Kodi will open the old STRM file because the migration is executed after.
            success = False
        else:
            success = route(pathitems)
    if not success:
        from xbmcplugin import endOfDirectory
        endOfDirectory(handle=G.PLUGIN_HANDLE, succeeded=False)
    LOG.log_time_trace()
 def start_services(self):
     """
     Start the background services
     """
     from resources.lib.services.playback.controller import PlaybackController
     from resources.lib.services.library_updater import LibraryUpdateService
     from resources.lib.services.settings_monitor import SettingsMonitor
     for server in self.SERVERS:
         server['instance'].server_activate()
         server['instance'].timeout = 1
         server['thread'].start()
         info('[{}] Thread started'.format(server['name']))
     self.controller = PlaybackController()
     self.library_updater = LibraryUpdateService()
     self.settings_monitor = SettingsMonitor()
     # Mark the service as active
     from xbmcgui import Window
     window_cls = Window(10000)
     window_cls.setProperty('nf_service_status', 'running')
     if not g.ADDON.getSettingBool('disable_startup_notification'):
         from resources.lib.kodi.ui import show_notification
         show_notification(get_local_string(30110))
    def _mode_watch(self):
        # type: () -> None

        channel_name = self._params.get("channel")
        if not channel_name:
            raise BouyguesTVUnknownChannelException(channel_name)

        video_url = self._api.get_channel_stream_url(channel_name)
        if not video_url:
            raise BouyguesTVException(
                "Unable to retrieve stream for channel {}".format(
                    channel_name))

        xbmcplugin.setResolvedUrl(
            self._handle,
            True,
            ListItem(path=video_url, offscreen=True),
        )

        Window(10000).setProperty(self._ACCESS_TOKEN_PROPERTY,
                                  self._api.access_token or "")
        Window(10000).setProperty(self._ID_TOKEN_PROPERTY, self._api.id_token
                                  or "")
 def __init__(self):
     """Do nothing on constructing the object"""
     # The class initialization (GlobalVariables) will only take place at the first initialization of this module
     # on subsequent add-on invocations (invoked by reuseLanguageInvoker) will have no effect.
     # Define here also any other variables necessary for the correct loading of the other project modules
     self.WND_KODI_HOME = Window(10000)  # Kodi home window
     self.IS_ADDON_FIRSTRUN = None
     self.ADDON = None
     self.ADDON_DATA_PATH = None
     self.DATA_PATH = None
     self.CACHE_MANAGEMENT = None
     self.CACHE_TTL = None
     self.CACHE_MYLIST_TTL = None
     self.CACHE_METADATA_TTL = None
	def set_folder(self, list_items, pluginurl, pluginhandle, pluginquery, folder_type, title=None):

		folder_defs = CONST['FOLDERS'].get(folder_type)
		old_pluginurl = getInfoLabel('Container.FolderPath')
		old_postion = getInfoLabel('Container.CurrentItem')

		addDirectoryItems(pluginhandle, list_items, len(list_items))

		if title is not None:
			setPluginCategory(pluginhandle, title)

		if 'content_type' in folder_defs.keys():
			self.log_debug('set_folder: set content_type: {}', folder_defs['content_type'])
			setContent(pluginhandle, folder_defs['content_type'])
		endOfDirectory(handle=pluginhandle,
		               cacheToDisc=(folder_defs.get('cacheable', False) and (self.get_bool_setting('disable_foldercache') is False)))

		self.wait_for_infolabel('Container.FolderPath', compat._format('{}{}', pluginurl, pluginquery))

		if 'view_mode' in folder_defs.keys():
			self.set_view_mode(folder_defs['view_mode'])

		if 'sort' in folder_defs.keys():
			self.set_folder_sort(folder_defs['sort'])

		# reset the postion to the last "known" if it is gt 1, if pluginurls matching -> likely to be a 'refresh'
		if getInfoLabel('Container.FolderPath') == old_pluginurl and old_postion.isdigit() and int(old_postion) > 1:
			from xbmcgui import Window, getCurrentWindowId, getCurrentWindowDialogId

			# wait untl all Dialogs are closed; 10099 => WINDOW_DIALOG_POINTER => smallest dialog_id; max 500 msecs
			dialog_wait_counter = 0
			while dialog_wait_counter <= 100 and getCurrentWindowDialogId() >= 10099:
				xbmc_sleep(5)
				dialog_wait_counter += 1
			self.log_debug('waited {} msecs for all dialogs to be closed', (dialog_wait_counter * 5))

			self.log_debug('FolderPath old pos {} ', old_postion)
			focus_id = Window(getCurrentWindowId()).getFocusId()
			set_postion = old_postion

			cmd = compat._format('Control.SetFocus({},{})', focus_id, set_postion)
			executebuiltin(cmd)
			self.log_debug('set current pos executebuiltin({})', cmd)

			# wait for the correct postion to be applied; max 500 msecs
			self.wait_for_infolabel('Container.CurrentItem', old_postion, cycles=100)
 def run(self):
     LOG.info("----====# Starting Special Monitor #====----")
     # "Start from beginning", "Play from beginning"
     strings = (getLocalizedString(12021), getLocalizedString(12023))
     while not self.stopped():
         if (getCondVisibility('Window.IsVisible(DialogContextMenu.xml)')
                 and getInfoLabel('Control.GetLabel(1002)') in strings):
             # Remember that the item IS indeed resumable
             control = int(Window(10106).getFocusId())
             if control == 1002:
                 # Start from beginning
                 state.RESUME_PLAYBACK = False
             elif control == 1001:
                 state.RESUME_PLAYBACK = True
             else:
                 # User chose something else from the context menu
                 state.RESUME_PLAYBACK = False
         sleep(200)
     LOG.info("#====---- Special Monitor Stopped ----====#")
 def run(self):
     LOG.info("----====# Starting Special Monitor #====----")
     # "Start from beginning", "Play from beginning"
     strings = (utils.try_encode(utils.lang(12021)),
                utils.try_encode(utils.lang(12023)))
     while not self.stopped():
         if xbmc.getCondVisibility(
                 'Window.IsVisible(DialogContextMenu.xml)'):
             if xbmc.getInfoLabel('Control.GetLabel(1002)') in strings:
                 # Remember that the item IS indeed resumable
                 control = int(Window(10106).getFocusId())
                 state.RESUME_PLAYBACK = True if control == 1001 else False
             else:
                 # Different context menu is displayed
                 state.RESUME_PLAYBACK = False
         if xbmc.getCondVisibility('Window.IsVisible(MyVideoNav.xml)'):
             path = xbmc.getInfoLabel('container.folderpath')
             if (isinstance(path, str)
                     and path.startswith('special://profile/playlists')):
                 pass
                 # TODO: start polling PMS for playlist changes
                 # Optionally: poll PMS continuously with custom intervall
         xbmc.sleep(200)
     LOG.info("#====---- Special Monitor Stopped ----====#")
    try:
        #On essaye d'ouvrir le fichier avec les news parser
        pkl_file = open(('%s-headlines' % RssFeeds), 'rb')
        headlines = pickle.load(pkl_file)
        pkl_file.close()
    except:
        #Si il n'est pas encore récupéré, on crée une news avec INDISPONIBLE
        headlines.append(('Indisponible', 'Indisponible', 
                          'Indisponible','Indisponible',
                          'Indisponible','Indisponible',
                          'Indisponible','Indisponible', 'Indisponible'))

debug("Feed= %s " % RssFeeds)

#On récupère l'ID de la fenêtre de skin qui à lancer le script
okno = Window(xbmcgui.getCurrentWindowId())
#Nb de news dans le flux
NbNews = len(headlines)
#Si il est > à la limite demandée, on ne récupére que limit
if limit > NbNews: limit = NbNews

for i in range(0, limit):
    #On défini les Properties d'apres headlines
    #0 => title, 1 => date, 2=> description, 
    #3 => content_type, 4 =>img_name,
    #5 => link_video, 6 => NoNews
    #7 => ImageCount, 8 => SlideShowable

    debug('%sRSS.%s.Title' % (prefix,i))
    okno.setProperty('%sRSS.%s.Title' % (prefix,i) , headlines[i][0] )
    okno.setProperty('%sRSS.%s.Date' % (prefix,i) , headlines[i][1])
RSSid = -1
prefix = ''

for arg in sys.argv:
    param = arg.lower()
    if 'prefix=' in param:
        prefix = param.replace('prefix=', '')
        if not prefix.endswith('.'):
            prefix = prefix + '.'
    elif 'id=' in param:
        RSSid = param.replace('id=', '') 
        

if RSSid > -1:
    okno = Window(xbmcgui.getCurrentWindowId())
    
    okno.setProperty('RSS.Title', okno.getProperty('%sRSS.%s.Title' % (prefix, RSSid)  ))
    okno.setProperty('RSS.Desc', okno.getProperty('%sRSS.%s.Desc' % (prefix, RSSid)  ))
    okno.setProperty('RSS.Image', okno.getProperty('%sRSS.%s.Image' % (prefix, RSSid)  ))
    
    okno.setProperty('RSS.Date', okno.getProperty('%sRSS.%s.Date' % (prefix, RSSid)  ))
    okno.setProperty('RSS.Channel', okno.getProperty('%sRSS.%s.Channel' % (prefix, RSSid)))
    okno.setProperty('RSS.Media', okno.getProperty('%sRSS.%s.Media' % (prefix, RSSid)))
    okno.setProperty('RSS.MultiImagePath', okno.getProperty('%sRSS.%s.MultiImagePath' % (prefix, RSSid)))
    okno.setProperty('RSS.SlideShowable', okno.getProperty('%sRSS.%s.SlideShowable' % (prefix, RSSid)))
    okno.setProperty('RSS.ID',  RSSid)
    
    i_count = okno.getProperty('%sRSS.%s.ImageCount' % (prefix, RSSid))
    
    okno.setProperty('RSS.ImageCount', i_count)
Exemple #32
0
ImgBoxDisk = None
ImgBoxDisk = None
filename = xbmc.translatePath("special://profile/addon_data/service.diskfree/diskfree.png")
#filename = 'special://home/henri/.xbmc/scripts/test.png'
ImgBoxDiskId = None
ImgBoxDiskId = None
#start_time = time.time() 
start_time = 0 
re_added_control = False

#Recupère les arguments envoyés par le skin qui a lancé le script
for arg in sys.argv:

    param = str(arg).lower()
    debug("param = %s " % param)
    if 'disk=' in param:
        disk = param.replace('disk=', '')
#On récupère l'ID de la fenêtre de skin qui à lancer le script
okno = Window(xbmcgui.getCurrentWindowId())

#On recupere les parametres des disques
#time = time.time()
freespace = freespace_disk('/home/')
totalspace = totalspace_disk('/home')
diskfree = ('%iGB') % (((freespace / 1024) / 1024) / 1024)
freespace = (((freespace / 1024) / 1024) / 1024)
totalspace = (((totalspace / 1024) / 1024) / 1024)
percent = totalspace and (totalspace - freespace) * 1.0 / totalspace or 0.0
debug( "f = %s, t = %s Pou = %s " % (freespace,totalspace,percent))
okno.setProperty('DISK' , '%s Go' % freespace )
Exemple #33
0
def clear_property(key, window_id=10000):
    """Clear a Window property"""
    return Window(window_id).clearProperty(key)
Exemple #34
0
def set_property(key, value, window_id=10000):
    """Set a Window property"""
    return Window(window_id).setProperty(key, from_unicode(str(value)))
def Read(sets, reader):
    okno = None
    try:
        if isWindow:
            if ID == -1:
                okno = Window(xbmcgui.getCurrentWindowId())
                print ' >> WINDOW ID = %i' % xbmcgui.getCurrentWindowId()
            else:
                okno = Window(ID)
        else:
            if ID == -1:
                okno = WindowDialog(xbmcgui.getCurrentWindowDialogId())
            else:
                okno = WindowDialog(ID)
            
        okno.setProperty('RSS.count', '0');
    except:
        pass
    unread_c = 0
    for set in sets:
        reader.ReadSet(set, True)
        for src in set.sources:
            for channel in src.channels:
                unread_c += channel.unread_count
                for item in channel.items:
                    if already_read.count(item.link) > 0:
                        item.read = True
                    else:
                        channel.unread_count += 1
                        channel.read = False

    log('All sets read from cache')  
      
    changes = False
    
    next_update = -1
    
    for set in sets:
        for source in set.sources:
            last_checking = time.time() - source.lastupdate
            interval = int(source.updateinterval) * 60
            if last_checking > interval:
                for src in set.sources:
                    for channel in src.channels:
                        unread_c -= channel.unread_count
                        
                reader.ReadSource(source, False)
                changes = True
                for src in set.sources:
                    for channel in src.channels:
                        unread_c += channel.unread_count
                        for item in channel.items:
                            if already_read.count(item.link) > 0:
                                item.read = True
                            else:
                                channel.unread_count += 1
                                channel.read = False
                
                if next_update == -1 or interval < next_update:
                    next_update = interval
            elif next_update == -1 or interval - last_checking < next_update:
                next_update = interval - last_checking
    
    if changes:
        log('Sets updated from URL')    

#items = sorted(self.items, cmp=DateCompare, reverse = self.sortdesc )
    try:
        
        okno.setProperty( "unread_rss", str(unread_c) )
        setting_script = xbmc.translatePath('special://home/addons/script.rssclient/set_properties.py')
        okno.setProperty('SettingScript', setting_script)
        itemList = []
        
        
        for set in sets:
            for source in set.sources:
                for channel in source.channels:
                    for item in channel.items:
                        itemList.append(item)
        
        c = 1
        items = sorted(itemList, cmp=DateCompare, reverse = False )
        
        for item in items:
            if c <= limit:
                okno.setProperty('%sRSS.%d.Title' % (prefix, c), item.title)
                
                okno.setProperty('%sRSS.%d.Desc' % (prefix, c), cleanText(item.description))
                
                if len(item.image) > 0:
                    okno.setProperty('%sRSS.%d.Image' % (prefix, c), item.image[0])
                else:
                    okno.setProperty('%sRSS.%d.Image' % (prefix, c), '')
                
                okno.setProperty('%sRSS.%d.ImageCount' % (prefix, c), str(len(item.image)) )
                
                
                okno.setProperty('%sRSS.%d.SlideShowable' % (prefix, c), (( (imageCachingEnabled and len(item.image) > 1) and ['true'] or ['false'])[0]))
                okno.setProperty('%sRSS.%d.MultiImagePath' % (prefix, c), item.multiimagepath)
                
                i = 1
                sep_images = ''
                for image in item.image:
                    okno.setProperty('%sRSS.%d.Image.%d' % (prefix, c,i), image)
                    
                    if len(sep_images) > 0:
                        sep_images = sep_images + ';'
                    sep_images = sep_images + image
                    
                    i = i + 1
                
                okno.setProperty('%sRSS.%d.MultiImages' % (prefix, c), sep_images)
                
                if len(item.video) > 1:
                    okno.setProperty('%sRSS.%d.Media' % (prefix, c), item.video)
                else:
                    okno.setProperty('%sRSS.%d.Media' % (prefix, c), '')
                
                
                okno.setProperty('%sRSS.%d.Date' % (prefix, c), item.date.replace(',', '.'))
                
                if item.channel != None:
                    okno.setProperty('%sRSS.%d.Channel' % (prefix, c), item.channel.title)

                c = c + 1;
                
                okno.setProperty('%sRSS.count' % prefix, str(c));
    except:
        pass

    if alarmEnabled and next_update > -1:
        alarmhash = xbmc.getCacheThumbName(args + str(time.localtime())).replace('.tbn', '')
        napis = 'AlarmClock(RSS_CHECK_%s,XBMC.RunScript(script.rssclient%s),%d,True)' % (alarmhash, args, ((next_update+60)  / 60.0))  
        log('Refresh in %d minutes' % ((next_update+60)  / 60.0))
        xbmc.executebuiltin(napis)
Exemple #36
0
import xbmc
from xbmcgui import Window
from urllib import quote_plus
import re
# limit number to
RECENT_NUMBER = 4
# grab the home window
WINDOW = Window( 10000 )
# sql statements
sql_movies = "select * from movieview order by idMovie desc limit %d" % ( RECENT_NUMBER, )
sql_episodes = "select * from episodeview order by idepisode desc limit %d" % ( RECENT_NUMBER, )
#sql_tvshowlinkepisode = "select idshow from tvshowlinkepisode where idEpisode=%u" % ( fields[ 13 ], )
# format our records start and end
xbmc.executehttpapi( "SetResponseFormat(OpenRecord,%s)" % ( "<record>", ) )
xbmc.executehttpapi( "SetResponseFormat(CloseRecord,%s)" % ( "</record>", ) )
# query the database
movies_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_movies ), )
episodes_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_episodes ), )
# separate the records
movies = re.findall( "<record>(.+?)</record>", movies_xml, re.DOTALL )
episodes = re.findall( "<record>(.+?)</record>", episodes_xml, re.DOTALL )
# enumerate thru our records and set our properties
for count, movie in enumerate( movies ):
    # separate individual fields
    fields = re.findall( "<field>(.*?)</field>", movie, re.DOTALL )
    # set title
    WINDOW.setProperty( "LatestMovie.%d.Label" % ( count + 1, ), fields[ 1 ] )
    # set year
    WINDOW.setProperty( "LatestMovie.%d.Label2" % ( count + 1, ), fields[ 8 ] )
    # set running time (uncomment below if you want running time for label2)
    #WINDOW.setProperty( "LatestMovie.%d.Label2" % ( count + 1, ), fields[ 12 ] )