def __init__(self, providers, method, timeout=10): super(ProviderListenerDialog, self).__init__(providers, method, timeout=timeout) self._total = len(providers) self._count = 0 self._dialog = DialogProgressBG()
def show_progress_background(heading='', message=''): """ Show a Kodi progress dialog """ from xbmcgui import DialogProgressBG if not heading: heading = ADDON.getAddonInfo('name') progress = DialogProgressBG() progress.create(heading=heading, message=message) return progress
def _get_artists_hashmap( self ): #gets a list of all the artists from XBMC pDialog = DialogProgressBG() pDialog.create( smartUTF8(language(32001)), smartUTF8(language(30301)) ) hashmap = _ordereddict() response = xbmc.executeJSONRPC ( '{"jsonrpc":"2.0", "method":"AudioLibrary.GetArtists", "params":{"albumartistsonly":false, "sort":{"order":"ascending", "ignorearticle":true, "method":"artist"}},"id": 1}}' ) try: artists_info = _json.loads(response)['result']['artists'] except (IndexError, KeyError, ValueError): artists_info = [] except Exception, e: lw.log( ['unexpected error getting JSON back from XBMC', e] ) artists_info = []
def __run(self): """ Do the work """ log.debug('Show sync info thread started') # cache local variables because it's faster total = self.total dialog = DialogProgressBG('dialoglogProgressBG') thread_stopped = self.thread_stopped dialog.create("%s %s: %s %s" % (lang(39714), self.item_type, str(total), lang(39715))) player = Player() total = 2 * total totalProgress = 0 while thread_stopped() is False and not player.isPlaying(): with LOCK: get_progress = GET_METADATA_COUNT process_progress = PROCESS_METADATA_COUNT viewName = PROCESSING_VIEW_NAME totalProgress = get_progress + process_progress try: percentage = int(float(totalProgress) / float(total) * 100.0) except ZeroDivisionError: percentage = 0 dialog.update(percentage, message="%s %s. %s %s: %s" % (get_progress, lang(39712), process_progress, lang(39713), viewName)) # Sleep for x milliseconds sleep(200) dialog.close() log.debug('Show sync info thread terminated')
def _run_server(self, host, port): app.frame_data = self._frame_data httpd = make_server(host, port, app, ws_handler_class=WebConsoleSocket) logger.info('Web-PDB: starting web-server on {0}:{1}...'.format( httpd.server_name, port) ) dialog = DialogProgressBG() started = False while not (self._stop_all.is_set() or kodi_monitor.abortRequested()): try: httpd.handle_request() except SystemExit: break if not started: logger.info('Web-PDB: web-server started.') dialog.create( addon.getLocalizedString(32001), addon.getLocalizedString(32002).format( httpd.server_name, port ) ) dialog.update(100) started = True httpd.handle_close() logger.info('Web-PDB: web-server stopped.') dialog.close()
def run(self): """ Do the work """ LOG.debug('Show sync info thread started') # cache local variables because it's faster total = self.total dialog = DialogProgressBG('dialoglogProgressBG') dialog.create("%s %s: %s %s" % (utils.lang(39714), self.item_type, unicode(total), utils.lang(39715))) total = 2 * total total_progress = 0 while not self.stopped(): with LOCK: get_progress = GET_METADATA_COUNT process_progress = PROCESS_METADATA_COUNT view_name = PROCESSING_VIEW_NAME total_progress = get_progress + process_progress try: percentage = int(float(total_progress) / float(total) * 100.0) except ZeroDivisionError: percentage = 0 dialog.update(percentage, message="%s %s. %s %s: %s" % (get_progress, utils.lang(39712), process_progress, utils.lang(39713), view_name)) # Sleep for x milliseconds sleep(200) dialog.close() LOG.debug('Show sync info thread terminated')
def __init__(self, host, port, patch_stdstreams=False): cry('listen socket') self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._listen_socket.settimeout(None) cry('setsokcport') self._listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) cry('bind') self._listen_socket.bind((host, port)) self._stop_monitor = threading.Event() self._monitor_thread = threading.Thread(target=self._monitor_abort) self._monitor_thread.daemon = True self._monitor_thread.start() if not host: host = socket.gethostname() port = self._listen_socket.getsockname()[1] cry("RemotePdb session open at %s:%s, waiting for connection ..." % (host, port)) self._dialog = DialogProgressBG() self._dialog.create('remote-pdb', 'Waiting for connection at [COLOR=yellow]%s:%s[/COLOR]' % (host, port) ) self._listen_socket.listen(1) self._connection, address = self._listen_socket.accept() self._connection.settimeout(None) self._dialog.update(100, heading='remote-pdb', message='Connection from %s active' % address[0]) cry("RemotePdb accepted connection from %s." % repr(address)) if PY3: self.handle = LF2CRLF_FileWrapper(self._connection.makefile('rw')) else: self.handle = LF2CRLF_FileWrapper(self._connection.makefile()) Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle) self.backup = [] if patch_stdstreams: for name in ( 'stderr', 'stdout', '__stderr__', '__stdout__', 'stdin', '__stdin__', ): self.backup.append((name, getattr(sys, name))) setattr(sys, name, self.handle) RemotePdb.active_instance = self
def update_tvdb(): progress_bar = DialogProgressBG() progress_bar.create(heading="Downloading database...") msg = "Базата данни НЕ бе обновена!" try: log('Force-updating tvdb') # recreated the db_file in case db_file is overwritten by use_local_db __db_file__ = os.path.join(get_resources_dir(), 'tv.db') asset = Assets(__db_file__, backup_db_file) progress_bar.update(1, "Downloading database...") errors = asset.update(settings.url_db) if errors: notify_error(msg + "\n" + errors) if settings.use_local_db: notify_success("Използвате локална база данни!") except Exception as ex: log(ex, 4) if progress_bar: progress_bar.close()
class ProviderListenerDialog(ProviderListener): def __init__(self, providers, method, timeout=10): super(ProviderListenerDialog, self).__init__(providers, method, timeout=timeout) self._total = len(providers) self._count = 0 self._dialog = DialogProgressBG() def on_receive(self, sender): self._count += 1 self._dialog.update(int(100 * self._count / self._total)) def __enter__(self): ret = super(ProviderListenerDialog, self).__enter__() self._dialog.create(ADDON_NAME, translate(30111)) return ret def __exit__(self, exc_type, exc_val, exc_tb): try: return super(ProviderListenerDialog, self).__exit__(exc_type, exc_val, exc_tb) finally: self._dialog.close()
def bg_progress_dialog(): """Show Kodi's Background Progress dialog""" return DialogProgressBG()
def generate_playlist(): ''' Function executed by scheduler to generate a playlist ''' progress_bar = DialogProgressBG() debug = settings.debug is_manual_run = False if len( sys.argv) > 1 and sys.argv[1] == 'False' else True if not is_manual_run: log('Автоматично генериране на плейлиста') if debug or is_manual_run: progress_bar.create(heading=get_addon_name()) def show_progress(percent, msg): if debug or is_manual_run: heading = "%s %s%%" % (get_addon_name().encode('utf-8'), str(percent)) progress_bar.update(percent, heading, msg) log(msg) try: if not settings.use_local_db: asset = Assets(db_file, backup_db_file) if asset.is_old(): errors = asset.update(settings.url_db) if errors: notify_error('Базата данни не бе обновена! %s' % errors) show_progress(10, 'Зареждане на канали от базата данни %s ' % db_file) conn = sqlite3.connect(db_file) cursor = conn.execute( '''SELECT c.id, c.disabled, c.name, cat.name AS category, c.logo, COUNT(s.id) AS streams, s.stream_url, s.page_url, s.player_url, c.epg_id, u.string, c.ordering FROM channels AS c JOIN streams AS s ON c.id = s.channel_id JOIN categories as cat ON c.category_id = cat.id JOIN user_agents as u ON u.id = s.user_agent_id WHERE c.disabled <> 1 GROUP BY c.name, c.id ORDER BY c.ordering''') show_progress(20, 'Генериране на плейлиста') update('generation', 'PlaylistGenerator') pl = Playlist(settings.include_radios) show_progress(25, 'Търсене на потоци') n = 26 for row in cursor: try: c = Channel(row) n += 1 show_progress(n, 'Търсене на поток за канал %s' % c.name) cursor = conn.execute('''SELECT s.*, u.string AS user_agent FROM streams AS s JOIN user_agents as u ON s.user_agent_id == u.id WHERE disabled <> 1 AND channel_id = %s AND preferred = 1''' % c.id) s = Stream(cursor.fetchone()) c.playpath = s.url if c.playpath is None: xbmc.log('Не е намерен валиден поток за канал %s ' % c.name) else: pl.channels.append(c) except Exception, er: xbmc.log('Грешка при търсене на поток за канал %s ' % c.name) log_last_exception() show_progress(90, 'Записване на плейлиста') pl.save(get_profile_dir()) ################################################### ### Apend/Prepend another playlist if specified ################################################### apf = settings.additional_playlist_file # if settings.concat_playlist and os.path.isfile(apf): # show_progress(92,'Обединяване с плейлиста %s' % apf) # pl.concat(apf, settings.append == '1') # pl.save(get_profile_dir()) ################################################### ### Copy playlist to additional folder if specified ################################################### ctf = settings.copy_to_folder if settings.copy_playlist and os.path.isdir(ctf): show_progress(95, 'Копиране на плейлиста') pl.save(ctf) #################################################### ### Set next run #################################################### show_progress(98, 'Генерирането на плейлистата завърши!') roi = int(settings.run_on_interval) * 60 show_progress( 99, 'Настройване на AlarmClock. Следващото изпълнение на скрипта ще бъде след %s часа' % (roi / 60)) command = "plugin://%s/?action=generate_playlist" % get_addon_id() xbmc.executebuiltin( 'AlarmClock(%s, RunScript(%s, False), %s, silent)' % (get_addon_id(), command, roi))
def __init__(self, database, cursor, progress_bar=True): self.epg_db = EpgDb(database, cursor) self.progress_bar = DialogProgress( ) if progress_bar else DialogProgressBG()
lw.log( loglines ) def _migrate( self ): lw.log( ['attempting to %s images from Artist Slideshow cache directory' % self.MIGRATETYPE] ) test_str = '' hashmap = self._get_artists_hashmap() try: folders, throwaway = xbmcvfs.listdir( self.ASCACHEFOLDER ) except OSError: lw.log( ['no directory found: ' + self.ASCACHEFOLDER] ) return except Exception, e: lw.log( ['unexpected error while getting directory list', e] ) return pDialog = DialogProgressBG() pDialog.create( smartUTF8(language(32003)), smartUTF8(language(30301)) ) total = len( folders ) count = 1 for folder in folders: try: artist_start = hashmap[folder] except KeyError: lw.log( ['no matching artist folder for: ' + folder] ) artist_start = '' except Exception, e: lw.log( ['unexpected error while finding matching artist for ' + folder, e] ) artist_start = '' if artist_start: pDialog.update(int(100*(count/total)), smartUTF8( language(32003) ), smartUTF8( artist_start ) ) if self.ENABLEFUZZYSEARCH == 'true':
class RemotePdb(Pdb): """ This will run pdb as a ephemeral telnet service. Once you connect no one else can connect. On construction this object will block execution till a client has connected. Based on https://github.com/tamentis/rpdb I think ... To use this:: RemotePdb(host='0.0.0.0', port=4444).set_trace() Then run: telnet 127.0.0.1 4444 """ active_instance = None has_quit = False def __init__(self, host, port, patch_stdstreams=False): cry('listen socket') self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._listen_socket.settimeout(None) cry('setsokcport') self._listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) cry('bind') self._listen_socket.bind((host, port)) self._stop_monitor = threading.Event() self._monitor_thread = threading.Thread(target=self._monitor_abort) self._monitor_thread.daemon = True self._monitor_thread.start() if not host: host = socket.gethostname() port = self._listen_socket.getsockname()[1] cry("RemotePdb session open at %s:%s, waiting for connection ..." % (host, port)) self._dialog = DialogProgressBG() self._dialog.create('remote-pdb', 'Waiting for connection at [COLOR=yellow]%s:%s[/COLOR]' % (host, port) ) self._listen_socket.listen(1) self._connection, address = self._listen_socket.accept() self._connection.settimeout(None) self._dialog.update(100, heading='remote-pdb', message='Connection from %s active' % address[0]) cry("RemotePdb accepted connection from %s." % repr(address)) if PY3: self.handle = LF2CRLF_FileWrapper(self._connection.makefile('rw')) else: self.handle = LF2CRLF_FileWrapper(self._connection.makefile()) Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle) self.backup = [] if patch_stdstreams: for name in ( 'stderr', 'stdout', '__stderr__', '__stdout__', 'stdin', '__stdin__', ): self.backup.append((name, getattr(sys, name))) setattr(sys, name, self.handle) RemotePdb.active_instance = self def _monitor_abort(self): while not (xbmc.abortRequested or self._stop_monitor.is_set()): time.sleep(0.1) if not self._stop_monitor.is_set(): self.do_quit(None) def __restore(self): if self.backup: cry('Restoring streams: %s ...' % self.backup) for name, fh in self.backup: setattr(sys, name, fh) self.handle.close() RemotePdb.active_instance = None def do_quit(self, arg): self._dialog.close() self._stop_monitor.set() try: self._connection.shutdown(socket.SHUT_WR) self._connection.close() except AttributeError: pass self._listen_socket.close() try: self.__restore() except AttributeError: pass self.set_quit() RemotePdb.has_quit = True return 1 do_q = do_exit = do_quit def set_trace(self, frame=None): if frame is None: frame = sys._getframe().f_back try: Pdb.set_trace(self, frame) except IOError as exc: if exc.errno != errno.ECONNRESET: raise def set_quit(self): sys.settrace(None)