Python xbmcgui 模块,DialogProgress() 实例源码

我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用xbmcgui.DialogProgress()

项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def resolve(self, url, proxy=None, maxbitrate=0, player=None):

        self.stopPlaying=threading.Event()
        progress = xbmcgui.DialogProgress()

        progress.create('Starting local proxy')
        progress.update(20, "", 'Loading local proxy', "")

        self.stopPlaying.clear()
        t = threading.Thread(target=self.__start, args=(self.stopPlaying, player,))
        t.daemon = True
        t.start()

        url_to_play = self.__prepare_url(url, proxy, maxbitrate=maxbitrate)

        xbmc.sleep(100)

        progress.update(100, "", "", "")
        progress.close()

        return url_to_play, player.MAIN_MIME_TYPE
项目:script.quasar.t411-rik91    作者:rik91    | 项目源码 | 文件源码
def __init__(self):
        # Objects
        self.dialog = xbmcgui.Dialog()
        self.pDialog = xbmcgui.DialogProgress()
        self.settings = xbmcaddon.Addon()

        # General information
        self.idAddon = self.settings.getAddonInfo('ID')  # gets name
        self.icon = self.settings.getAddonInfo('icon')
        self.fanart = self.settings.getAddonInfo('fanart')
        self.path = self.settings.getAddonInfo('path')
        self.name = self.settings.getAddonInfo('name')  # gets name
        self.cleanName = re.sub('.COLOR (.*?)]', '', self.name.replace('[/COLOR]', ''))
        self.value = {}  # it contains all the settings from xml file
        with open(path.join(self.path, "resources", "settings.xml"), 'r') as fp:
            data = fp.read()
        soup = BeautifulSoup(data)
        settings = soup.select("setting")
        for setting in settings:
            key = setting.attrs.get("id")
            if key is not None:
                self.value[key] = self.settings.getSetting(key)
        if 'url_address' in self.value and self.value['url_address'].endswith('/'):
            self.value['url_address'] = self.value['url_address'][:-1]
项目:plugin.video.jen    作者:midraal    | 项目源码 | 文件源码
def all_episodes(url):
    global content_type
    import pickle
    import xbmcgui
    season_urls = pickle.loads(url)
    result_items = []
    dialog = xbmcgui.DialogProgress()
    dialog.create(addon_name, _("Loading items"))
    num_urls = len(season_urls)
    for index, season_url in enumerate(season_urls):
        if dialog.iscanceled():
            break
        percent = ((index + 1) * 100) / num_urls
        dialog.update(percent, _("processing lists"), _("%s of %s") % (
            index + 1,
            num_urls))

        jen_list = JenList(season_url)
        result_items.extend(jen_list.get_list(skip_dialog=True))
    content_type = "episodes"
    display_list(result_items, "episodes")
项目:script.profilecleaner    作者:cibboy    | 项目源码 | 文件源码
def PerformCleanup(self, bitmask):
        if addonSettings.getSetting("ShowNotifications") == "true" and not showGUI:
            xbmc.executebuiltin("Notification(%s,%s,2000,%s)" % (addonName, normalize(addonLanguage(32164)), addonIcon))

        if (bitmask > 0 and showGUI):
            self.Progress = xbmcgui.DialogProgress()
            self.Progress.create(addonName)

        if ((bitmask & 1) == 1):
            self.ThumbnailCleanup()
        if ((bitmask & 2) == 2):
            self.SearchAndDeleteThumbnail()
        if ((bitmask & 4) == 4):
            self.EmptyThumbnailTable()
        if ((bitmask & 8) == 8):
            self.AddonCleanup()

        if (bitmask > 0 and showGUI):
            self.Progress.close()

        if addonSettings.getSetting("ShowNotifications") == "true" and not showGUI:
            xbmc.executebuiltin("Notification(%s,%s,2000,%s)" % (addonName, normalize(addonLanguage(32165)), addonIcon))
项目:repository.midraal    作者:midraal    | 项目源码 | 文件源码
def all_episodes(url):
    global content_type
    import pickle
    import xbmcgui
    season_urls = pickle.loads(url)
    result_items = []
    dialog = xbmcgui.DialogProgress()
    dialog.create(addon_name, _("Loading items"))
    num_urls = len(season_urls)
    for index, season_url in enumerate(season_urls):
        if dialog.iscanceled():
            break
        percent = ((index + 1) * 100) / num_urls
        dialog.update(percent, _("processing lists"), _("%s of %s") % (index + 1,
                                                                 num_urls))

        jen_list = JenList(season_url)
        result_items.extend(jen_list.get_list(skip_dialog=True))
    content_type = "episodes"
    display_list(result_items, "episodes")
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def get_base_datas():
    """
    Fetch the header nav datas from API and clean it (menu items)
    """

    global main_data
    if main_data is None:

        site = 'media' # 'data-site' attr from body
        url = common.rtbf_url + 'news/api/menu?site=%s' % site 

        progressdialog = xbmcgui.DialogProgress()
        progressdialog.create(common.plugin.addon.getAddonInfo('name'))
        progressdialog.update(0, 'Récupération des données...')

        common.plugin.log("get_base_datas")

        try:

            json_data = utils.request_url(url)
            if not json_data:
                return

            main_data = json.loads(json_data) #will generate unicode
            main_data = clean_base_datas(main_data)
            progressdialog.update(100, 'Done!')

        except:
            main_data = False
            progressdialog.update(0, 'Échec!')
            xbmc.sleep(1000)

        progressdialog.close()

    #common.plugin.log("before clean_base_datas:")
    #common.plugin.log(json.dumps(main_data))

    #common.plugin.log("after clean_base_datas:")
    #common.plugin.log(json.dumps(main_data))

    return main_data
