我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用xbmc.Monitor()。
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
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")
def get_kodishows(self, continuing_only=False): ''' get all tvshows in the kodi library and make sure we have a valid tvdb id returns combined tvshow details ''' kodi_series = self._get_kodi_json('VideoLibrary.GetTvShows', '{"properties": [ %s ] }' % KODI_TV_PROPS) all_series = [] monitor = xbmc.Monitor() if kodi_series and kodi_series.get("tvshows"): for kodi_serie in kodi_series["tvshows"]: if monitor.abortRequested() or self._close_called: break tvdb_details = self._parse_kodi_show(kodi_serie) if tvdb_details and "tvdb_status" in tvdb_details: if not continuing_only or (continuing_only and tvdb_details["tvdb_status"] == "Continuing"): all_series.append(tvdb_details) del monitor return all_series
def get_kodishows_airingtoday(self): ''' returns full info for each tvshow in the kodi library that airs today ''' result = [] monitor = xbmc.Monitor() for series_info in self.get_kodishows(continuing_only=True): if monitor.abortRequested() or self._close_called: break details = self.get_kodishow_details(series_info["title"], serie_details=series_info) if details and details.get("next_episode"): airdate = arrow.get(details["next_episode"]["firstaired"]).date() if airdate == date.today(): result.append(series_info) del monitor return sorted(result, key=lambda k: k.get('airtime', ""))
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")
def onNotification(self, sender, method, data): xbmc.Monitor.onNotification(self, sender, method, data) xbmc.log('%s: Notification %s from %s, params: %s' % (ADDONID, method, sender, str(data))) if method == 'VideoLibrary.OnUpdate': params = json.loads(data) if 'item' in params and 'type' in params['item']: item_type = params['item']['type'] if item_type == 'episode' and 'id' in params['item'] and 'playcount' in params: item_id = params['item']['id'] playcount = params['playcount'] self.watched_status.update_server_status(item_id, playcount > 0) elif method == 'Player.OnStop': params = json.loads(data) if 'item' in params and 'type' in params['item']: item_type = params['item']['type'] if item_type == 'episode' and 'id' in params['item']: item_id = params['item']['id'] end = params['end'] if end: self.watched_status.update_server_status(item_id, True) else: # resume time is not still updated so need to re-check time later threading.Timer(3.0, self.onPlayerStopped, args=(item_id, )).start()
def __init__(self): '''Init''' self.monitor = xbmc.Monitor() self.colorthemes = ColorThemes() self.backuprestore = BackupRestore()
def __init__(self): self.addon = xbmcaddon.Addon(id=ADDON_ID) 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 self.token_info = self.get_auth_token() if self.token_info and not self.kodimonitor.abortRequested(): # initialize spotipy self.sp._auth = self.token_info["access_token"] me = self.sp.me() log_msg("Logged in to Spotify - Username: %s" % me["id"], xbmc.LOGNOTICE) # start experimental spotify connect daemon if self.addon.getSetting("connect_player") == "true" and self.spotty.playback_supported: self.connect_player.start() # start mainloop self.main_loop()
def play_track_radio(self): player = SpotifyRadioPlayer() player.set_parent(self) seed_track = self.sp.track(self.trackid) player.set_seed_tracks([seed_track]) player.play() monitor = xbmc.Monitor() monitor.waitForAbort()
def __init__(self): '''Initialize our caching class''' self._win = xbmcgui.Window(10000) self._monitor = xbmc.Monitor() self.check_cleanup() self._log_msg("Initialized")
def get_kodishows_details(self, continuing_only=False): ''' returns full info for each tvshow in the kodi library returns both kodi and tvdb info combined, including next-/last episode ''' result = [] monitor = xbmc.Monitor() for series_info in self.get_kodishows(continuing_only=continuing_only): if monitor.abortRequested() or self._close_called: break details = self.get_kodishow_details(series_info["title"], serie_details=series_info) if details: result.append(series_info) del monitor return result
def __init__(self, *args, **kwargs): xbmc.Monitor.__init__(self, *args, **kwargs) self.config = TidalConfig2() self.setLastSettings()
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
def rate_limiter(rl_params): ''' A very basic rate limiter which limits to 1 request per X seconds to the api''' # Please respect the parties providing these free api's to us and do not modify this code. # If I suspect any abuse I will revoke all api keys and require all users # to have a personal api key for all services. # Thank you if not rl_params: return monitor = xbmc.Monitor() win = xbmcgui.Window(10000) rl_name = rl_params[0] rl_delay = rl_params[1] cur_timestamp = int(time.mktime(datetime.datetime.now().timetuple())) prev_timestamp = try_parse_int(win.getProperty("ratelimiter.%s" % rl_name)) if (prev_timestamp + rl_delay) > cur_timestamp: sec_to_wait = (prev_timestamp + rl_delay) - cur_timestamp log_msg( "Rate limiter active for %s - delaying request with %s seconds - " "Configure a personal API key in the settings to get rid of this message and the delay." % (rl_name, sec_to_wait), xbmc.LOGNOTICE) while sec_to_wait and not monitor.abortRequested(): monitor.waitForAbort(1) # keep setting the timestamp to create some sort of queue cur_timestamp = int(time.mktime(datetime.datetime.now().timetuple())) win.setProperty("ratelimiter.%s" % rl_name, "%s" % cur_timestamp) sec_to_wait -= 1 # always set the timestamp cur_timestamp = int(time.mktime(datetime.datetime.now().timetuple())) win.setProperty("ratelimiter.%s" % rl_name, "%s" % cur_timestamp) del monitor del win
def get_json(url, params=None, retries=0, ratelimit=None): '''get info from a rest api''' result = {} if not params: params = {} # apply rate limiting if needed rate_limiter(ratelimit) try: response = requests.get(url, params=params, timeout=20) if response and response.content and response.status_code == 200: result = json.loads(response.content.decode('utf-8', 'replace')) if "results" in result: result = result["results"] elif "result" in result: result = result["result"] elif response.status_code in (429, 503, 504): raise Exception('Read timed out') except Exception as exc: result = None if "Read timed out" in str(exc) and retries < 5 and not ratelimit: # retry on connection error or http server limiting monitor = xbmc.Monitor() if not monitor.waitForAbort(2): result = get_json(url, params, retries + 1) del monitor else: log_exception(__name__, exc) # return result return result
def wait_for_internet(wait=30, retry=5): import xbmc monitor = xbmc.Monitor() count = 0 while True: if internet(): return True count += 1 if count >= retry or monitor.abortRequested(): return False monitor.waitForAbort(wait)
def __init__(self, api, *args, **kwargs): xbmc.Monitor.__init__(self) self._api = api
def __init__(self, *args, **kwargs): xbmc.Monitor.__init__(self) self.id = xbmcaddon.Addon().getAddonInfo('id')
def busy_execute_sleep(self,executebuiltin, sleep=500, close=True): xbmc.executebuiltin("ActivateWindow(busydialog)") #RunAddon(script.reddit.reader,mode=listSubReddit&url=https%3A%2F%2Fwww.reddit.com%2Fr%2Fall%2F.json%3F%26nsfw%3Ano%2B%26limit%3D10%26after%3Dt3_4wmiag&name=all&type=) xbmc.executebuiltin( executebuiltin ) xbmc.Monitor().waitForAbort( int(sleep/1000) ) #xbmc.sleep(sleep) #a sleep of 500 is enough for listing subreddit use about 5000 for executing a link/playing video especially a ytdl video if close: self.close() else: xbmc.executebuiltin( "Dialog.Close(busydialog)" )
def __init__( self ): self._service_setup() while (not self.Monitor.abortRequested()) and (not self.Exit): xbmc.sleep(1000)
def _service_setup( self ): self.HatchetURL = 'https://api.hatchet.is' self.ClientId = 'xbm' self.ClientVersion = '0.2' self.ClientProtocol = '1.2.1' self.Exit = False self.Monitor = MyMonitor(action = self._get_settings) self._get_settings()
def __init__( self, *args, **kwargs ): xbmc.Monitor.__init__( self ) self.action = kwargs['action']
def __init__( self, *args, **kwargs ): xbmc.Monitor.__init__( self )
def onScanStarted(self, library): xbmc.Monitor.onScanStarted(self, library) xbmc.log('%s: Library scan \'%s\' started' % (ADDONID, library))
def onScanFinished(self, library): xbmc.Monitor.onScanFinished(self, library) xbmc.log('%s: Library scan \'%s\' finished' % (ADDONID, library)) self.watched_status.sync_status() # TODO: do in new thread
def abortRequested(): return abort # Monitor class which will get called when the settings change
def __init__(self): xbmc.Monitor.__init__(self) # Init settings settings.init() # This is the function that signals that the user just changed a setting. # First default settings will be loaded, then we read the user-defined settings and # overwrite these default settings if needed.
def update_youtube_dl_core(url,name,action_type): #credit to ruuk for most of the download code import tarfile if action_type=='download': newVersion=note_ytdl_versions() LATEST_URL=YTDL_LATEST_URL_TEMPLATE.format(newVersion) profile = xbmc.translatePath(profile_path) #xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8') archivePath = os.path.join(profile,'youtube_dl.tar.gz') extractedPath = os.path.join(profile,'youtube-dl') extracted_core_path=os.path.join(extractedPath,'youtube_dl') #ytdl_core_path xbmc.translatePath( addon_path+"/resources/lib/youtube_dl/" ) try: if os.path.exists(extractedPath): shutil.rmtree(extractedPath, ignore_errors=True) update_dl_status('temp files removed') update_dl_status('Downloading {0} ...'.format(newVersion)) log(' From: {0}'.format(LATEST_URL)) log(' to: {0}'.format(archivePath)) urllib.urlretrieve(LATEST_URL,filename=archivePath) if os.path.exists(archivePath): update_dl_status('Extracting ...') with tarfile.open(archivePath,mode='r:gz') as tf: members = [m for m in tf.getmembers() if m.name.startswith('youtube-dl/youtube_dl')] #get just the files from the youtube_dl source directory tf.extractall(path=profile,members=members) else: update_dl_status('Download failed') except Exception as e: update_dl_status('Error:' + str(e)) update_dl_status('Updating...') if os.path.exists(extracted_core_path): log( ' extracted dir exists:'+extracted_core_path) if os.path.exists(ytdl_core_path): log( ' destination dir exists:'+ytdl_core_path) shutil.rmtree(ytdl_core_path, ignore_errors=True) update_dl_status(' Old ytdl core removed') xbmc.sleep(1000) try: shutil.move(extracted_core_path, ytdl_core_path) update_dl_status(' New core copied') xbmc.sleep(1000) update_dl_status('Update complete') xbmc.Monitor().waitForAbort(2.0) #ourVersion=ytdl_get_version_info('local') setSetting('ytdl_btn_check_version', "") setSetting('ytdl_btn_download', "") except Exception as e: update_dl_status('Failed...') log( 'move failed:'+str(e)) elif action_type=='checkversion': note_ytdl_versions()
def get_stream(url, airing_id, channel_id, program_id, series_id, tms_id, title, plot): headers = {'Accept': '*/*', 'Content-type': 'application/x-www-form-urlencoded', 'Origin': 'https://vue.playstation.com', 'Accept-Language': 'en-US,en;q=0.8', 'Referer': 'https://vue.playstation.com/watch/live', 'Accept-Encoding': 'gzip, deflate, br', 'User-Agent': UA_ANDROID_TV, 'Connection': 'Keep-Alive', 'Host': 'media-framework.totsuko.tv', 'reqPayload': ADDON.getSetting(id='EPGreqPayload'), 'X-Requested-With': 'com.snei.vue.android' } r = requests.get(url, headers=headers, cookies=load_cookies(), verify=VERIFY) json_source = r.json() stream_url = json_source['body']['video'] headers = '|User-Agent=' headers += 'Adobe Primetime/1.4 Dalvik/2.1.0 (Linux; U; Android 6.0.1 Build/MOB31H)' headers += '&Cookie=reqPayload=' + urllib.quote('"' + ADDON.getSetting(id='EPGreqPayload') + '"') listitem = xbmcgui.ListItem() # Checks to see if VideoPlayer info is already saved. If not then info is loaded from stream link if xbmc.getCondVisibility('String.IsEmpty(ListItem.Title)'): listitem = xbmcgui.ListItem(title, plot) listitem.setInfo(type="Video", infoLabels={'title': title, 'plot': plot}) listitem.setMimeType("application/x-mpegURL") else: listitem = xbmcgui.ListItem() listitem.setMimeType("application/x-mpegURL") if xbmc.getCondVisibility('System.HasAddon(inputstream.adaptive)'): stream_url = json_source['body']['video_alt'] # Uses alternate Sony stream to prevent Inputstream adaptive from crashing listitem.setProperty('inputstreamaddon', 'inputstream.adaptive') listitem.setProperty('inputstream.adaptive.manifest_type', 'hls') listitem.setProperty('inputstream.adaptive.stream_headers', headers) listitem.setProperty('inputstream.adaptive.license_key', headers) else: stream_url += headers listitem.setPath(stream_url) xbmcplugin.setResolvedUrl(addon_handle, True, listitem) # Seek to time #Give the stream sometime to start before checking monitor = xbmc.Monitor() monitor.waitForAbort(10) xbmc.log("Is playing video? " + str(xbmc.Player().isPlayingVideo())) while xbmc.Player().isPlayingVideo() and not monitor.abortRequested(): xbmc.log("Still playing...") monitor.waitForAbort(3) xbmc.log("We're done, write info back to ps servers!!!") sony = SONY() sony.put_resume_time(airing_id, channel_id, program_id, series_id, tms_id)