Python xbmc.Monitor() Examples

The following are 30 code examples of xbmc.Monitor(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xbmc , or try the search function .
Example #1
Source File: kodi_monitor.py    From script.skin.helper.service with GNU General Public License v2.0 6 votes vote down vote up
def show_info_panel(self):
        '''feature to auto show the OSD infopanel for X seconds'''
        try:
            sec_to_display = int(xbmc.getInfoLabel("Skin.String(SkinHelper.ShowInfoAtPlaybackStart)"))
        except Exception:
            return

        if sec_to_display > 0 and not self.infopanelshown:
            retries = 0
            log_msg("Show OSD Infopanel - number of seconds: %s" % sec_to_display)
            self.infopanelshown = True
            if self.win.getProperty("VideoScreensaverRunning") != "true":
                while retries != 50 and getCondVisibility("!Player.ShowInfo"):
                    xbmc.sleep(100)
                    if getCondVisibility("!Player.ShowInfo + Window.IsActive(fullscreenvideo)"):
                        xbmc.executebuiltin('Action(info)')
                    retries += 1
                # close info again after given amount of time
                xbmc.Monitor().waitForAbort(sec_to_display)
                if getCondVisibility("Player.ShowInfo + Window.IsActive(fullscreenvideo)"):
                    xbmc.executebuiltin('Action(info)') 
Example #2
Source File: artworkprocessor.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def __init__(self, monitor=None):
        self.monitor = monitor or xbmc.Monitor()
        self.language = None
        self.autolanguages = None
        self.progress = xbmcgui.DialogProgressBG()
        self.visible = False
        self.freshstart = "0"
        self.processed = ProcessedItems()
        self.gatherer = None
        self.downloader = None
        self.chunkcount = 1
        self.currentchunk = 0
        self.debug = False
        self.localmode = False
        settings.update_settings()
        mediatypes.update_settings() 
Example #3
Source File: events_handler.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def run(self):
        """Monitor and process the event queue"""
        common.debug('[Event queue monitor] Thread started')
        monitor = xbmc.Monitor()

        while not monitor.abortRequested() and not self._stop_requested:
            try:
                # Take the first queued item
                event = self.queue_events.get_nowait()
                # Process the request
                continue_queue = self._process_event_request(event)
                if not continue_queue:
                    # Ban future requests from this event id
                    self.banned_events_ids += [event.get_event_id()]
            except queue.Empty:
                pass
            except Exception as exc:  # pylint: disable=broad-except
                common.error('[Event queue monitor] An error has occurred: {}', exc)
                import traceback
                common.error(g.py2_decode(traceback.format_exc(), 'latin-1'))
                self.clear_queue()
            monitor.waitForAbort(1) 
Example #4
Source File: koditidal2.py    From plugin.audio.tidal2 with GNU General Public License v3.0 6 votes vote down vote up
def get_album_json_thread(self):
        try:
            while not xbmc.Monitor().waitForAbort(timeout=0.01) and not self.abortAlbumThreads:
                try:
                    album_id = self.albumQueue.get_nowait()
                except:
                    break
                try:
                    self.get_album(album_id, withCache=False)
                except requests.HTTPError as e:
                    r = e.response
                    msg = _T(30505)
                    try:
                        msg = r.reason
                        msg = r.json().get('userMessage')
                    except:
                        pass
                    log('Error getting Album ID %s' % album_id, xbmc.LOGERROR)
                    if r.status_code == 429 and not self.abortAlbumThreads:
                        self.abortAlbumThreads = True
                        log('Too many requests. Aborting Workers ...', xbmc.LOGERROR)
                        self.albumQueue._init(9999)
                        xbmcgui.Dialog().notification(plugin.name, msg, xbmcgui.NOTIFICATION_ERROR)
        except Exception, e:
            traceback.print_exc() 
Example #5
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def precache_library(self):
        if not self.win.getProperty("Spotify.PreCachedItems"):
            monitor = xbmc.Monitor()
            self.win.setProperty("Spotify.PreCachedItems", "busy")
            userplaylists = self.get_user_playlists(self.userid)
            for playlist in userplaylists:
                self.get_playlist_details(playlist['owner']['id'], playlist["id"])
                if monitor.abortRequested():
                    return
            self.get_savedalbums()
            if monitor.abortRequested():
                return
            self.get_savedartists()
            if monitor.abortRequested():
                return
            self.get_saved_tracks()
            del monitor
            self.win.setProperty("Spotify.PreCachedItems", "done") 
Example #6
Source File: service.py    From plugin.git.browser with GNU General Public License v3.0 6 votes vote down vote up
def start(self):

		enable_updates
		class Monitor(xbmc.Monitor):
			def onSettingsChanged(self):
				global enable_updates
				enable_updates = kodi.get_setting('enable_updates') == 'true'
		monitor = Monitor()
		kodi.log("Service Starting...")


		if is_depricated:
			while not xbmc.abortRequested:
				kodi.sleep(1000)
				self.update()
		else:
			while not monitor.abortRequested():
				if monitor.waitForAbort(10):
					break
				self.update()

		self.shutdown() 
Example #7
Source File: library_updater.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def __init__(self):
        try:
            self.enabled = g.ADDON.getSettingInt('lib_auto_upd_mode') == 2
        except Exception:  # pylint: disable=broad-except
            # If settings.xml was not created yet, as at first service run
            # g.ADDON.getSettingInt('lib_auto_upd_mode') will thrown a TypeError
            # If any other error appears, we don't want the service to crash,
            # let's return None in all case
            self.enabled = False

        self.startidle = 0
        self.next_schedule = _compute_next_schedule()

        # Update library variables
        xbmc.Monitor.__init__(self)
        self.scan_in_progress = False
        self.scan_awaiting = False
        AddonSignals.registerSlot(
            g.ADDON.getAddonInfo('id'), common.Signals.LIBRARY_UPDATE_REQUESTED,
            self.update_kodi_library) 
Example #8
Source File: kodiaddon.py    From plugin.video.mediathekview with MIT License 6 votes vote down vote up
def register_instance(self, waittime=1):
        """
        Tries to register an instance. If another
        instance (thread/process) is active, the method
        locks until the process is terminated or a
        timeout occurs

        Args:
            waittime(int, optional): Timeout for registering
                the instance. Default is 1 second
        """
        if self.bad_instance():
            self.service.info(
                'Found other instance with id {}', self.instance_id)
            self.service.info(
                'Startup delayed by {} second(s) waiting the other instance to shut down', waittime)
            self.service.set_setting(self.setting_id, self.instance_id)
            xbmc.Monitor.waitForAbort(self, waittime)
        else:
            self.service.set_setting(self.setting_id, self.instance_id) 
Example #9
Source File: service.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        super(ServiceMonitor, self).__init__()
        self.property_basename = 'TMDbHelper.ListItem'
        self.kodimonitor = xbmc.Monitor()
        self.container = 'Container.'
        self.containeritem = 'ListItem.'
        self.exit = False
        self.cur_item = 0
        self.pre_item = 1
        self.pre_folder = None
        self.cur_folder = None
        self.properties = set()
        self.indxproperties = set()
        self.cron_job = CronJob(self.addon.getSettingInt('library_autoupdate_hour'))
        self.cron_job.setName('Cron Thread')
        self.playermonitor = None
        self.run_monitor() 
Example #10
Source File: kodiaddon.py    From plugin.video.mediathekview with MIT License 6 votes vote down vote up
def wait_for_abort(self, timeout=None):
        """
        Waits until Kodi is shutting down or a specified timeout
        has occurred. Returns `True` if Kodi is shutting down.

        Args:
            timeout(int, optional): Number of seconds to wait.
                If not specified, the funtion waits forever.
        """
        if timeout is None:
            # infinite wait
            while not self.abort_requested():
                if xbmc.Monitor.waitForAbort(self, 1):
                    return True
            return True
        else:
            for _ in range(timeout):
                if self.bad_instance() or xbmc.Monitor.waitForAbort(self, 1):
                    return True
            return self.bad_instance() 
Example #11
Source File: scoring_updates.py    From plugin.video.nhlgcl with GNU General Public License v2.0 6 votes vote down vote up
def startScoringUpdatesTEST():
    dialog = xbmcgui.Dialog()  
    title = "Score Notifications"  
    dialog.notification(title, 'Starting...', '', 5000, False)     
   
    wait = 5
    monitor = xbmc.Monitor()    

    while True:        
        xbmc.log("**************Running**********************")     

        if monitor.waitForAbort(wait):       
            xbmc.log("**************Abort Called**********************")     
            break

    sys.exit() 
Example #12
Source File: default.py    From script.tvtime with GNU General Public License v2.0 6 votes vote down vote up
def __init__ (self):
        xbmc.Player.__init__(self)
        log('Player - init')
        self.token = __addon__.getSetting('token')
        self.facebook = __addon__.getSetting('facebook')
        self.twitter = __addon__.getSetting('twitter')
        self.welcome = __addon__.getSetting('welcome')
        self.notifications = __addon__.getSetting('notifications')
        self.notif_during_playback = __addon__.getSetting('notif_during_playback')
        self.notif_scrobbling = __addon__.getSetting('notif_scrobbling')
        self.progress = __addon__.getSetting('progress')
        self.http = __addon__.getSetting('http')
        self.http_playing = False
        self.emotion = __addon__.getSetting('emotion')
        self.defaultemotion = __addon__.getSetting('defaultemotion')
        if self.token is '':
            log(__language__(32901))
            if self.notifications == 'true':
                notif(__language__(32901), time=2500)
            return
        self.user = self._GetUser()
        if not self.user.is_authenticated:
            return
        self._monitor = Monitor(action = self._reset)
        log('Player - monitor') 
Example #13
Source File: kodilibrary.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, dbtype=None, tvshowid=None, attempt_reconnect=False):
        self.dbtype = None
        self.database = None
        self.get_database(dbtype, tvshowid)

        if self.database or not dbtype or not attempt_reconnect:
            return

        # If we didn't get database retry in case Kodi was starting up
        retries = 0
        monitor = xbmc.Monitor()
        while not monitor.abortRequested() and not self.database and retries < 5:
            monitor.waitForAbort(1)
            self.get_database(dbtype, tvshowid)
            retries += 1
            utils.kodi_log(u'Unable to retrive {} KodiDB!\nAttempting to Reconnect - Attempt {}'.format(dbtype, retries), 1)
        if not self.database:
            utils.kodi_log(u'Getting KodiDB {} FAILED!'.format(dbtype), 1) 