项目:context.youtube.download    作者:anxdpanic    | 项目源码 | 文件源码
def __init__(self, heading, line1='', line2='', line3='', background=False, active=True):
        if active:
            if background:
                self.pd = xbmcgui.DialogProgressBG()
                msg = line1 + line2 + line3
                self.pd.create(heading, msg)
            else:
                self.pd = xbmcgui.DialogProgress()
                self.pd.create(heading, line1, line2, line3)
            self.background = background
            self.heading = heading
            self.pd.update(0)
        else:
            self.pd = None
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def handle_wait(time_to_wait,title,text):
    logger.info ("[xbmctools.py] handle_wait(time_to_wait=%d)" % time_to_wait)
    import xbmc,xbmcgui
    espera = xbmcgui.DialogProgress()
    ret = espera.create(' '+title)

    secs=0
    percent=0
    increment = int(100 / time_to_wait)

    cancelled = False
    while secs < time_to_wait:
        secs = secs + 1
        percent = increment*secs
        secs_left = str((time_to_wait - secs))
        remaining_display = ' Espera '+secs_left+' segundos para que comience el vídeo...'
        espera.update(percent,' '+text,remaining_display)
        xbmc.sleep(1000)
        if (espera.iscanceled()):
             cancelled = True
             break

    if cancelled == True:     
         logger.info ('Espera cancelada')
         return False
    else:
         logger.info ('Espera finalizada')
         return True

