python类DialogProgress()的实例源码

proxy.py 文件源码 项目:plugin.video.brplay 作者: olavopeixoto 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
common.py 文件源码 项目:script.quasar.t411-rik91 作者: rik91 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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]
default.py 文件源码 项目:plugin.video.jen 作者: midraal 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:script.profilecleaner 作者: cibboy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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))
default.py 文件源码 项目:repository.midraal 作者: midraal 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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")
api.py 文件源码 项目:plugin.video.auvio 作者: rickybiscus 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
kodi.py 文件源码 项目:context.youtube.download 作者: anxdpanic 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
xbmctools.py 文件源码 项目:tvalacarta 作者: tvalacarta 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
default.py 文件源码 项目:catchup4kodi 作者: catchup4kodi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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()
F4MProxy.py 文件源码 项目:catchup4kodi 作者: catchup4kodi 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
F4MProxy.py 文件源码 项目:catchup4kodi 作者: catchup4kodi 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
Library.py 文件源码 项目:plugin.video.netflix 作者: asciidisco 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()
F4mProxy.py 文件源码 项目:specto 作者: mrknow 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
platformtools.py 文件源码 项目:pelisalacarta-ce 作者: pelisalacarta-ce 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def dialog_progress(heading, line1, line2=" ", line3=" "):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
platformtools.py 文件源码 项目:plugin.video.streamondemand-pureita 作者: orione7 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def dialog_progress(heading, line1, line2="", line3=""):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
xbmctools.py 文件源码 项目:plugin.video.streamondemand-pureita 作者: orione7 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
appfeed.py 文件源码 项目:plugin.video.amazon65 作者: phil65 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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()
installer.py 文件源码 项目:plugin.program.indigo 作者: tvaddonsco 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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

# ****************************************************************
installer.py 文件源码 项目:plugin.program.indigo 作者: tvaddonsco 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)


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


# #****************************************************************
installer.py 文件源码 项目:plugin.program.indigo 作者: tvaddonsco 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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]")


##############
xbmc_progress_dialog.py 文件源码 项目:plugin.video.youtube 作者: jdf76 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
xbmc_progress_dialog.py 文件源码 项目:plugin.video.youtube 作者: Kolifanes 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
platformtools.py 文件源码 项目:addon 作者: alfa-addon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def dialog_progress(heading, line1, line2=" ", line3=" "):
    dialog = xbmcgui.DialogProgress()
    dialog.create(heading, line1, line2, line3)
    return dialog
DialogProgressWrapper.py 文件源码 项目:plugin.video.9anime 作者: DxCx 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, title, progress_string):
        self._dialog = xbmcgui.DialogProgress()
        self._progress_string = progress_string
        self._dialog.create(title)
main.py 文件源码 项目:plugin.audio.bytefm 作者: kopf 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
kodihelper.py 文件源码 项目:kodi-viaplay 作者: emilsvennesson 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
backuprestore.py 文件源码 项目:script.skin.helper.skinbackup 作者: marcelveldt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
download_and_play.py 文件源码 项目:tvalacarta 作者: tvalacarta 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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()
default.py 文件源码 项目:catchup4kodi 作者: catchup4kodi 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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")
default.py 文件源码 项目:catchup4kodi 作者: catchup4kodi 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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')


问题


面经


文章

微信
公众号

扫码关注公众号