Example #14
Source File: PostPlayInfo.py    From service.nextup.notification with GNU General Public License v2.0 6 votes vote down vote up
def countdown(self):
        xbmc.log("PostPlayInfo ->  countdown started timeout",level=xbmc.LOGNOTICE)
        while self.timeout and not xbmc.Monitor().waitForAbort(0.1):
            now = time.time()
            if self.timeout and now > self.timeout:
                self.timeout = None
                self.setProperty('countdown', '')
                if not self.showStillWatching and self.playAutomatically:
                    xbmc.executebuiltin('SendClick(,{0})'.format(self.NEXT_BUTTON_ID))
                    xbmc.log("PostPlayInfo ->  played next",level=xbmc.LOGNOTICE)
                    self.setAutoPlayed(True)
                    xbmcgui.Window(10000).setProperty("NextUpNotification.AutoPlayed","1")
                break
            elif self.timeout is not None:
                self.setProperty('countdown', str(min(15, int((self.timeout or now) - now))))
                xbmc.log("PostPlayInfo ->  increment countdown",level=xbmc.LOGNOTICE) 
Example #15
Source File: main_service.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.addon = xbmcaddon.Addon(id=ADDON_ID)
        self.win = xbmcgui.Window(10000)
        self.kodimonitor = xbmc.Monitor()
        self.spotty = Spotty()

        # spotipy and the webservice are always prestarted in the background
        # the auth key for spotipy will be set afterwards
        # the webserver is also used for the authentication callbacks from spotify api
        self.sp = spotipy.Spotify()
        self.connect_player = ConnectPlayer(sp=self.sp, spotty=self.spotty)

        self.proxy_runner = ProxyRunner(self.spotty)
        self.proxy_runner.start()
        webport = self.proxy_runner.get_port()
        log_msg('started webproxy at port {0}'.format(webport))

        # authenticate at startup
        self.renew_token()

        # start mainloop
        self.main_loop() 