# Adds all the items to the Kodi directory
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def PLAY_STREAM(name,url,iconimage):
    dp = xbmcgui.DialogProgress()
    r='    Please Wait While We Load [COLOR yellow][B]%s[/B][/COLOR]'%(name)
    dp.create("NotFilmOn",'',r,'')
    programme_id=str(iconimage).replace('http://static.filmon.com/couch/channels/','').replace('/big_logo.png','')
    GA_track(programme_id,name)
    liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    liz.setInfo( type="Video", infoLabels={ "Title": name} )
    liz.setProperty("IsPlayable","true")
    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    pl.clear()
    pl.add(url, liz)
    xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(pl)
    dp.close()
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def playF4mLink(self,url,name,proxy=None,use_proxy_for_chunks=False, maxbitrate=0, simpleDownloader=False, auth=None, streamtype='HDS',setResolved=False,swf=None):
        print "URL: " + url
        stopPlaying=threading.Event()
        progress = xbmcgui.DialogProgress()


        f4m_proxy=f4mProxy()
        stopPlaying.clear()
        runningthread=thread.start_new_thread(f4m_proxy.start,(stopPlaying,))
        progress.create('Starting local proxy')
        stream_delay = 1
        progress.update( 20, "", 'Loading local proxy', "" )
        xbmc.sleep(stream_delay*1000)
        progress.update( 100, "", 'Loading local proxy', "" )
        url_to_play=f4m_proxy.prepare_url(url,proxy,use_proxy_for_chunks,maxbitrate=maxbitrate,simpleDownloader=simpleDownloader,auth=auth, streamtype=streamtype, swf=swf)
        listitem = xbmcgui.ListItem(name,path=url_to_play)
        listitem.setInfo('video', {'Title': name})

        if setResolved:
            return url_to_play, listitem
        mplayer = MyPlayer()    
        mplayer.stopPlaying = stopPlaying
        progress.close() 
        mplayer.play(url_to_play,listitem)

        #xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(url, listitem)
        firstTime=True
        while True:
            if stopPlaying.isSet():
                break;
            #if not xbmc.Player().isPlaying():
            #    break
            xbmc.log('Sleeping...')
            xbmc.sleep(200)
            #if firstTime:
            #    xbmc.executebuiltin('Dialog.Close(all,True)')
            #    firstTime=False
        stopPlaying.isSet()

        print 'Job done'
        return
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def playF4mLink(self,url,name,iconimage,proxy=None,use_proxy_for_chunks=False, maxbitrate=0, simpleDownloader=False, auth=None, streamtype='HDS',setResolved=False,swf=None):
        print "URL: " + url
        stopPlaying=threading.Event()
        progress = xbmcgui.DialogProgress()


        f4m_proxy=f4mProxy()
        stopPlaying.clear()
        runningthread=thread.start_new_thread(f4m_proxy.start,(stopPlaying,))
        progress.create('Starting local proxy')
        stream_delay = 1
        progress.update( 20, "", 'Loading local proxy', "" )
        xbmc.sleep(stream_delay*1000)
        progress.update( 100, "", 'Loading local proxy', "" )
        url_to_play=f4m_proxy.prepare_url(url,proxy,use_proxy_for_chunks,maxbitrate=maxbitrate,simpleDownloader=simpleDownloader,auth=auth, streamtype=streamtype, swf=swf)
        listitem = xbmcgui.ListItem(name,path=url_to_play,thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name})

        if setResolved:
            return url_to_play, listitem
        mplayer = MyPlayer()    
        mplayer.stopPlaying = stopPlaying
        progress.close() 
        mplayer.play(url_to_play,listitem)

        #xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(url, listitem)
        firstTime=True
        while True:
            if stopPlaying.isSet():
                break;
            #if not xbmc.Player().isPlaying():
            #    break
            xbmc.log('Sleeping...')
            xbmc.sleep(200)
            #if firstTime:
            #    xbmc.executebuiltin('Dialog.Close(all,True)')
            #    firstTime=False
        stopPlaying.isSet()

        print 'Job done'
        return
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_movie(self, title, year):
        """Removes the DB entry & the strm file for the movie given

        Parameters
        ----------
        title : :obj:`str`
            Title of the movie

        year : :obj:`int`
            Release year of the movie

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        movie_meta = '%s (%d)' % (title, year)
        folder = re.sub(
            pattern=r'[?|$|!|:|#]',
            repl=r'',
            string=self.db[self.movies_label][movie_meta]['alt_title'])
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(1210), movie_meta)
        progress.update(50)
        time.sleep(0.5)
        del self.db[self.movies_label][movie_meta]
        self._update_local_db(filename=self.db_filepath, db=self.db)
        dirname = self.kodi_helper.check_folder_path(
            path=os.path.join(self.movie_path, folder))
        filename = os.path.join(self.movie_path, folder, movie_meta + '.strm')
        if xbmcvfs.exists(dirname):
            xbmcvfs.delete(filename)
            xbmcvfs.rmdir(dirname)
            return True
        return False
        time.sleep(1)
        progress.close()
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def playF4mLink(self,url,name,proxy=None,use_proxy_for_chunks=False, maxbitrate=0, simpleDownloader=False, auth=None, streamtype='HDS',setResolved=False):
        print "URL: " + url
        stopPlaying=threading.Event()
        progress = xbmcgui.DialogProgress()


        f4m_proxy=f4mProxy()
        stopPlaying.clear()
        runningthread=thread.start_new_thread(f4m_proxy.start,(stopPlaying,))
        progress.create('Starting local proxy')
        stream_delay = 1
        progress.update( 20, "", 'Loading local proxy', "" )
        xbmc.sleep(stream_delay*1000)
        progress.update( 100, "", 'Loading local proxy', "" )
        url_to_play=f4m_proxy.prepare_url(url,proxy,use_proxy_for_chunks,maxbitrate=maxbitrate,simpleDownloader=simpleDownloader,auth=auth, streamtype=streamtype)
        listitem = xbmcgui.ListItem(name,path=url_to_play)
        listitem.setInfo('video', {'Title': name})

        if setResolved:
            return url_to_play, listitem
        mplayer = MyPlayer()    
        mplayer.stopPlaying = stopPlaying
        progress.close() 
        mplayer.play(url_to_play,listitem)

        #xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(url, listitem)
        firstTime=True
        while True:
            if stopPlaying.isSet():
                break;
            #if not xbmc.Player().isPlaying():
            #    break
            xbmc.log('Sleeping...')
            xbmc.sleep(200)
            #if firstTime:
            #    xbmc.executebuiltin('Dialog.Close(all,True)')
            #    firstTime=False
        stopPlaying.isSet()

        print 'Job done'
        return
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def dialog_progress(heading, line1, line2=" ", line3=" "):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def dialog_progress(heading, line1, line2="", line3=""):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def handle_wait(time_to_wait,title,text):
    logger.info ("[xbmctools.py] handle_wait(time_to_wait=%d)" % time_to_wait)
    import xbmc,xbmcgui
    espera = xbmcgui.DialogProgress()
    ret = espera.create(' '+title)

    secs=0
    percent=0
    increment = int(100 / time_to_wait)

    cancelled = False
    while secs < time_to_wait:
        secs = secs + 1
        percent = increment*secs
        secs_left = str((time_to_wait - secs))
        remaining_display = ' Attendi '+secs_left+' secondi per il video...'
        espera.update(percent,' '+text,remaining_display)
        xbmc.sleep(1000)
        if (espera.iscanceled()):
             cancelled = True
             break

    if cancelled == True:     
         logger.info ('Attesa eliminata')
         return False
    else:
         logger.info ('Attesa conclusa')
         return True
项目:plugin.video.amazon65    作者:phil65    | 项目源码 | 文件源码
def RefreshList():
    import tv
    import movies
    list_ = common.args.url
    mvlist = []
    tvlist = []
    pDialog = xbmcgui.DialogProgress()
    pDialog.create(common.__plugin__, common.getString(30117))

    for asin in common.SCRAP_ASINS(common.movielib % list_):
        if not movies.lookupMoviedb(asin):
            mvlist.append(asin)

    for asin in common.SCRAP_ASINS(common.tvlib % list_):
        if not tv.lookupTVdb(asin, tbl='seasons'):
            tvlist.append(asin)

    if mvlist:
        movies.updateLibrary(mvlist)
    if tvlist:
        tv.addTVdb(False, tvlist)
    pDialog.close()

    if mvlist:
        movies.updateFanart()
    if tvlist:
        tv.updateFanart()
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def HUBINSTALL(name, url, script):
    aList = []
    script_url = url
    link = OPEN_URL(script_url)
    matcher = script + '-(.+?).zip'
    match = re.compile(matcher).findall(link)
    for version in match:
        aList.append(version)
    aList.sort(cmp=ver_cmp, reverse=True)
    newest_v = script + '-' + aList[0]
    newest_v_url = script_url + script + '-' + aList[0] + '.zip'
    kodi.log("Looking for : " + newest_v_url)
    path = xbmc.translatePath(os.path.join('special://home', 'addons', 'packages'))
    dp = xbmcgui.DialogProgress()
    dp.create("Starting up", "Initializing ", '', 'Please Stand By....')
    # lib = os.path.join(path, name + '.zip')
    lib = os.path.join(path, newest_v + '.zip')
    addonfolder = xbmc.translatePath(os.path.join('special://', 'home', 'addons'))
    if os.path.exists(lib):
        os.remove(lib)
    downloader.download(newest_v_url, lib, dp, timeout=120)
    try:
        # xbmc.executebuiltin("InstallAddon(%s)" % newest_v)
        extract.all(lib, addonfolder, '')
        time.sleep(2)
    except IOError, (errno, strerror):
        kodi.message("Failed to open required files", "Error code is:", strerror)
        return False

# ****************************************************************
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def OPENSUBINSTALL(url):
    path = xbmc.translatePath(os.path.join('special://home', 'addons', 'packages'))
    dp = xbmcgui.DialogProgress();
    dp.create("Please Wait", " ", '', 'Installing Official OpenSubtitles Addon')
    lib = os.path.join(path, 'opensubtitlesOfficial.zip')
    try:
        os.remove(lib)
    except:
        pass
    downloader.download(url, lib, dp, timeout=120)
    addonfolder = xbmc.translatePath(os.path.join('special://', 'home', 'addons'))
    time.sleep(2)
    try:
        extract.all(lib, addonfolder, '')
    except IOError, (errno, strerror):
        kodi.message("Failed to open required files", "Error code is:", strerror)
        return False
    xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
    addon_able.set_enabled("service.subtitles.opensubtitles_by_opensubtitles")
    dialog.ok("Installation Complete!", "    We hope you enjoy your Kodi addon experience!",
              "    Brought To You By %s " % siteTitle)


# #################################################################


# #****************************************************************
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def make_lib(path, name):
    addon_title = AddonTitle + " Installer"
    dp = xbmcgui.DialogProgress()
    dp.create(addon_title, "", "", "")
    lib = os.path.join(path, name)
    try:
        os.remove(lib)
    except:
        pass
    downloader.download(url, lib, dp)
    dialog.ok(addon_title, "[COLOR gold]Download complete, File can be found at: [/COLOR][COLOR blue]" + lib + "[/COLOR]")


##############
项目:plugin.video.youtube    作者:jdf76    | 项目源码 | 文件源码
def __init__(self, heading, text):
        AbstractProgressDialog.__init__(self, 100)
        self._dialog = xbmcgui.DialogProgress()
        self._dialog.create(heading, text)

        # simple reset because KODI won't do it :(
        self._position = 1
        self.update(steps=-1)
项目:plugin.video.youtube    作者:Kolifanes    | 项目源码 | 文件源码
def __init__(self, heading, text):
        AbstractProgressDialog.__init__(self, 100)
        self._dialog = xbmcgui.DialogProgress()
        self._dialog.create(heading, text)

        # simple reset because KODI won't do it :(
        self._position = 1
        self.update(steps=-1)
        pass
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def dialog_progress(heading, line1, line2=" ", line3=" "):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
项目:plugin.video.9anime    作者:DxCx    | 项目源码 | 文件源码
def __init__(self, title, progress_string):
        self._dialog = xbmcgui.DialogProgress()
        self._progress_string = progress_string
        self._dialog.create(title)
项目:plugin.audio.bytefm    作者:kopf    | 项目源码 | 文件源码
def _download_show(title, moderators, show_slug, broadcast_date, image_url, show_path):
    plugin.log_notice("Downloading show {} to {}".format(show_slug, show_path))
    broadcast_data = _get_broadcast_recording_playlist(show_slug, broadcast_date)
    recordings = broadcast_data['recordings']
    list_items = []
    if not os.path.exists(show_path):
        os.makedirs(show_path)
    thumbnail_path = _save_thumbnail(image_url, show_path)
    for rec_idx, url in enumerate(recordings):
        mp3_filename = url.replace('/', '_').replace(' ', '_').lower()
        label = 'Part {}'.format(rec_idx+1)
        show_part_path = os.path.join(show_path, label)
        list_items.append({'url': show_part_path, 'label': label})
        if not os.path.exists(show_part_path):
            os.makedirs(show_part_path)
        shutil.copy(thumbnail_path, show_part_path)
        mp3_path = os.path.join(show_part_path, mp3_filename)
        cue_path = mp3_path + '.cue'
        _save_cuefile(broadcast_data['playlist'][url], cue_path, mp3_path, moderators, title)
        if not os.path.isfile(mp3_path):
            plugin.log_notice('{} does not exist, downloading...'.format(mp3_path))
            resp = _http_get(ARCHIVE_BASE_URL + url, stream=True)
            progress_bar = xbmcgui.DialogProgress()
            progress_bar.create(_('Downloading...'))
            i = 0.0
            file_size = int(resp.headers['Content-Length'])
            extra_info = _('File {} of {}').format(rec_idx + 1, len(recordings))
            with open(mp3_path, 'wb') as f:
                for block in resp.iter_content(CHUNK_SIZE):
                    f.write(block)
                    i += 1
                    percent_done = int(((CHUNK_SIZE * i) / file_size) * 100)
                    progress_bar.update(percent_done, _('Please wait'), extra_info)

    return list_items
项目:kodi-viaplay    作者:emilsvennesson    | 项目源码 | 文件源码
def device_registration(self):
        """Presents a dialog with information on how to activate the device.
        Attempts to authorize the device using the interval returned by the activation data."""
        activation_data = self.vp.get_activation_data()
        message = self.language(30039).format(activation_data['verificationUrl'], activation_data['userCode'])
        dialog = xbmcgui.DialogProgress()
        xbmc.sleep(200)  # small delay to prevent DialogProgress from hanging
        dialog.create(self.language(30040), message)
        secs = 0
        expires = activation_data['expires']

        while secs < expires:
            try:
                self.vp.authorize_device(activation_data)
                dialog.close()
                return True
            except self.vp.ViaplayError as error:
                # raise all non-pending authorization errors
                if not error.value == 'DeviceAuthorizationPendingError':
                    raise
            secs += activation_data['interval']
            percent = int(100 * float(secs) / float(expires))
            dialog.update(percent, message)
            xbmc.sleep(activation_data['interval'] * 1000)
            if dialog.iscanceled():
                dialog.close()
                return False

        dialog.close()
        return False
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def restore(self, filename="", silent=False):
        '''restore skin settings from file'''

        if not filename:
            filename = self.get_restorefilename()

        progressdialog = None
        if not silent:
            progressdialog = xbmcgui.DialogProgress(self.addon.getLocalizedString(32006))
            progressdialog.create(self.addon.getLocalizedString(32007))

        if filename and xbmcvfs.exists(filename):
            # create temp path
            temp_path = self.create_temp()
            if not filename.endswith("zip"):
                # assume that passed filename is actually a skinsettings file
                skinsettingsfile = filename
            else:
                # copy zip to temp directory and unzip
                skinsettingsfile = temp_path + "guisettings.txt"
                if progressdialog:
                    progressdialog.update(0, "unpacking backup...")
                zip_temp = u'%sskinbackup-%s.zip' % (ADDON_DATA, datetime.now().strftime('%Y-%m-%d-%H-%M'))
                copy_file(filename, zip_temp, True)
                unzip_fromfile(zip_temp, temp_path)
                delete_file(zip_temp)
                # copy skinshortcuts preferences
                self.restore_skinshortcuts(temp_path)
                # restore any custom skin images or themes
                for directory in ["custom_images/", "themes/"]:
                    custom_images_folder = u"special://profile/addon_data/%s/%s" % (xbmc.getSkinDir(), directory)
                    custom_images_folder_temp = temp_path + directory
                    if xbmcvfs.exists(custom_images_folder_temp):
                        for file in xbmcvfs.listdir(custom_images_folder_temp)[1]:
                            xbmcvfs.copy(custom_images_folder_temp + file,
                                         custom_images_folder + file)
            # restore guisettings
            if xbmcvfs.exists(skinsettingsfile):
                self.restore_guisettings(skinsettingsfile, progressdialog)

            # cleanup temp
            recursive_delete_dir(temp_path)
            progressdialog.close()
        if not silent:
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(32006), self.addon.getLocalizedString(32009))
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def download_and_play(url,file_name,download_path,show_dialog=True):
    # Lanza thread
    logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
    logger.info("[download_and_play.py] "+repr(threading.enumerate()))
    logger.info("[download_and_play.py] Starting download thread...")
    download_thread = DownloadThread(url,file_name,download_path)
    download_thread.start()
    logger.info("[download_and_play.py] Download thread started")
    logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
    logger.info("[download_and_play.py] "+repr(threading.enumerate()))

    # Espera
    logger.info("[download_and_play.py] Waiting...")

    while True:
        cancelled=False

        if show_dialog:
            dialog = xbmcgui.DialogProgress()
            dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
            dialog.update(0)

            while not cancelled and download_thread.is_alive():
                dialog.update( download_thread.get_progress() , "Cancela esta ventana para empezar la reproducción", "Velocidad: "+str(int(download_thread.get_speed()/1024))+" KB/s "+str(download_thread.get_actual_size())+"MB de "+str(download_thread.get_total_size())+"MB" , "Tiempo restante: "+str( downloadtools.sec_to_hms(download_thread.get_remaining_time())) )
                xbmc.sleep(1000)

                if dialog.iscanceled():
                    cancelled=True
                    break

            dialog.close()
        else:
            xbmc.executebuiltin((u'XBMC.Notification("Iniciando", "Iniciando descarga en segundo plano...", 300)'))
            xbmc.sleep(3000)

        logger.info("[download_and_play.py] End of waiting")

        # Lanza el reproductor
        player = CustomPlayer()
        player.set_download_thread(download_thread)
        player.PlayStream( download_thread.get_file_name() )

        # Fin de reproducción
        logger.info("[download_and_play.py] Fin de reproducción")

        if player.is_stopped():
            logger.info("[download_and_play.py] Terminado por el usuario")
            break
        else:
            if not download_thread.is_alive():
                logger.info("[download_and_play.py] La descarga ha terminado")
                break
            else:
                logger.info("[download_and_play.py] Continua la descarga")

    # Cuando el reproductor acaba, si continúa descargando lo para ahora
    logger.info("[download_and_play.py] Download thread alive="+str(download_thread.is_alive()))
    if download_thread.is_alive():
        logger.info("[download_and_play.py] Killing download thread")
        download_thread.force_stop()
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def playall(name,url):
    dp = xbmcgui.DialogProgress()
    dp.create("Disney Junior",'Creating Your Playlist')
    dp.update(0)
    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    pl.clear()

    response=OPEN_URL(url)
    link=response.split('"title":"')
    test=re.compile('"embedURL":"(.+?)"').findall(response)

    playlist = []
    nItem    = len(test)
    try:
        for p in link:
          try:
            title=p.split('"')[0]            
            newurl=re.compile('"embedURL":"(.+?)"').findall(p)[0]            
            iconimage=re.compile('"thumb":"(.+?)"').findall(p)[0]            
            description=re.compile('"description":"(.+?)"').findall(p)[0]
            SHOWME=re.compile('"ptitle":"(.+?)"').findall(p)[0]       
            if name in SHOWME:        
                liz = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
                liz.setInfo( type="Video", infoLabels={ "Title": title} )
                liz.setProperty("IsPlayable","true")

                r='"mp4".+?".+?"url":"(.+?)"}'
                html=OPEN_URL(newurl)
                match = re.compile(r).findall(html)
                amount = len(match)-1
                URL=match[amount]
                playlist.append((URL ,liz))

                progress = len(playlist) / float(nItem) * 100  
                dp.update(int(progress), 'Adding to Your Playlist',title)

                if dp.iscanceled():
                    return
          except:pass
        dp.close()

        print 'THIS IS PLAYLIST====   '+str(playlist)

        for blob ,liz in playlist:
            try:
                if blob:
                    print blob
                    pl.add(blob,liz)
            except:
                pass

        if not xbmc.Player().isPlayingVideo():
        xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(pl)
    except:
        raise
        dialog = xbmcgui.Dialog()
        dialog.ok("Disney Junior", "Sorry Get All Valid Urls", "Why Not Try A Singular Video")
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def send_email(TOWHO,LOG):
    PASSWORD=EmailPass()
    import zipfile
    dp = xbmcgui.DialogProgress()
    dp.create("USB BACKUP/RESTORE",'Logging Into Your Email')
    dp.update(0)
    THESMTP ,THEPORT = Servers()

    #zf = zipfile.ZipFile(LOG)
    fromaddr=ADDON.getSetting('email')
    toaddr=fromaddr
    try:filename = LOG.rsplit('\\', 1)[1]
    except:filename = LOG.rsplit('/', 1)[1]

    import datetime
    TODAY=datetime.datetime.today().strftime('[%d-%m-%Y %H:%M]')
    from email import encoders
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.mime.base import MIMEBase
    fromaddr = '"Hi Message From Yourself" <%s>'% (fromaddr)
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "Your "+filename +'  '+str(TODAY)

    body = open(THEHTML).read()

    content = MIMEText(body, 'html')
    msg.attach(content)
    part = MIMEBase('application', 'zip')
    part.set_payload(open(LOG,'rb').read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"'%filename)
    msg.attach(part)
    import smtplib
    server = smtplib.SMTP(str(THESMTP), int(THEPORT))
    dp.update(50, 'Attaching Your Email',filename)
    server.ehlo()
    server.starttls()
    server.ehlo()
    try:server.login(ADDON.getSetting('email').encode('UTF-8'),PASSWORD.encode('UTF-8'))
    except Exception as e:
        if 'gmail' in THESMTP:
            if '/answer/787' in str(e):
                e=getMessage()
        return showText('[COLOR red]ERROR !![/COLOR]',str(e).replace('\\n','[CR]'))
    text = msg.as_string()
    dp.update(75, 'Sending........',filename.replace('log','txt'))
    try:server.sendmail(fromaddr, toaddr, text)
    except Exception as e:
        if 'gmail' in THESMTP:
            if '/answer/787' in str(e):
                e=getMessage()
        return showText('[COLOR red]ERROR !![/COLOR]',str(e).replace('\\n','[CR]'))
    dp.close()
    Show_Dialog('Email Sent To','[COLOR green]'+toaddr+'[/COLOR]','Also Check Junk Folder')
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def send_email(TOWHO,LOG):
    PASSWORD=EmailPass()
    dp = xbmcgui.DialogProgress()
    dp.create(".Kodi Log Emailer",'Logging Into Your Email')
    dp.update(0)
    THESMTP ,THEPORT = Servers()

    fromaddr=ADDON.getSetting('email')
    if TOWHO =='ME':
        toaddr=fromaddr
    else:
        toaddr=getOther()

    if toaddr =='[COLOR red]Cancel[/COLOR]':
        Show_Dialog('No Email Sent','','Email Cancelled')
    else:    
        import datetime
        TODAY=datetime.datetime.today().strftime('[%d-%m-%Y %H:%M]')

        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText
        fromaddr = '"Hi Message From Yourself" <%s>'% (fromaddr)
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = "Your Kodi Log "+str(TODAY)

        body = open(THEHTML).read()

        content = MIMEText(body, 'html')
        msg.attach(content)

        try:filename = LOG.rsplit('\\', 1)[1]
        except:filename = LOG.rsplit('/', 1)[1]

        f = file(LOG)
        attachment = MIMEText(f.read())
        attachment.add_header('Content-Disposition', 'attachment', filename=filename.replace('log','txt'))           
        msg.attach(attachment)
        import smtplib
        server = smtplib.SMTP(str(THESMTP), int(THEPORT))
        dp.update(50, 'Attaching Your Email',filename.replace('log','txt'))
        server.ehlo()
        server.starttls()
        server.ehlo()
        try:server.login(ADDON.getSetting('email').encode('UTF-8'),PASSWORD.encode('UTF-8'))
        except Exception as e:
            if 'gmail' in THESMTP:
                if '/answer/787' in str(e):
                    e=getMessage()
            return showText('[COLOR red]ERROR !![/COLOR]',str(e).replace('\\n','[CR]'))
        text = msg.as_string()
        dp.update(75, 'Sending........',filename.replace('log','txt'))
        server.sendmail(fromaddr, toaddr, text)
        dp.close()
        Show_Dialog('Email Sent To','[COLOR green]'+toaddr+'[/COLOR]','Also Check Junk Folder')
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def add_movie(self, title, alt_title, year, video_id, build_url):
        """Adds a movie to the local db, generates & persists the strm file

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        alt_title : :obj:`str`
            Alternative title given by the user

        year : :obj:`int`
            Release year of the show

        video_id : :obj:`str`
            ID of the video to be played

        build_url : :obj:`fn`
            Function to generate the stream url
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        movie_meta = '%s (%d)' % (title, year)
        folder = re.sub(r'[?|$|!|:|#]', r'', alt_title)
        dirname = self.kodi_helper.check_folder_path(
            path=os.path.join(self.movie_path, folder))
        filename = os.path.join(dirname, movie_meta + '.strm')
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(650), movie_meta)
        if xbmcvfs.exists(filename):
            return
        if not xbmcvfs.exists(dirname):
            xbmcvfs.mkdirs(dirname)
        if self.movie_exists(title=title, year=year) is False:
            progress.update(50)
            time.sleep(0.5)
            self.db[self.movies_label][movie_meta] = {'alt_title': alt_title}
            self._update_local_db(filename=self.db_filepath, db=self.db)
        url = build_url({'action': 'play_video', 'video_id': video_id})
        self.write_strm_file(path=filename, url=url, title_player=movie_meta)
        progress.update(100)
        time.sleep(1)
        progress.close()
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def add_show(self, title, alt_title, episodes, build_url):
        """Adds a show to the local db, generates & persists the strm files

        Note: Can also used to store complete seasons or single episodes,
        it all depends on what is present in the episodes dictionary

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        alt_title : :obj:`str`
            Alternative title given by the user

        episodes : :obj:`dict` of :obj:`dict`
            Episodes that need to be added

        build_url : :obj:`fn`
            Function to generate the stream url
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        show_meta = '%s' % (title)
        folder = re.sub(r'[?|$|!|:|#]', r'', alt_title.encode('utf-8'))
        show_dir = self.kodi_helper.check_folder_path(
            path=os.path.join(self.tvshow_path, folder))
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(650), show_meta)
        count = 1
        if not xbmcvfs.exists(show_dir):
            xbmcvfs.mkdirs(show_dir)
        if self.show_exists(title) is False:
            self.db[self.series_label][show_meta] = {
                'seasons': [],
                'episodes': [],
                'alt_title': alt_title}
            episode_count_total = len(episodes)
            step = round(100.0 / episode_count_total, 1)
            percent = step
        for episode in episodes:
            desc = self.kodi_helper.get_local_string(20373) + ': '
            desc += str(episode.get('season'))
            long_desc = self.kodi_helper.get_local_string(20359) + ': '
            long_desc += str(episode.get('episode'))
            progress.update(
                percent=int(percent),
                line1=show_meta,
                line2=desc,
                line3=long_desc)
            self._add_episode(
                show_dir=show_dir,
                title=title,
                season=episode.get('season'),
                episode=episode.get('episode'),
                video_id=episode.get('id'),
                build_url=build_url)
            percent += step
            time.sleep(0.05)
        self._update_local_db(filename=self.db_filepath, db=self.db)
        time.sleep(1)
        progress.close()
        return show_dir
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_show(self, title):
        """Removes the DB entry & the strm files for the show given

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        label = self.series_label
        rep_str = self.db[label][title]['alt_title'].encode('utf-8')
        folder = re.sub(
            pattern=r'[?|$|!|:|#]',
            repl=r'',
            string=rep_str)
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(1210), title)
        time.sleep(0.5)
        del self.db[self.series_label][title]
        self._update_local_db(filename=self.db_filepath, db=self.db)
        show_dir = self.kodi_helper.check_folder_path(
            path=os.path.join(self.tvshow_path, folder))
        if xbmcvfs.exists(show_dir):
            show_files = xbmcvfs.listdir(show_dir)[1]
            episode_count_total = len(show_files)
            step = round(100.0 / episode_count_total, 1)
            percent = 100 - step
            for filename in show_files:
                progress.update(int(percent))
                xbmcvfs.delete(os.path.join(show_dir, filename))
                percent = percent - step
                time.sleep(0.05)
            xbmcvfs.rmdir(show_dir)
            return True
        return False
        time.sleep(1)
        progress.close()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def download_and_play(url,file_name,download_path):
    # Lanza thread
    logger.info("Active threads "+str(threading.active_count()))
    logger.info(""+repr(threading.enumerate()))
    logger.info("Starting download thread...")
    download_thread = DownloadThread(url,file_name,download_path)
    download_thread.start()
    logger.info("Download thread started")
    logger.info("Active threads "+str(threading.active_count()))
    logger.info(""+repr(threading.enumerate()))

    # Espera
    logger.info("Waiting...")

    while True:
        cancelled=False
        dialog = xbmcgui.DialogProgress()
        dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
        dialog.update(0)

        while not cancelled and download_thread.isAlive():
            dialog.update( download_thread.get_progress() , "Cancela esta ventana para empezar la reproducción", "Velocidad: "+str(int(download_thread.get_speed()/1024))+" KB/s "+str(download_thread.get_actual_size())+"MB de "+str(download_thread.get_total_size())+"MB" , "Tiempo restante: "+str( downloadtools.sec_to_hms(download_thread.get_remaining_time())) )
            xbmc.sleep(1000)

            if dialog.iscanceled():
                cancelled=True
                break

        dialog.close()

        logger.info("End of waiting")

        # Lanza el reproductor
        player = CustomPlayer()
        player.set_download_thread(download_thread)
        player.PlayStream( download_thread.get_file_name() )

        # Fin de reproducción
        logger.info("Fin de reproducción")

        if player.is_stopped():
            logger.info("Terminado por el usuario")
            break
        else:
            if not download_thread.isAlive():
                logger.info("La descarga ha terminado")
                break
            else:
                logger.info("Continua la descarga")

    # Cuando el reproductor acaba, si continúa descargando lo para ahora
    logger.info("Download thread alive="+str(download_thread.isAlive()))
    if download_thread.isAlive():
        logger.info("Killing download thread")
        download_thread.force_stop()
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def download_and_play(url,file_name,download_path):
    # Lanza thread
    logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
    logger.info("[download_and_play.py] "+repr(threading.enumerate()))
    logger.info("[download_and_play.py] Starting download thread...")
    download_thread = DownloadThread(url,file_name,download_path)
    download_thread.start()
    logger.info("[download_and_play.py] Download thread started")
    logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
    logger.info("[download_and_play.py] "+repr(threading.enumerate()))

    # Espera
    logger.info("[download_and_play.py] Waiting...")

    while True:
        cancelled=False
        dialog = xbmcgui.DialogProgress()
        dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
        dialog.update(0)

        while not cancelled and download_thread.is_alive():
            dialog.update( download_thread.get_progress() , "Cancela esta ventana para empezar la reproducción", "Velocidad: "+str(int(download_thread.get_speed()/1024))+" KB/s "+str(download_thread.get_actual_size())+"MB de "+str(download_thread.get_total_size())+"MB" , "Tiempo restante: "+str( downloadtools.sec_to_hms(download_thread.get_remaining_time())) )
            xbmc.sleep(1000)

            if dialog.iscanceled():
                cancelled=True
                break

        dialog.close()

        logger.info("[download_and_play.py] End of waiting")

        # Lanza el reproductor
        player = CustomPlayer()
        player.set_download_thread(download_thread)
        player.PlayStream( download_thread.get_file_name() )

        # Fin de reproducción
        logger.info("[download_and_play.py] Fin de reproducción")

        if player.is_stopped():
            logger.info("[download_and_play.py] Terminado por el usuario")
            break
        else:
            if not download_thread.is_alive():
                logger.info("[download_and_play.py] La descarga ha terminado")
                break
            else:
                logger.info("[download_and_play.py] Continua la descarga")

    # Cuando el reproductor acaba, si continúa descargando lo para ahora
    logger.info("[download_and_play.py] Download thread alive="+str(download_thread.is_alive()))
    if download_thread.is_alive():
        logger.info("[download_and_play.py] Killing download thread")
        download_thread.force_stop()
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def install_keymap(name, url):
    if os.path.isfile(KEYBOARD_FILE):
        try:
            os.remove(KEYBOARD_FILE)
        except:
            pass
    # Check is the packages folder exists, if not create it.
    path = xbmc.translatePath(os.path.join('special://home/addons', 'packages'))
    if not os.path.exists(path):
        os.makedirs(path)
    path_key = xbmc.translatePath(os.path.join('special://home/userdata', 'keymaps'))
    if not os.path.exists(path_key):
        os.makedirs(path_key)
    buildname = name
    dp = xbmcgui.DialogProgress()
    dp.create("Keymap Installer", "", "", "[B]Keymap: [/B]" + buildname)
    buildname = "customkeymap"
    lib = os.path.join(path, buildname + '.zip')

    try:
        os.remove(lib)
    except:
        pass

    downloader.download(url, lib, dp, timeout=120)
    addonfolder = xbmc.translatePath(os.path.join('special://', 'home'))
    time.sleep(2)
    dp.update(0, "", "Installing Please wait..", "")
    try:
        extract.all(lib, addonfolder, dp)
    except IOError, (errno, strerror):
        kodi.message("Failed to open required files", "Error code is:", strerror)
        return False
    time.sleep(1)
    try:
        os.remove(lib)
    except:
        pass

    xbmc.executebuiltin("Container.Refresh")
    dialog.ok("Custom Keymap Installed!", "     We hope you enjoy your Kodi addon experience!",
              "    Brought To You By %s " % siteTitle)
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def download(url, dest, dp = None,timeout = None):
    if timeout == None:
        timeout = 120

    try:
        if not dp:
            dp = xbmcgui.DialogProgress()
            dp.create("Status...","Checking Installation",' ', ' ')
        dp.update(0)
        start_time = time.time()
        u = urllib2.urlopen(url, timeout = timeout)
        h = u.info()
        totalSize = int(h["Content-Length"])
        fp = open(dest, 'wb')
        blockSize = 8192 #100000 # urllib.urlretrieve uses 8192
        count = 0
        while True:  # and (end - start < 15):
            if time.time() - start_time > timeout:
                kodi.message("Slow or no Download available:", 'Files could not be downloaded at this time',
                             'Please try again later, Attempting to continue...')
                break
            chunk = u.read(blockSize)
            if not chunk: break
            fp.write(chunk)
            count += 1
            if totalSize > 0:
                try:
                    percent = int(count * blockSize * 100 / totalSize)
                    dp.update(percent)
                except:
                    percent = 100
                    dp.update(percent)
                if dp.iscanceled():
                    dp.close()
                    raise Exception("Canceled")
        timetaken =  time.time() - start_time
        kodi.log('Duration of download was %.02f secs ' % timetaken )
    except socket.timeout, e:
        # For Python 2.7
        kodi.message("There was an error: %r" % e, 'Files could not be downloaded at this time', 'Please try again later, Attempting to continue...')
        return
    except urllib2.HTTPError as e:
        kodi.message("There was an error:", str(e),'Please try again later, Attempting to continue...')
        return
项目:plugin.video.zdf_de_2016    作者:generia    | 项目源码 | 文件源码
def service(self, request, response):
        pages = int(request.getParam('pages', -1))
        page = int(request.getParam('page', 1))

        query = dict(request.params)
        if 'pages' in query:
            del query['pages']

        query['from'] = ''
        query['to'] = ''
        query['sender'] = 'alle Sender'
        query['attrs'] = ''

        if 'q' not in query:
            self.info("Timer - getting search-string from keyboard ...")
            start = self.context.log.start()
            text = self._getKeyboardInput()
            self.info("Timer - getting search-string from keyboard ... done. [{} ms]", self.context.log.stop(start))
            if text is not None:
                query['q'] = text
            else:
                response.sendInfo(self._(32006))
                return

        self.info("Timer - loading results  ...")
        start = self.context.log.start()
        self._progress = xbmcgui.DialogProgress()
        try:
            msg = self._(32021)
            if pages != -1:
                msg = self._(32022, page, pages)
            self._progress.create(self._(32020), msg)
            self._progress.update(0, msg)
            self._loadResults(request, response, pages, page, query)

            # add search history entry
            self._saveQuery(query)

        #except:
        #    self.warn("Timer - loading results ... exception")            
        finally:
            self.info("Timer - loading results ... done. [{} ms]", self.context.log.stop(start))
            self._progress.close();
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def download_and_play(url, file_name, download_path):
    # Lanza thread
    logger.info("Active threads " + str(threading.active_count()))
    logger.info("" + repr(threading.enumerate()))
    logger.info("Starting download thread...")
    download_thread = DownloadThread(url, file_name, download_path)
    download_thread.start()
    logger.info("Download thread started")
    logger.info("Active threads " + str(threading.active_count()))
    logger.info("" + repr(threading.enumerate()))

    # Espera
    logger.info("Waiting...")

    while True:
        cancelled = False
        dialog = xbmcgui.DialogProgress()
        dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
        dialog.update(0)

        while not cancelled and download_thread.isAlive():
            dialog.update(download_thread.get_progress(), "Cancela esta ventana para empezar la reproducción",
                          "Velocidad: " + str(int(download_thread.get_speed() / 1024)) + " KB/s " + str(
                              download_thread.get_actual_size()) + "MB de " + str(
                              download_thread.get_total_size()) + "MB",
                          "Tiempo restante: " + str(downloadtools.sec_to_hms(download_thread.get_remaining_time())))
            xbmc.sleep(1000)

            if dialog.iscanceled():
                cancelled = True
                break

        dialog.close()

        logger.info("End of waiting")

        # Lanza el reproductor
        player = CustomPlayer()
        player.set_download_thread(download_thread)
        player.PlayStream(download_thread.get_file_name())

        # Fin de reproducción
        logger.info("Fin de reproducción")

        if player.is_stopped():
            logger.info("Terminado por el usuario")
            break
        else:
            if not download_thread.isAlive():
                logger.info("La descarga ha terminado")
                break
            else:
                logger.info("Continua la descarga")

    # Cuando el reproductor acaba, si continúa descargando lo para ahora
    logger.info("Download thread alive=" + str(download_thread.isAlive()))
    if download_thread.isAlive():
        logger.info("Killing download thread")
        download_thread.force_stop()