Example #16
Source File: interface.py    From script.simkl with GNU General Public License v3.0 6 votes vote down vote up
def threaded(self):
        """ A loop threaded function, so you can do another things meanwhile """
        log("login thread start = {0}".format(self))
        cnt = 0
        while True:
            log("Still waiting... {0}".format(cnt))
            if self.pin_check(self.pin):
                self.success()
                self.close()
                break
            if self.canceled or cnt >= 220:
                notify(get_str(32031))
                break
            cnt += 1
            xbmc.Monitor().waitForAbort(4)

        log("Stop waiting") 
Example #17
Source File: osd.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        '''Main run loop for the background thread'''
        last_title = ""
        monitor = xbmc.Monitor()
        while not monitor.abortRequested() and self.active:
            cur_playback = self.get_curplayback()
            if cur_playback and cur_playback.get("item"):
                if cur_playback["shuffle_state"] != self.dialog.shuffle_state:
                    self.toggle_shuffle(cur_playback["shuffle_state"])
                if cur_playback["repeat_state"] != self.dialog.repeat_state:
                    self.set_repeat(cur_playback["repeat_state"])
                if cur_playback["is_playing"] != self.dialog.is_playing:
                    self.toggle_playstate(cur_playback["is_playing"])
                cur_title = cur_playback["item"]["uri"]
                if cur_title != last_title:
                    last_title = cur_title
                    trackdetails = cur_playback["item"]
                    self.update_info(trackdetails)
            monitor.waitForAbort(2)

        del monitor 
Example #18
Source File: service.py    From plugin.audio.tidal2 with GNU General Public License v3.0 5 votes vote down vote up
def onSettingsChanged(self):
        xbmc.Monitor.onSettingsChanged(self)
        if self.reloginNeeded():
            if xbmcgui.Dialog().yesno(heading=addon.getAddonInfo('name'), line1=_T(30256), line2=_T(30257)):
                xbmc.executebuiltin('XBMC.RunPlugin(plugin://%s/login)' % addon.getAddonInfo('id'))
            pass 
Example #19
Source File: service.py    From plugin.audio.tidal2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        xbmc.Monitor.__init__(self, *args, **kwargs)
        self.config = TidalConfig2()
        self.setLastSettings() 
Example #20
Source File: utils.py    From script.module.clouddrive.common with GNU General Public License v3.0 5 votes vote down vote up
def get_system_monitor():
        import xbmc
        return xbmc.Monitor() 
Example #21
Source File: kodi_monitor.py    From script.skin.helper.service with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        xbmc.Monitor.__init__(self)
        self.metadatautils = kwargs.get("metadatautils")
        self.win = kwargs.get("win")
        self.enable_animatedart = getCondVisibility("Skin.HasSetting(SkinHelper.EnableAnimatedPosters)") == 1 
Example #22
Source File: Player.py    From service.nextup.notification with GNU General Public License v2.0 5 votes vote down vote up
def displayRandomUnwatched(self):
        # Get the active player
        result = self.getNowPlaying()
        if 'result' in result:
            itemtype = result["result"]["item"]["type"]
            if itemtype == "episode":
                # playing an episode so find a random unwatched show from the same genre
                genres = result["result"]["item"]["genre"]
                if genres:
                    genretitle = genres[0]
                    self.logMsg("Looking up tvshow for genre " + genretitle, 2)
                    tvshow = utils.getJSON('VideoLibrary.GetTVShows', '{ "sort": { "order": "descending", "method": "random" }, "filter": {"and": [{"operator":"is", "field":"genre", "value":"%s"}, {"operator":"is", "field":"playcount", "value":"0"}]}, "properties": [ %s ],"limits":{"end":1} }' % (genretitle, self.fields_tvshows))
                if not tvshow:
                    self.logMsg("Looking up tvshow without genre", 2)
                    tvshow = utils.getJSON('VideoLibrary.GetTVShows', '{ "sort": { "order": "descending", "method": "random" }, "filter": {"and": [{"operator":"is", "field":"playcount", "value":"0"}]}, "properties": [ %s ],"limits":{"end":1} }' % self.fields_tvshows)
                self.logMsg("Got tvshow" + str(tvshow), 2)
                tvshowid = tvshow[0]["tvshowid"]
                if int(tvshowid) == -1:
                    tvshowid = self.showtitle_to_id(title=itemtitle)
                    self.logMsg("Fetched missing tvshowid " + str(tvshowid), 2)
                episode = utils.getJSON('VideoLibrary.GetEpisodes', '{ "tvshowid": %d, "sort": {"method":"episode"}, "filter": {"and": [ {"field": "playcount", "operator": "lessthan", "value":"1"}, {"field": "season", "operator": "greaterthan", "value": "0"} ]}, "properties": [ %s ], "limits":{"end":1}}' % (tvshowid, self.fields_episodes))

                if episode:
                    self.logMsg("Got details of next up episode %s" % str(episode), 2)
                    addonSettings = xbmcaddon.Addon(id='service.nextup.notification')
                    unwatchedPage = UnwatchedInfo("script-nextup-notification-UnwatchedInfo.xml",
                    addonSettings.getAddonInfo('path'), "default", "1080i")
                    unwatchedPage.setItem(episode[0])
                    self.logMsg("Calling display unwatched", 2)
                    unwatchedPage.show()
                    monitor = xbmc.Monitor()
                    monitor.waitForAbort(10)
                    self.logMsg("Calling close unwatched", 2)
                    unwatchedPage.close()
                    del monitor 