项目:repository.midraal    作者:midraal    | 项目源码 | 文件源码
def authenticate():
    addon = xbmcaddon.Addon()
    access_token = addon.getSetting("TRAKT_ACCESS_TOKEN")
    if access_token:
        expires = addon.getSetting("TRAKT_EXPIRES_AT")
        if time.time() > expires:
            return trakt_refresh_token()
        return access_token
    values = {"client_id": TRAKT_API_KEY}

    device_codes = requests.post(
        'https://api.trakt.tv/oauth/device/code', data=values).json()
    data = {
        "code": device_codes["device_code"],
        "client_id": TRAKT_API_KEY,
        "client_secret": TRAKT_SECRET
    }

    start = time.time()
    expires_in = device_codes["expires_in"]
    progress_dialog = xbmcgui.DialogProgress()
    progress_dialog.create(
        "Authenticate Trakt",
        "Please go to https://trakt.tv/activate and enter the code",
        str(device_codes["user_code"]))
    try:
        time_passed = 0
        while not xbmc.abortRequested and not progress_dialog.iscanceled(
        ) and time_passed < expires_in:
            try:
                response = requests.post(
                    'https://api.trakt.tv/oauth/device/token',
                    data=data).json()
            except Exception, e:
                progress = int(100 * time_passed / expires_in)
                progress_dialog.update(progress)
                xbmc.sleep(max(device_codes["interval"], 1) * 1000)
            else:
                response = response
                expires_at = time.time() + 60 * 60 * 24 * 30
                addon.setSetting("TRAKT_EXPIRES_AT", str(expires_at))
                addon.setSetting("TRAKT_ACCESS_TOKEN",
                                 response["access_token"])
                addon.setSetting("TRAKT_REFRESH_TOKEN",
                                 response["refresh_token"])
                return response["access_token"]
            time_passed = time.time() - start
    finally:
        progress_dialog.close()
        del progress_dialog
    return None