Example #23
Source File: service.py    From service.subtitles.subdivx with GNU General Public License v2.0 5 votes vote down vote up
def sleep(secs):
    """Sleeps efficiently for secs seconds"""
    if kodi_major_version > 13:
        xbmc.Monitor().waitForAbort(secs)
    else:
        xbmc.sleep(1000 * secs) 
Example #24
Source File: koditidal2.py    From plugin.audio.tidal2 with GNU General Public License v3.0 5 votes vote down vote up
def save_album_cache(self):
        numAlbums = 0
        if self._config.cache_albums:
            album_ids = self.albumJsonBuffer.keys()
            for album_id in album_ids:
                if xbmc.Monitor().waitForAbort(timeout=0.01):
                    break
                json_obj = self.albumJsonBuffer.get(album_id, None)
                if json_obj != None and 'id' in json_obj and not json_obj.get('_cached', False):
                    numAlbums += 1
                    self.metaCache.insertAlbumJson(json_obj)
            if numAlbums > 0:
                log('Wrote %s from %s Albums into the MetaCache' % (numAlbums, len(album_ids)))
        return numAlbums 
Example #25
Source File: default.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def __del__( self ):
        xbmc.log( "#=#=#=# Monitor destructed #=#=#=#" ) 
Example #26
Source File: kodi_monitor.py    From script.skin.helper.widgets with GNU General Public License v2.0 5 votes vote down vote up
def onNotification(self, sender, method, data):
        '''builtin function for the xbmc.Monitor class'''
        try:
            log_msg("Kodi_Monitor: sender %s - method: %s  - data: %s" % (sender, method, data))
            data = json.loads(data.decode('utf-8'))
            mediatype = ""
            if data and isinstance(data, dict):
                if data.get("item"):
                    mediatype = data["item"].get("type", "")
                elif data.get("type"):
                    mediatype = data["type"]

            if method == "VideoLibrary.OnUpdate":
                if not mediatype:
                    mediatype = self.last_mediatype # temp hack
                self.refresh_video_widgets(mediatype)

            if method == "AudioLibrary.OnUpdate":
                self.refresh_music_widgets(mediatype)

            if method == "Player.OnStop":
                self.last_mediatype = mediatype
                if mediatype in ["movie", "episode", "musicvideo"]:
                    if self.addon.getSetting("aggresive_refresh") == "true":
                        self.refresh_video_widgets(mediatype)

        except Exception as exc:
            log_msg("Exception in KodiMonitor: %s" % exc, xbmc.LOGERROR) 
Example #27
Source File: kodi_monitor.py    From script.skin.helper.widgets with GNU General Public License v2.0 5 votes vote down vote up
def onDatabaseUpdated(self, database):
        '''builtin function for the xbmc.Monitor class'''
        log_msg("Kodi_Monitor: %s database updated" % database)
        if database == "music":
            self.refresh_music_widgets("")
        else:
            self.refresh_video_widgets("") 
Example #28
Source File: kodi_monitor.py    From script.skin.helper.widgets with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        xbmc.Monitor.__init__(self)
        self.win = kwargs.get("win")
        self.addon = kwargs.get("addon") 
Example #29
Source File: events.py    From script.simkl with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, api, *args, **kwargs):
        xbmc.Monitor.__init__(self)

        self._api = api 
Example #30
Source File: servop.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def run():
    server_address = ('', 8781)
    httpd = HTTPServer(server_address, HandleRequests)
    monitor = xbmc.Monitor()
    httpd.timeout = 1
    while not monitor.abortRequested():
        try:
            httpd.handle_request()
        except Exception as e:
            logger.error(e)
    httpd.socket.close()