Python xbmcgui.DialogProgress Examples


The following are 31 code examples for showing how to use xbmcgui.DialogProgress. They are extracted from open source Python projects. You can click vote to vote up the examples you like, or click vote to vote down the exmaples you don't like. Your votes will be used in our system to extract more high-quality examples.

You may also check out all available functions/classes of the module xbmcgui , or try the search function .


Example 1

From project debianlink-xbmc-mediastream, under directory MediaStream/extras/XBMC Lyrics/resources/lib, in source file update.py.

Score: 10
vote
vote
def __init__( self ):
        self.base_url = "http://xbmc-scripting.googlecode.com/svn"
        self.dialog = xbmcgui.DialogProgress()
        new = self._check_for_new_version()
        if ( new ): self._update_script()
        else: xbmcgui.Dialog().ok( __scriptname__, _( 1000 + ( 30 * ( new is None ) ) ) )
            
     

Example 2

From project debianlink-xbmc-mediastream, under directory programs/SVN Repo Installer/installerAPI, in source file xbmcplugin_downloader.py.

Score: 10
vote
vote
def __init__( self ):
        self.dialog = xbmcgui.DialogProgress()
        # get the repository info
        self._get_repo_info()
        # parse sys.argv for our current url
        self._parse_argv()
        # create the script/plugin/skin title
        self.title = self.args.download_url.split( "/" )[ -2 ].replace( "%20", " " )
        # get the list
        self._download_item()

     

Example 3

From project Transmission-XBMC, under directory resources/lib, in source file gui.py.

Score: 10
vote
vote
def onInit(self):
        p = xbmcgui.DialogProgress()
        p.create(_(32000), _(32001)) # 'Transmission', 'Connecting to Transmission'
        try:
            self.transmission = common.get_rpc_client()
        except:
            p.close()
            self.close()
            (type, e, traceback) = sys.exc_info()
            message = _(32900) # Unexpected error
            if type is transmissionrpc.TransmissionError:
                if e.original:
                    if e.original.code is 401:
                        message = _(32902) # Invalid auth
                    else:
                        message = _(32901) # Unable to connect
                if xbmcgui.Dialog().yesno(_(32002), message, _(32003)):
                    __settings__.openSettings()
            elif type is ValueError:
                # In python 2.4, urllib2.HTTPDigestAuthHandler will barf up a lung
                # if auth fails and the server wants non-digest authentication
                message = _(32902) # Invalid auth
                if xbmcgui.Dialog().yesno(_(32002), message, _(32003)):
                    __settings__.openSettings()
            else:
                message = _(32900) # Unexpected error
                xbmcgui.Dialog().ok(_(32002), message)
            return False
        self.updateTorrents()
        p.close()
        self.timer = threading.Timer(UPDATE_INTERVAL, self.updateTorrents)
        self.timer.start()
     

Example 4

From project plugin.video.mlbtv, under directory resources/libs, in source file mc.py.

Score: 10
vote
vote
def ShowDialogWait():
    progress = xbmcgui.DialogProgress()
    progress.create('XBMC - Addon', 'Loading...')
    return progress
    #xbmcgui.lock()

 

Example 5

From project plugin.video.freplay-master, under directory resources/lib/channels, in source file favourites.py.

Score: 10
vote
vote
def list_videos(channel,show_title):
    videos=[]                
    if show_title=='unseen':
        if os.path.exists(globalvar.FAVOURITES_FILE) :
            #Read favourites
            fileFav = open(globalvar.FAVOURITES_FILE)
            jsonfav = json.loads(fileFav.read())
            pDialog = xbmcgui.DialogProgress()
            ret = pDialog.create(globalvar.LANGUAGE(33002).encode('utf-8'),'')
            i=1
            for show_folder in  jsonfav['favourites']:
                show_folder = [x.encode('utf-8') for x in show_folder]
                pDialog.update((i-1)*100/len(jsonfav['favourites']),globalvar.LANGUAGE(33003).encode('utf-8')+ show_folder[2] + ' - ' + str(i) + '/' +  str(len(jsonfav['favourites'])))
                videos+=(list_videos(show_folder[0],show_folder[1]));
                i+=1
            fileFav.close()
            pDialog.close()
    else:
        videos=globalvar.channels[channel][1].list_videos(channel,show_title) 
    return videos

 

Example 6

From project plugin.video.pelisalacarta-master, under directory platformcode/xbmc, in source file xbmctools.py.

Score: 10
vote
vote
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

 

Example 7

From project plugin.video.torrenter-master, under directory , in source file Libtorrent.py.

Score: 10
vote
vote
def getMagnetInfo(self):
        magnetSettings = {
            'url': self.magnetLink,
            'save_path': self.storageDirectory,
            'storage_mode': self.lt.storage_mode_t(0),
            'paused': True,
            #'auto_managed': True,
            #'duplicate_is_error': True
        }
        progressBar = xbmcgui.DialogProgress()
        progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting'))
        #try:
        self.torrentHandle = self.session.add_torrent(magnetSettings)
        #except:
        #    self.torrentHandle = self.lt.add_magnet_uri(self.session, self.magnetLink, magnetSettings)
        iterator = 0
        while iterator < 100:
            xbmc.sleep(500)
            progressBar.update(iterator, Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')+'.' * (iterator % 4), ' ')
            iterator += 1
            if progressBar.iscanceled():
                progressBar.update(0)
                progressBar.close()
                return
            if self.torrentHandle.status().has_metadata:
                iterator = 100
        progressBar.update(0)
        progressBar.close()
        if self.torrentHandle.status().has_metadata:
            try:
                info = self.torrentHandle.torrent_file()
            except:
                info = self.torrentHandle.get_torrent_info()
            return info

     

Example 8

From project repository.arabic.xbmc-addons, under directory plugin.video.shahidmbcnet/resources/community, in source file livetvPlayer.py.

Score: 10
vote
vote
def PlayStream(sourceEtree, urlSoup, name, url):
	try:
		playpath=urlSoup.chnumber.text
		pDialog = xbmcgui.DialogProgress()
		pDialog.create('XBMC', 'Communicating with Livetv')
		pDialog.update(40, 'Attempting to Login')
		code=getcode(shoudforceLogin());
		print 'firstCode',code
		if not code or code[0:1]=="w":
			pDialog.update(40, 'Refreshing Login')
			code=getcode(True);
			print 'secondCode',code
		liveLink= sourceEtree.findtext('rtmpstring')
		pDialog.update(80, 'Login Completed, now playing')
		print 'rtmpstring',liveLink
		#liveLink=liveLink%(playpath,match)
		liveLink=liveLink%(playpath,code)
		name+='-LiveTV'
		print 'liveLink',liveLink
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
		pDialog.close()
		player = CustomPlayer.MyXBMCPlayer()
		start = time.time()
		#xbmc.Player().play( liveLink,listitem)
		player.play( liveLink,listitem)
		while player.is_active:
			xbmc.sleep(200)
		#return player.urlplayed
		#done = time.time()
		done = time.time()
		elapsed = done - start
		if player.urlplayed and elapsed>=3:
			return True
		else:
			return False 
	except:
		traceback.print_exc(file=sys.stdout)    
	return False    

 

Example 9

From project script.sportscenter-master, under directory resources/lib/centerutils, in source file downloadtools.py.

Score: 10
vote
vote
def extract(self,file_tar,destination):
	dp = xbmcgui.DialogProgress()
	dp.create(translate(40000),translate(40044))
	tar = tarfile.open(file_tar)
	tar.extractall(destination)
	dp.update(100)
	tar.close()
	dp.close()
		
 

Example 10

From project plugin.video.vimeo-master, under directory resources/lib/kodion/impl/xbmc, in source file xbmc_progress_dialog.py.

Score: 10
vote
vote
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

     

Example 11

From project xbmc-israel, under directory plugin.video.makoTV.video, in source file Mako.py.

Score: 10
vote
vote
def getSeason(seasonURL, seasonId):
    # obtain the same page as before but parse the wanted season
    seasonLoader = MakoSeasonLoader.MakoSeasonLoader(__properties, seasonURL, seasonId)
    seasonDict = seasonLoader.loadURL()
    if 'vods' not in seasonDict:
        xbmc.log('***** Mako: didnt find vods in season dict for season with id %s' % (seasonId), xbmc.LOGERROR)
    else:
        # get the vod items and create them
	xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_TITLE)
	progress = xbmcgui.DialogProgress()
	progress.create('Mako TV', 'Loading VOD items...')
	vodItems = seasonDict['vods']
	step = int(100 / len(vodItems))
	perc = 0
	for vodItem in vodItems:
	    # load each item URL since we want all the data available before play
	    url = vodItem['link']
	    xbmc.log('***** Mako: loading vod item page: %s' % (url), xbmc.LOGDEBUG)
	    itemLoader = MakoVodItemLoader.MakoVodItemLoader(__properties, url)
	    vodItemDict = itemLoader.loadURL()
	    vodItemNode = MakoVodItemNode.MakoVodItemNode(vodItemDict)
	    addVodItemView(vodItemNode)
	    perc = perc + step
	    progress.update(perc, 'Mako TV', 'Loading VOD items...')
	progress.close

 

Example 12

From project xbmc-israel, under directory plugin.video.KIDSIL/resources/lib, in source file downloader.py.

Score: 10
vote
vote
def download(url, dest, dp = None):
    if not dp:
        dp = xbmcgui.DialogProgress()
        dp.create("XBMCTALK WIZARD","Downloading & Copying File",' ', ' ')
    dp.update(0)
    start_time=time.time()
    urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time))
     
 

Example 13

From project xbmc-israel, under directory plugin.video.KIDSIL, in source file default.py.

Score: 10
vote
vote
def TvMode(user):
    playlists=PlaylistsFromUser(user)
    if playlists==[] :  #no playlists on  youtube channel
        dialog = xbmcgui.Dialog()
        ok = dialog.ok('XBMC', 'No TV mode for this Channel.')
        CATEGORIES()
    #print "str is" +  str(random.choice(playlists)[0])
    else:
        pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        pl.clear()
        dp= xbmcgui.DialogProgress()
        dp.create('KIDSIL BY o2Ri','Preapring TV mode')
        for i in range (1,21) :  #20  RANDOM PROGRAMS IN TV MODE 
            dp.update(i*5,"Please wait ","Will take few minutes")
            #print str (playlists)
            ran=str(random.choice(playlists)[0])
            print "kkkkkkkkkkkkkk"+str(ran)
            finalurl,title,thumb= RanFromPlayList(ran)
            liz = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumb)
            liz.setInfo( type="Video", infoLabels={ "Title": title} )
            liz.setProperty("IsPlayable","true")
            pl.add(finalurl, liz)
        xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(pl)
    
 

Example 14

From project plugin.video.telkkarista-master, under directory , in source file default.py.

Score: 10
vote
vote
def speedtest():
  #get a list of servers and do a speedtest. Store the resulting prioritized list of hosts in a setting.
  global PLAYROOT
  dp = xbmcgui.DialogProgress() 
  dp.create('Running speedtests')
  servers=apiget('cache/get','')
  for ix,server in enumerate(servers):
    dp.update(ix*100/len(servers),server['country'],server['host'])
    if server['status']=='up':
      url = 'http://%s/speedtest_1mb.bin' % (server['host'])
      start=time.time()
      requests.get(url)
      delta=time.time()-start
      server['speed']=8.0/delta
    else:
      server['speed']=0.0
    if dp.iscanceled(): #TODO: it will fail below if not all servers have a speed....
      break
  dp.close()
  servers=sorted(servers, key=lambda k: -k['speed'])
  xbmc.log('telkkarista speedtest result:'+repr(servers))
  hosts=[k['host'] for k in servers]
  telkkarista_addon.setSetting("preferredhosts",",".join(hosts))
  PLAYROOT=hosts[0]
  telkkarista_addon.setSetting("currentcachehost",PLAYROOT) #Found preferredhost
  
 

Example 15

From project lolabitsXBMC-master, under directory plugin.video.lolabits, in source file default.py.

Score: 8
vote
vote
def comecarvideo(name,url,playterm,legendas=None):        
        sitename='Lolabits - '+name      
        playeractivo = xbmc.getCondVisibility('Player.HasMedia')
        if playterm=='download':
              fazerdownload(name,url)
              return
        thumbnail=''
        playlist = xbmc.PlayList(1)
        if not playterm and playeractivo==0: playlist.clear()
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        #listitem.setInfo("Video", {"Title":"Balas & Bolinhos","year":2001})
        title='%s' % (name.split('[/B]')[0].replace('[B]',''))

        listitem.setInfo("Video", {"Title":title})
        listitem.setInfo("Music", {"Title":title})
        listitem.setProperty('mimetype', 'video/x-msvideo')
        listitem.setProperty('IsPlayable', 'true')
        if playterm <> 'playlist':
              dialogWait = xbmcgui.DialogProgress()
              dialogWait.create('Video', 'Cargando')
        playlist.add(url, listitem)
        if playterm <> 'playlist':		
              dialogWait.close()
              del dialogWait
        xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
        if not playterm and playeractivo==0:
              
              xbmcPlayer.play(playlist)
        if legendas!=None: xbmcPlayer.setSubtitles(legendas)
        else:
			if selfAddon.getSetting("subtitles") == 'true': 
				try: totalTime = xbmc.Player().getTotalTime()
				except: totalTime = 0
				print '##totaltime',totalTime
				if totalTime >= int(selfAddon.getSetting("minsize"))*60:
					print '#pesquisar legendas'
					from resources.lib import subtitles
					legendas = subtitles.getsubtitles(name,selfAddon.getSetting("sublang1"),selfAddon.getSetting("sublang2"))
					if legendas!=None: xbmcPlayer.setSubtitles(legendas)
        if playterm=='playlist': xbmc.executebuiltin("XBMC.Notification("+sitename+","+traducao(40039)+",'500000',"+iconpequeno.encode('utf-8')+")")

 

Example 16

From project plugin.video.pelisalacarta-master, under directory platformcode/xbmc, in source file download_and_play.py.

Score: 8
vote
vote
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()


 

Example 17

From project plugin.video.torrenter-master, under directory , in source file Player.py.

Score: 8
vote
vote
def buffer(self):
        iterator = 0
        progressBar = xbmcgui.DialogProgress()
        progressBar.create(self.localize('Please Wait') + str(' [%s]' % str(self.torrent.lt.version)),
                           self.localize('Seeds searching.'))
        if self.subs_dl:
            subs = self.torrent.getSubsIds(os.path.basename(self.torrent.getFilePath(self.contentId)))
            if len(subs) > 0:
                for ind, title in subs:
                    self.torrent.continueSession(ind)
        num_pieces = int(self.torrent.torrentFileInfo.num_pieces())
        xbmc.sleep(1000)
        self.torrent.torrentHandle.force_dht_announce()
        while iterator < 100:
            self.torrent.debug()
            downloadedSize = self.torrent.torrentHandle.file_progress()[self.contentId]
            status = self.torrent.torrentHandle.status()
            iterator = int(status.progress * 100)
            if status.state == 0 or (status.progress == 0 and status.num_pieces > 0):
                iterator = int(status.num_pieces * 100 / num_pieces)
                if iterator > 99: iterator = 99
                progressBar.update(iterator, self.localize('Checking preloaded files...'), ' ', ' ')
            elif status.state == 3:
                dialogText = self.localize('Preloaded: ') + str(downloadedSize / 1024 / 1024) + ' MB / ' + str(
                    self.fullSize / 1024 / 1024) + ' MB'
                peersText = ' [%s: %s; %s: %s]' % (
                    self.localize('Seeds'), str(self.torrent.getSeeds()), self.localize('Peers'),
                    str(self.torrent.getPeers()),)
                speedsText = '%s: %s Mbit/s; %s: %s Mbit/s' % (
                    self.localize('Downloading'), str(self.torrent.getDownloadRate() * 8 / 1000000),
                    self.localize('Uploading'), str(self.torrent.getUploadRate() * 8 / 1000000))
                if self.debug:
                    peersText=peersText + ' ' + self.torrent.get_debug_info('dht_state')
                    dialogText=dialogText.replace(self.localize('Preloaded: '),'') + ' ' + self.torrent.get_debug_info('trackers_sum')
                progressBar.update(iterator, self.localize('Seeds searching.') + peersText, dialogText,
                                   speedsText)
            else:
                progressBar.update(iterator, self.localize('UNKNOWN STATUS'), ' ', ' ')
            if progressBar.iscanceled():
                progressBar.update(0)
                progressBar.close()
                self.torrent.threadComplete = True
                self.torrent.checkThread()
                return
            xbmc.sleep(1000)
        self.torrent.session.remove_torrent(self.torrent.torrentHandle)
        progressBar.update(0)
        progressBar.close()
        return True

     

Example 18

From project plugin.video.torrenter-master, under directory , in source file functions.py.

Score: 8
vote
vote
def search(url, searchersList, isApi=None):
    from threading import Thread
    try:
        from Queue import Queue, Empty
    except ImportError:
        from queue import Queue, Empty

    num_threads=__settings__.getSetting('num_threads')
    if num_threads and int(num_threads)>0:
        num_threads = int(num_threads)
    else:
        num_threads = 3
    queue = Queue()
    result = {}
    iterator, filesList, left_searchers = 0, [], []
    timeout_multi=int(sys.modules["__main__"].__settings__.getSetting("timeout"))
    left_searchers.extend(searchersList)
    if not isApi:
        progressBar = xbmcgui.DialogProgress()
        progressBar.create(Localization.localize('Please Wait'), Localization.localize('Materials are loading now.'))

    class CleanExit:
        pass

    def search_one(i, q):
        while True:
            try:
                if not isApi and progressBar.iscanceled():
                    progressBar.update(0)
                    progressBar.close()
                    return
                iterator=100*int(len(searchersList)-len(left_searchers))/len(searchersList)
                if not isApi:
                    progressBar.update(int(iterator), join_list(left_searchers, replace='.py'))
                searcherFile = q.get_nowait()
                if searcherFile == CleanExit:
                    return
                searcher=searcherFile.replace('.py','')
                print "Thread %s: Searching at %s" % (i, searcher)
                result[searcherFile]=Searchers().searchWithSearcher(url, searcher)
                left_searchers.remove(searcherFile)
                q.task_done()
            except Empty:
                pass

    workers=[]
    for i in range(num_threads):
        worker = Thread(target=search_one, args=(i, queue))
        worker.setDaemon(True)
        worker.start()
        workers.append(worker)

    for searcherFile in searchersList:
        queue.put(searcherFile)

    print "Main Thread Waiting"
    queue.join()
    for i in range(num_threads):
        queue.put(CleanExit)

    print "Main Thread Waiting for Threads"
    for w in workers:
        w.join()

    print "Done"

    if not isApi:
        progressBar.update(0)
        progressBar.close()

    for k in result.keys():
        filesList.extend(result[k])
    return filesList


 

Example 19

From project plugin.video.torrenter-master, under directory , in source file BTClientPlayer.py.

Score: 8
vote
vote
def buffer(self):
        iterator = 0
        progressBar = xbmcgui.DialogProgress()
        progressBar.create('%s [%s]' % (self.__class__.__name__,str(self.lt.version)),
                           self.localize('Seeds searching.'))
        while not self.c.is_file_ready:#iterator < 100:
            iterator = 0
            ready_list=[]
            status = self.c.get_normalized_status()
            conditions=[status['state'] in ['downloading', 'finished', 'seeding'], status['desired_rate'] > 0 or status['progress'] > 0.01,
                        status['progress'] > 0.005, self.c.is_file_ready,# or status['progress'] > 0.02
                        (status['download_rate'] > status['desired_rate'] or
                        status['download_rate'] * int(status['progress'] * 100) > status['desired_rate'])]
            for cond in conditions:
                if cond:
                    ready_list.append(True)
                    iterator+=100/len(conditions)
                else:
                    ready_list.append(False)

            speedsText = '%s: %s Mbit/s %s %s: %s Mbit/s' % (self.localize('Download speed'),str(status['download_rate'] * 8 / 1000000),
                                                   '[COLOR=green]>[/COLOR]' if ready_list[4] else '[COLOR=red]<[/COLOR]',
                                              self.localize('Bitrate'), str(int(status['desired_rate'] * 8 / (1024 * 1024))) if status['desired_rate'] else 0,)

            if status['state'] in ['queued','checking','checking fastresume'] or (status['progress'] == 0 and status['num_pieces'] > 0):
                progressBar.update(iterator, self.localize('Checking preloaded files...'), speedsText, ' ')

            elif status['state'] in ['downloading', 'finished', 'seeding']:
                dialogText = self.localize('Preloaded: ') + '%s MB %s %s MB (%s MB)' % \
                        (str(status['downloaded'] / 1024 / 1024), '[COLOR=green]>[/COLOR]' if ready_list[2] else '[COLOR=red]<[/COLOR]', str(status['total_size'] / 1024 / 1024 /200), str(status['total_size'] / 1024 / 1024))
                peersText = '%s: %s [%s: %s; %s: %s]' % (self.localize('File ready: '), '[COLOR=green]YES[/COLOR]' if ready_list[3] else '[COLOR=red]NO[/COLOR]',
                                self.localize('Seeds'), str(status['seeds_connected']), self.localize('Peers'), str(status['peers_connected']),)
                progressBar.update(iterator, peersText, speedsText, dialogText,
                                   )
            else:
                progressBar.update(iterator, self.localize('UNKNOWN STATUS'), ' ', ' ')
            if progressBar.iscanceled():
                self.on_exit()
                break
            xbmc.sleep(1000)
        progressBar.update(0)
        progressBar.close()
        return True

     

Example 20

From project repository.arabic.xbmc-addons, under directory plugin.video.shahidmbcnet/resources/community, in source file genericPlayer.py.

Score: 8
vote
vote
def PlayStream(sourceEtree, urlSoup, name, url):
	try:
		#url = urlSoup.url.text
		pDialog = xbmcgui.DialogProgress()
		pDialog.create('XBMC', 'Parsing the xml file')
		pDialog.update(10, 'fetching channel info')
		title=''
		link=''
		sc=''
		try:
			title=urlSoup.item.title.text
			
			link=urlSoup.item.link.text
			sc=sourceEtree.findtext('sname')
		except: pass
		if link=='':
			timeD = 2000  #in miliseconds
			line1="couldn't read title and link"
			xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
			return False
		regexs = urlSoup.find('regex')
		pDialog.update(80, 'Parsing info')
		if (not regexs==None) and len(regexs)>0:
			liveLink=	getRegexParsed(urlSoup,link)
		else:
			liveLink=	link
		liveLink=liveLink
		if len(liveLink)==0:
			timeD = 2000  #in miliseconds
			line1="couldn't read title and link"
			xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
			return False
			
		timeD = 2000  #in miliseconds
		line1="Resource found,playing now."
		pDialog.update(80, line1)
		liveLink=replaceSettingsVariables(liveLink)
		name+='-'+sc+':'+title
		print 'liveLink',liveLink
		pDialog.close()
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
		player = CustomPlayer.MyXBMCPlayer()
		start = time.time() 
		#xbmc.Player().play( liveLink,listitem)
		player.play( liveLink,listitem)
		while player.is_active:
			xbmc.sleep(200)
		#return player.urlplayed
		done = time.time()
		elapsed = done - start
		if player.urlplayed and elapsed>=3:
			return True
		else:
			return False  
	except:
		traceback.print_exc(file=sys.stdout)    
	return False  

 

Example 21

From project repository.arabic.xbmc-addons, under directory plugin.video.shahidmbcnet/resources/community, in source file teledunetPlayer.py.

Score: 8
vote
vote
def PlayStream(sourceEtree, urlSoup, name, url):
	try:
		channelId = urlSoup.url.text
		pDialog = xbmcgui.DialogProgress()
		pDialog.create('XBMC', 'Communicating with Teledunet')
		pDialog.update(10, 'fetching channel page')
		loginName=selfAddon.getSetting( "teledunetTvLogin" )

		if not (loginName==None or loginName==""):
			cookieJar,loginPerformed= getCookieJar(shoudforceLogin())
			if cookieJar and not loginPerformed:
				print 'adding cookie jar'
				now_datetime=datetime.datetime.now()
				selfAddon.setSetting( id="lastteledunetLogin" ,value=now_datetime.strftime("%Y-%m-%d %H:%M:%S"))
				cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
				opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
				opener = urllib2.install_opener(opener)
			
		if 1==1:
			newURL='http://www.teledunet.com/mobile/?con'
			print 'newURL',newURL
			req = urllib2.Request(newURL)
			req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
			req.add_header('Referer',newURL)
			response = urllib2.urlopen(req)
			link=response.read()
			response.close()
			match =re.findall('aut=\'\?id0=(.*?)\'', link)
			print match
			timesegment=match[0];str(long(float(match[0])))
			try:
				rtmp =re.findall(('rtmp://(.*?)/%s\''%channelId), link)[0]
				rtmp='rtmp://%s/%s'%(rtmp,channelId)
				#if '5.135.134.110' in rtmp and 'bein' in channelId:
				#	rtmp=rtmp.replace('5.135.134.110','www.teledunet.com')
			except:
				traceback.print_exc(file=sys.stdout)  
				rtmp='rtmp://5.135.134.110:1935/teledunet/%s'%(channelId)
		pDialog.update(80, 'trying to play')
		liveLink= sourceEtree.findtext('rtmpstring');

		print 'rtmpstring',liveLink,rtmp
#		liveLink=liveLink%(rtmp,channelId,match,channelId,channelId)
		liveLink=liveLink%(rtmp,channelId,timesegment,channelId)
		name+='-Teledunet'
		print 'liveLink',liveLink
		pDialog.close()
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
		player = CustomPlayer.MyXBMCPlayer()
		#xbmc.Player().play( liveLink,listitem)
		start = time.time()  
		player.play( liveLink,listitem)  
		while player.is_active:
			xbmc.sleep(200)
		#return player.urlplayed
		done = time.time()
		elapsed = done - start
		if player.urlplayed and elapsed>=3:
			return True
		else:
			return False
	except:
		traceback.print_exc(file=sys.stdout)    
	return False  



 

Example 22

From project repository.arabic.xbmc-addons, under directory plugin.video.shahidmbcnet, in source file default.py.

Score: 8
vote
vote
def RefreshResources(auto=False):
#	print Fromurl
	pDialog = xbmcgui.DialogProgress()
	if auto:
		ret = pDialog.create('XBMC', 'Daily Auto loading Fetching resources...')
	else:
		ret = pDialog.create('XBMC', 'Fetching resources...')
	baseUrlForDownload='https://raw.githubusercontent.com/Shani-08/ShaniXBMCWork/master/plugin.video.shahidmbcnet/resources/community/'
	Fromurl=baseUrlForDownload+'Resources.xml'
	req = urllib2.Request(Fromurl)
	req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
	response = urllib2.urlopen(req)
	data=response.read()
	response.close()
	#data='<resources><file fname="Categories.xml"/><file fname="palestinecoolUrls.xml" url="http://goo.gl/yNlwCM"/></resources>'
	pDialog.update(20, 'Importing modules...')
	soup= BeautifulSOAP(data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	resources=soup('file')
	fileno=1
	totalFile = len(resources)
	
	for rfile in resources:
		progr = (fileno*80)/totalFile
		fname = rfile['fname']
		remoteUrl=None
		try:
			remoteUrl = rfile['url']
		except: pass
		if remoteUrl:
			fileToDownload = remoteUrl
		else:
			fileToDownload = baseUrlForDownload+fname
		#print fileToDownload
		req = urllib2.Request(fileToDownload)
		req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
		response = urllib2.urlopen(req)
		data=response.read()
		if len(data)>0:
			with open(os.path.join(communityStreamPath, fname), "wb") as filewriter:
				filewriter.write(data)
			pDialog.update(20+progr, 'imported ...'+fname)
		else:
			pDialog.update(20+progr, 'Failed..zero byte.'+fname)
		fileno+=1
	pDialog.close()
	dialog = xbmcgui.Dialog()
	ok = dialog.ok('XBMC', 'Download finished. Close close Addon and come back')

 

Example 23

From project repository.arabic.xbmc-addons, under directory plugin.video.dardarkom, in source file default.py.

Score: 8
vote
vote
def indexIndian(url,initial,max,plot,rating,genre,cast,year,duration,writer,director):
	try:
		for counter in range(initial,max+1):
			dlg = xbmcgui.DialogProgress()
			line1 = 'Getting the movies...'
			dlg.create('In progress, Please wait...', line1)
			percent = int((counter * 100) / max)
			label = str(counter)+" out of "+str(max)+" pages"
			dlg.update(percent, line1, label)
			
			req = urllib2.Request(url+'/page/'+str(counter)+'/')
			response = urllib2.urlopen(req)
			link=response.read()
			url_target=(re.compile('<a href="(.+?)"><font color="(.+?)">(.+?)</font>   </a>').findall(link))
			url_2=(re.compile('<a href="(.+?)" onclick="return hs.expand').findall(link))
			target= re.findall(r'<div  style="font-family:Tahoma;font-size:9pt;color: #5C7287;;text-align:right;padding:10px; margin-right:10px;">(.*?)\s(.*?)</div>', link, re.DOTALL)
			name=''
			
			for (itr,items,it) in itertools.izip  (url_target,url_2,target):
				name=str( itr[2]).strip()
				path =str(itr[0]).strip()
				image=str(items).strip()
				plot=str( it[1]).strip()
				plot=str(plot).replace("&quot;","").replace(";quot&","")
				name2=removeArabicCharsFromString(name)
				myResult=(getImdbCred(name2))
				myFanart=str(myResult["Poster"]).strip()
				rating=str(myResult["imdbRating"]).strip()
				genre=str(myResult["Genre"]).strip()
				cast=str(myResult["Actors"]).strip()
				year=str(myResult["Year"]).strip()
				duration=str(myResult["Runtime"]).strip()
				writer=str(myResult["Writer"]).strip()
				director=str(myResult["Director"]).strip()
				genre = "[COLOR=%s]%s[/COLOR]" % ( "FF00FF00", genre  )
				year = "[COLOR=%s]%s[/COLOR]" % ( "FFFF0000  ", year  )
				if  myResult["Plot"]=="No Plot found" and myResult["Poster"]=="No Poster found" and rating=="No Rating found" and genre=="No Genre found" and year=="No Year found" and cast=="No Actors found" and duration=="No Runtime found" and writer=="No Writer found" and director=="No Director found":
					addLink(name+" "+genre+" "+year,path,2,image,image,plot,' ',"N/A","N/A","N/A","N/A","N/A","N/A")
				else:
					plot2= getImdbCred(name2)["Plot"]
					combinedPlot=str(plot)+"\n"+"\n"+str(plot2)+"\n"+"Actors: "+str(cast)
					addLink(name+" "+genre+" "+year,path,2,image,myFanart,combinedPlot,rating,genre,cast,year,duration,writer,director)
					
			if len(str(name))<2:
				url_target2=(re.compile('<a href="(.+?)">(.+?)</a></center>').findall(link))
				url_2=(re.compile('<center><div class="boxshort"> <img src="(.+?)" alt="').findall(link))
				for (itr,items) in itertools.izip  (url_target2,url_2):
					path=str( itr[0]).strip()
					name=str( itr[1]).strip()
					image=str(items).strip()
					name2=removeArabicCharsFromString(name)
					myResult=(getImdbCred(name2))
					myFanart=str(myResult["Poster"]).strip()
					rating=str(myResult["imdbRating"]).strip()
					genre=str(myResult["Genre"]).strip()
					cast=str(myResult["Actors"]).strip()
					year=str(myResult["Year"]).strip()
					duration=str(myResult["Runtime"]).strip()
					writer=str(myResult["Writer"]).strip()
					director=str(myResult["Director"]).strip()
					genre = "[COLOR=%s]%s[/COLOR]" % ( "FF00FF00", genre  )
					year = "[COLOR=%s]%s[/COLOR]" % ( "FFFF0000  ", year  )
					if  myResult["Plot"]=="No Plot found" and myResult["Poster"]=="No Poster found" and rating=="No Rating found" and genre=="No Genre found" and year=="No Year found" and cast=="No Actors found" and duration=="No Runtime found" and writer=="No Writer found" and director=="No Director found":
						addLink(name+" "+genre+" "+year,path,2,image,image,plot,' ',"N/A","N/A","N/A","N/A","N/A","N/A")
					else:
						plot2= getImdbCred(name2)["Plot"]
						combinedPlot=str(plot)+"\n"+"\n"+str(plot2)+"\n"+"Actors: "+str(cast)
						addLink(name+" "+genre+" "+year,path,2,image,myFanart,combinedPlot,rating,genre,cast,year,duration,writer,director)
	except:
		pass
				
	initial=initial+10
	max=max + 10
	
	addDir('<<<< ????? ????? ?????',url,4,'http://www.theonestopfunshop.com/product_images/uploaded_images/movie-night.jpg',initial,max,'DESCRIPTION','0.0')

	
 

Example 24

From project plex, under directory scripts, in source file guibuilder.py.

Score: 8
vote
vote
def __init__(self, win, skinXML, imagePath='', title='GUI Builder', line1='', dlg=None, pct=0, fastMethod=False, debug=False):
		try:
			self.debug							= debug
			self.debugWrite('guibuilder.py', 2)
			self.win 							= win
			self.win.SUCCEEDED	 			= True
			self.skinXML 						= skinXML[skinXML.rfind('\\') + 1:]
			self.fastMethod					= fastMethod
			self.pct 							= pct
			self.lineno 							= line1 != ''
			self.lines 							= [''] * 3
			self.lines[0] 						= line1
			self.lines[self.lineno] 			= 'Creating GUI from %s.' % (self.skinXML,)
			self.initVariables()
			if (not self.fastMethod):	
				if (dlg): self.dlg = dlg
				else: 
					self.dlg = xbmcgui.DialogProgress()
					self.dlg.create(title)
				self.dlg.update(self.pct, self.lines[0], self.lines[1], self.lines[2])
				self.pct1 = int((100 - pct) * 0.333)
				self.includesExist = self.LoadIncludes()
				self.referencesExist = self.LoadReferences()
			else:
				self.includesExist = False
			self.pct1 = int((100 - self.pct) * 0.5)
			self.parseSkinFile(imagePath, skinXML)
			if (self.win.SUCCEEDED): self.setNav()
			if (not self.win.SUCCEEDED): raise
			else:
				if (self.defaultControl and self.win.controls.has_key(self.defaultControl)):
					self.win.setFocus(self.win.controls[self.defaultControl])
				if (self.includesExist): self.incdoc.unlink()
			if (not self.fastMethod): self.dlg.close()
		except:
			self.win.SUCCEEDED = False
			if (not self.fastMethod):
				if (dlg): dlg.close()
				dlg = xbmcgui.Dialog()
				dlg.ok(title, 'There was an error setting up controls.', 'Check your skin file:', skinXML)
				self.dlg.close()


	 

Example 25

From project xbmc-israel, under directory plugin.video.gozlan.me/t0mm0/common, in source file addon.py.

Score: 8
vote
vote
def show_countdown(self, time_to_wait, title='', text=''):
        '''
        Show a countdown dialog with a progress bar for XBMC while delaying 
        execution. Necessary for some filehosters eg. megaupload
        
        The original version of this code came from Anarchintosh.
        
        Args:
            time_to_wait (int): number of seconds to pause for.
            
        Kwargs:
            title (str): Displayed in the title of the countdown dialog. Default
            is blank.
                         
            text (str): A line of text to be displayed in the dialog. Default
            is blank.
            
        Returns: 
            ``True`` if countdown is allowed to complete, ``False`` if the 
            user cancelled the countdown.
        '''
        
        dialog = xbmcgui.DialogProgress()
        ret = dialog.create(title)

        self.log_notice('waiting %d secs' % time_to_wait)
        
        secs = 0
        increment = 100 / time_to_wait

        cancelled = False
        while secs <= time_to_wait:

            if (dialog.iscanceled()):
                cancelled = True
                break

            if secs != 0: 
                xbmc.sleep(1000)

            secs_left = time_to_wait - secs
            if secs_left == 0: 
                percent = 100
            else: 
                percent = increment * secs
            
            remaining_display = ('Wait %d seconds for the ' +
                    'video stream to activate...') % secs_left
            dialog.update(percent, text, remaining_display)

            secs += 1

        if cancelled == True:     
            self.log_notice('countdown cancelled')
            return False
        else:
            self.log_debug('countdown finished waiting')
            return True        


     

Example 26

From project tvs, under directory plugin.video.tvs/resources/lib, in source file dvbtuner.py.

Score: 5
vote
vote
def _dvb_tuning(country,adapter,adaptername,outfile,freqmax=999999):
    f = None
    proc = None
    res = False
    startcheck = False
    isscanning = False
    progressDlg = None
    services = 0
    progressvalue = 0
    freqcounter = 0
    freqtuned = 0
    title_scan_msg = xbmcutil.translate('wait_for_scan')
    wait_scan_msg = xbmcutil.translate('warning_scan_running')
    scan_found_msg = xbmcutil.translate('scan_services_found')
    plugin.log.debug('dvb_tuning() - initialized adapter:%d' % adapter)
    try:
        try:            
            if adapter >= 0:
                plugin.log.debug('dvb_tuning() - start progress')
                progressDlg = xbmcgui.DialogProgress()
                plugin.log.debug('dvb_tuning() - progress started')
                progressDlg.create(xbmcutil.translate('tuning_title'),
                                   title_scan_msg % (adaptername),
                                   wait_scan_msg % (''))
                plugin.log.debug('dvb_tuning() - progress created adapter=%d country=%s' % (adapter,country))
                command = (SCAN_COMMAND % (adapter,country))
                f = open(outfile,'w+')
                plugin.log.debug('dvb_tuning() - outfile opened=%s' % outfile)
                plugin.log.debug('dvb_tuning() - ready to launch command=%s' % command)
                cmd = shlex.split(command)
                proc = subprocess.Popen(cmd, 
                                        shell=False,
                                        bufsize=0,
                                        stdin=None,
                                        stdout=f,
                                        stderr=subprocess.PIPE, 
                                        close_fds=True)
                plugin.log.debug('dvb_tuning() - start command: %s' % command)
                chname = ''
                te = ''
                _lastte = te
                while True and not progressDlg.iscanceled():
                    # non blocking read
                    r = select.select([proc.stderr.fileno()], [], [], 5)[0]
                    if r:
                        data = proc.stderr.readline()
                        if not data:
                            break  # EOF from process has been reached
                        else:
                            line = data.rstrip()
                            # log line from scan tool
                            plugin.log.debug(line)
                            if not check_error(line):
                                if not startcheck:
                                    currentadapter = get_dvb_frontend(line)
                                    startcheck = get_start_token(line)
                                    progressvalue = min(100,progressvalue + 1)
                                    progressDlg.update(progressvalue)
                                if startcheck:
                                    # master frequency scan
                                    (fr,te) = find_frequency(line)
                                    
                                    if fr <> '':
                                        isscanning = True
                                        freqcounter += 1
                                        # inc progressbar
                                        progressvalue = min(100,int(float(fr) / freqmax * 100))
                                        progressDlg.update(progressvalue)
                                    else:
                                        # total time elapsed check
                                        te = find_time_elapsed(line)
                                        # channels scan
                                        _chname = find_service(line)
                                        if _chname <> '':
                                            services += 1
                                            chname = ' - ' + _chname
                                        ft = find_frequency_tuned(line)
                                        if ft <> '':
                                            freqtuned += 1  
                                        
                                    if te <> '':
                                        _lastte = te
                                    if freqtuned > 0:
                                        # inc progressbar
                                        progressvalue = min(100,int(float(freqtuned) / freqcounter * 100))
                                        progressDlg.update(progressvalue) 
                                        title_scan_msg = xbmcutil.translate('warning_scan_running_2') 
                                        scan_found_msg = xbmcutil.translate('scan_channel_found')
                                        msg_counter = services
                                    else:
                                        msg_counter = freqcounter
                                                                                                                        
                                    if isscanning:
                                        progressDlg.update(progressvalue, 
                                                           title_scan_msg % (adaptername), 
                                                           wait_scan_msg % (_lastte), 
                                                           (scan_found_msg % (msg_counter)) + chname)
                            else:
                                # an error was encountered while executing w_scan
                                plugin.log.error(command)
                                plugin.log.error(line)
                                progressDlg.close()
                                if check_pid(proc.pid): os.kill(proc.pid, signal.SIGKILL)
                    
                if progressDlg.iscanceled():
                    plugin.log.debug('progress canceled')
                    if check_pid(proc.pid): os.kill(proc.pid, signal.SIGKILL)
            
            if services > 0:
                res = True
        except:
            res = False
            plugin.log.error('>>>>> _dvb_tuning() error:')
            plugin.log.error(str(sys.exc_info()[0]))
            plugin.log.error(str(sys.exc_info()[1]))

    finally:
        plugin.log.debug('dvb tuning end !')        
        if f <> None:
            f.close()
        if proc <> None:
            if check_pid(proc.pid): proc.terminate()
            if progressDlg <> None:
                progressDlg.close()
            del(progressDlg)
            
    return res

 

Example 27

From project plugin.video.pelisalacarta-master, under directory servers, in source file servertools.py.

Score: 5
vote
vote
def resolve_video_urls_for_playing(server,url,video_password="",muestra_dialogo=False):
    logger.info("[servertools.py] resolve_video_urls_for_playing, server="+server+", url="+url)
    video_urls = []
    torrent = False
    
    server = server.lower()

    # Si el vídeo es "directo", no hay que buscar más
    if server=="directo" or server=="local":
        logger.info("[servertools.py] server=directo, la url es la buena")
        
        try:
            import urlparse
            parsed_url = urlparse.urlparse(url)
            logger.info("parsed_url="+str(parsed_url))
            extension = parsed_url.path[-4:]
        except:
            extension = url[-4:]

        video_urls = [[ "%s [%s]" % (extension,server) , url ]]
        return video_urls,True,""

    # Averigua las URL de los vídeos
    else:
        
        #if server=="torrent":
        #    server="filenium"
        #    torrent = True

        # Carga el conector
        try:
            # Muestra un diálogo de progreso
            if muestra_dialogo:
                import xbmcgui
                progreso = xbmcgui.DialogProgress()
                progreso.create( "pelisalacarta" , "Conectando con "+server)

            # Sustituye el código por otro "Plex compatible"
            #exec "from servers import "+server+" as server_connector"
            servers_module = __import__("servers."+server)
            server_connector = getattr(servers_module,server)

            logger.info("[servertools.py] servidor de "+server+" importado")
            if muestra_dialogo:
                progreso.update( 20 , "Conectando con "+server)

            # Si tiene una función para ver si el vídeo existe, lo comprueba ahora
            if hasattr(server_connector, 'test_video_exists'):
                logger.info("[servertools.py] invocando a "+server+".test_video_exists")
                puedes,motivo = server_connector.test_video_exists( page_url=url )

                # Si la funcion dice que no existe, fin
                if not puedes:
                    logger.info("[servertools.py] test_video_exists dice que el video no existe")
                    if muestra_dialogo: progreso.close()
                    return video_urls,puedes,motivo
                else:
                    logger.info("[servertools.py] test_video_exists dice que el video SI existe")

            # Obtiene enlaces free
            if server in FREE_SERVERS:
                logger.info("[servertools.py] invocando a "+server+".get_video_url")
                video_urls = server_connector.get_video_url( page_url=url , video_password=video_password )
                
                # Si no se encuentran vídeos en modo free, es porque el vídeo no existe
                if len(video_urls)==0:
                    if muestra_dialogo: progreso.close()
                    return video_urls,False,"No se puede encontrar el vídeo en "+server

            # Obtiene enlaces premium si tienes cuenta en el server
            if server in PREMIUM_SERVERS and config.get_setting(server+"premium")=="true":
                video_urls = server_connector.get_video_url( page_url=url , premium=(config.get_setting(server+"premium")=="true") , user=config.get_setting(server+"user") , password=config.get_setting(server+"password"), video_password=video_password )
                
                # Si no se encuentran vídeos en modo premium directo, es porque el vídeo no existe
                if len(video_urls)==0:
                    if muestra_dialogo: progreso.close()
                    return video_urls,False,"No se puede encontrar el vídeo en "+server
    
            # Obtiene enlaces filenium si tienes cuenta
            if server in FILENIUM_SERVERS and config.get_setting("fileniumpremium")=="true":
    
                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update( 40 , "Conectando con Filenium")
    
                from servers import filenium as gen_conector
                
                video_gen = gen_conector.get_video_url( page_url=url , premium=(config.get_setting("fileniumpremium")=="true") , user=config.get_setting("fileniumuser") , password=config.get_setting("fileniumpassword"), video_password=video_password )
                extension = gen_conector.get_file_extension(video_gen)
                logger.info("[xbmctools.py] filenium url="+video_gen)
                video_urls.append( [ extension+" ["+server+"][filenium]", video_gen ] )

            # Obtiene enlaces realdebrid si tienes cuenta
            if server in REALDEBRID_SERVERS and config.get_setting("realdebridpremium")=="true":
    
                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update( 60 , "Conectando con Real-Debrid")

                from servers import realdebrid as gen_conector
                video_gen = gen_conector.get_video_url( page_url=url , premium=(config.get_setting("realdebridpremium")=="true") , user=config.get_setting("realdebriduser") , password=config.get_setting("realdebridpassword"), video_password=video_password )
                logger.info("[xbmctools.py] realdebrid url="+video_gen)
                if not "REAL-DEBRID" in video_gen:
                    video_urls.append( [ "."+video_gen.rsplit('.',1)[1]+" [realdebrid]", video_gen ] )
                else:
                    if muestra_dialogo: progreso.close()
                    # Si RealDebrid da error pero tienes un enlace válido, no te dice nada
                    if len(video_urls)==0:
                        return video_urls,False,video_gen
                  
            # Obtiene enlaces alldebrid si tienes cuenta
            if server in ALLDEBRID_SERVERS and config.get_setting("alldebridpremium")=="true":
    
                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update( 80 , "Conectando con All-Debrid")

                from servers import alldebrid as gen_conector
                video_gen = gen_conector.get_video_url( page_url=url , premium=(config.get_setting("alldebridpremium")=="true") , user=config.get_setting("alldebriduser") , password=config.get_setting("alldebridpassword"), video_password=video_password )
                logger.info("[xbmctools.py] alldebrid url="+video_gen)
                if video_gen.startswith("http"):
                    video_urls.append( [ "."+video_gen.rsplit('.',1)[1]+" [alldebrid]", video_gen ] )
                else:
                    # Si Alldebrid da error pero tienes un enlace válido, no te dice nada
                    if len(video_urls)==0:
                        return [],False,video_gen.strip()

            
            if muestra_dialogo:
                progreso.update( 100 , "Proceso finalizado")

            # Cierra el diálogo de progreso
            if muestra_dialogo: progreso.close()

            # Llegas hasta aquí y no tienes ningún enlace para ver, así que no vas a poder ver el vídeo
            if len(video_urls)==0:
                # ¿Cual es el motivo?
                
                # 1) No existe -> Ya está controlado
                # 2) No tienes alguna de las cuentas premium compatibles

                # Lista de las cuentas que soportan este servidor
                listapremium = ""
                if server in ALLDEBRID_SERVERS: listapremium+="All-Debrid o "            
                if server in FILENIUM_SERVERS: listapremium+="Filenium o "
                if server in REALDEBRID_SERVERS: listapremium+="Real-Debrid o "
                if server in PREMIUM_SERVERS: listapremium+=server+" o "
                listapremium = listapremium[:-3]
    
                return video_urls,False,"Para ver un vídeo en "+server+" necesitas<br/>una cuenta en "+listapremium

        except:
            if muestra_dialogo: progreso.close()
            import traceback
            from pprint import pprint
            exc_type, exc_value, exc_tb = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_tb)
            for line in lines:
                line_splits = line.split("\n")
                for line_split in line_splits:
                    logger.error(line_split)

            return video_urls,False,"Se ha producido un error en<br/>el conector con "+server

    return video_urls,True,""
    
 

Example 28

From project plugin.video.pelisalacarta-master, under directory core, in source file downloadtools.py.

Score: 5
vote
vote
def downloadfile(url,nombrefichero,headers=[],silent=False,continuar=False):
    logger.info("[downloadtools.py] downloadfile: url="+url)
    logger.info("[downloadtools.py] downloadfile: nombrefichero="+nombrefichero)

    try:
        # Si no es XBMC, siempre a "Silent"
        try:
            import xbmcgui
        except:
            silent=True
        
        # antes
        #f=open(nombrefichero,"wb")
        try:
            import xbmc
            nombrefichero = xbmc.makeLegalFilename(nombrefichero)
        except:
            pass
        logger.info("[downloadtools.py] downloadfile: nombrefichero="+nombrefichero)
    
        # El fichero existe y se quiere continuar
        if os.path.exists(nombrefichero) and continuar:
            #try:
            #    import xbmcvfs
            #    f = xbmcvfs.File(nombrefichero)
            #    existSize = f.size(nombrefichero)
            #except:
            f = open(nombrefichero, 'r+b')
            existSize = os.path.getsize(nombrefichero)
            
            logger.info("[downloadtools.py] downloadfile: el fichero existe, size=%d" % existSize)
            grabado = existSize
            f.seek(existSize)

        # el fichero ya existe y no se quiere continuar, se aborta
        elif os.path.exists(nombrefichero) and not continuar:
            logger.info("[downloadtools.py] downloadfile: el fichero existe, no se descarga de nuevo")
            return

        # el fichero no existe
        else:
            existSize = 0
            logger.info("[downloadtools.py] downloadfile: el fichero no existe")
            
            #try:
            #    import xbmcvfs
            #    f = xbmcvfs.File(nombrefichero,"w")
            #except:
            f = open(nombrefichero, 'wb')
            grabado = 0
    
        # Crea el diálogo de progreso
        if not silent:
            progreso = xbmcgui.DialogProgress()
            progreso.create( "plugin" , "Descargando..." , url , nombrefichero )
            #progreso.create( "plugin" , "Descargando..." , os.path.basename(nombrefichero)+" desde "+urlparse.urlparse(url).hostname )
        else:
            progreso = ""
    
        # Login y password Filenium
        # http://abcd%40gmail.com:[email protected]/get/Oi8vd3d3/LmZpbGVz/ZXJ2ZS5j/b20vZmls/ZS9kTnBL/dm11/b0/?.zip
        if "filenium" in url:
            from servers import filenium
            url , authorization_header = filenium.extract_authorization_header(url)
            headers.append( [ "Authorization", authorization_header ] )
    
        if "|" in url:
            additional_headers = url.split("|")[1]
            if "&" in additional_headers:
                additional_headers = additional_headers.split("&")
            else:
                additional_headers = [ additional_headers ]
    
            for additional_header in additional_headers:
                logger.info("[downloadtools.py] additional_header: "+additional_header)
                name = re.findall( "(.*?)=.*?" , additional_header )[0]
                value = urllib.unquote_plus(re.findall( ".*?=(.*?)$" , additional_header )[0])
                headers.append( [ name,value ] )
    
            url = url.split("|")[0]
            logger.info("[downloadtools.py] downloadfile: url="+url)
    
        # Timeout del socket a 60 segundos
        socket.setdefaulttimeout(60)
    
        h=urllib2.HTTPHandler(debuglevel=0)
        request = urllib2.Request(url)
        for header in headers:
            logger.info("[downloadtools.py] Header="+header[0]+": "+header[1])
            request.add_header(header[0],header[1])
    
        if existSize > 0:
            request.add_header('Range', 'bytes=%d-' % (existSize, ))
    
        opener = urllib2.build_opener(h)
        urllib2.install_opener(opener)
        try:
            connexion = opener.open(request)
        except urllib2.HTTPError,e:
            logger.info("[downloadtools.py] downloadfile: error %d (%s) al abrir la url %s" % (e.code,e.msg,url))
            #print e.code
            #print e.msg
            #print e.hdrs
            #print e.fp
            f.close()
            if not silent:
                progreso.close()
            # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo
            if e.code==416:
                return 0
            else:
                return -2
    
        try:
            totalfichero = int(connexion.headers["Content-Length"])
        except:
            totalfichero = 1
                
        if existSize > 0:
            totalfichero = totalfichero + existSize
    
        logger.info("Content-Length=%s" % totalfichero)
    
        blocksize = 100*1024
    
        bloqueleido = connexion.read(blocksize)
        logger.info("Iniciando descarga del fichero, bloqueleido=%s" % len(bloqueleido))
    
        maxreintentos = 10
        
        while len(bloqueleido)>0:
            try:
                # Escribe el bloque leido
                #try:
                #    import xbmcvfs
                #    f.write( bloqueleido )
                #except:
                f.write(bloqueleido)
                grabado = grabado + len(bloqueleido)
                percent = int(float(grabado)*100/float(totalfichero))
                totalmb = float(float(totalfichero)/(1024*1024))
                descargadosmb = float(float(grabado)/(1024*1024))
    
                # Lee el siguiente bloque, reintentando para no parar todo al primer timeout
                reintentos = 0
                while reintentos <= maxreintentos:
                    try:
                        before = time.time()
                        bloqueleido = connexion.read(blocksize)
                        after = time.time()
                        if (after - before) > 0:
                            velocidad=len(bloqueleido)/((after - before))
                            falta=totalfichero-grabado
                            if velocidad>0:
                                tiempofalta=falta/velocidad
                            else:
                                tiempofalta=0
                            #logger.info(sec_to_hms(tiempofalta))
                            if not silent:
                                #progreso.update( percent , "Descargando %.2fMB de %.2fMB (%d%%)" % ( descargadosmb , totalmb , percent),"Falta %s - Velocidad %.2f Kb/s" % ( sec_to_hms(tiempofalta) , velocidad/1024 ), os.path.basename(nombrefichero) )
                                progreso.update( percent , "%.2fMB/%.2fMB (%d%%) %.2f Kb/s %s falta " % ( descargadosmb , totalmb , percent , velocidad/1024 , sec_to_hms(tiempofalta)))
                        break
                    except:
                        reintentos = reintentos + 1
                        logger.info("ERROR en la descarga del bloque, reintento %d" % reintentos)
                        import traceback
                        logger.error( traceback.print_exc() )
                
                # El usuario cancelo la descarga
                try:
                    if progreso.iscanceled():
                        logger.info("Descarga del fichero cancelada")
                        f.close()
                        progreso.close()
                        return -1
                except:
                    pass
    
                # Ha habido un error en la descarga
                if reintentos > maxreintentos:
                    logger.info("ERROR en la descarga del fichero")
                    f.close()
                    if not silent:
                        progreso.close()
    
                    return -2
    
            except:
                import traceback
                logger.error( traceback.print_exc() )

                f.close()
                if not silent:
                    progreso.close()
                
                #advertencia = xbmcgui.Dialog()
                #resultado = advertencia.ok('Error al descargar' , 'Se ha producido un error' , 'al descargar el archivo')
                
                return -2

    except:
        if url.startswith("rtmp") and not silent:
            import xbmcgui
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok( "No puedes descargar ese vídeo","Las descargas en RTMP aún no","están soportadas")
        else:
            import traceback,sys
            from pprint import pprint
            exc_type, exc_value, exc_tb = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_tb)
            for line in lines:
                line_splits = line.split("\n")
                for line_split in line_splits:
                    logger.error(line_split)

    try:
        f.close()
    except:
        pass

    if not silent:
        try:
            progreso.close()
        except:
            pass

    logger.info("Fin descarga del fichero")

 

Example 29

From project plugin.video.pelisalacarta-master, under directory platformcode/xbmc, in source file launcher.py.

Score: 5
vote
vote
def run():
    logger.info("[launcher.py] run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters()
    logger.info("[launcher.py] fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s" % (fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif ( action=="update" ):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info("[launcher.py] Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

        elif (action=="channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params,url,category)

        elif (action=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path(), PLUGIN_NAME , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("[launcher.py] regular_channel_path=%s" % regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" % core_channel_path)

            if channel_name=="buscador":
                import pelisalacarta.buscador as channel
            if channel_name=="personal" or channel_name=="personal2" or channel_name=="personal3" or channel_name=="personal4" or channel_name=="personal5":
                import pelisalacarta.channels.personal as channel
            elif os.path.exists( regular_channel_path ):
                exec "import pelisalacarta.channels."+channel_name+" as channel"
            elif os.path.exists( regular_channel_path ):
                exec "import tvalacarta.channels."+channel_name+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+channel_name+" as channel"

            logger.info("[launcher.py] running channel %s %s" % (channel.__name__ , channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos 
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("[launcher.py] xbmc native channel")
                if (action=="strm"):
                    from platformcode.xbmc import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, viewmode=viewmode, show=show, password=password, fanart=fanart)
                
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("[launcher.py] No subtitle")
                '''
                from platformcode.xbmc import xbmctools

                if action=="play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("[launcher.py] executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                    else:
                        logger.info("[launcher.py] no channel 'play' method, executing core method")
                        xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("[launcher.py] play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")                    

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode.xbmc import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("[launcher.py] add_pelicula_to_library")
                    from platformcode.xbmc import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("[launcher.py] add_serie_to_library, show=#"+item.show+"#")
                    from platformcode.xbmc import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    
                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel."+action+"(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        logger.info("[launcher.py] add_serie_to_library, title="+item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("[launcher.py]Error al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    from platformcode.xbmc import library
                    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action=="download_all_episodes":
                    download_all_episodes(item,channel)

                elif action=="search":
                    logger.info("[launcher.py] search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("[launcher.py] executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                            
                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info("[launcher.py] no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from core import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback,sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %(e.reason[0],e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)    

# Parse XBMC params - based on script.module.parsedom addon    
 

Example 30

From project plugin.video.torrenter-master, under directory , in source file Core.py.

Score: 5
vote
vote
def drawcontentList(self, contentList, params={}):
        from resources.scrapers.scrapers import Scrapers
        contentList = sorted(contentList, key=lambda x: x[0], reverse=True)
        self.Scraper = Scrapers()
        progressBar = xbmcgui.DialogProgress()
        progressBar.create(self.localize('Please Wait'), self.localize('Waiting for website response...'))
        i = 0
        debug = 0
        ListString = 'XBMC.RunPlugin(%s)' % (sys.argv[0] + '?action=List&action2=%s&%s=%s')
        meta = None
        scrapers = {'tvdb': 'TheTVDB.com', 'tmdb': 'TheMovieDB.org', 'kinopoisk': 'KinoPoisk.ru'}
        for num, originaltitle, title, year, img, info in contentList:
            i = i + 1
            time.sleep(0.005)
            ListInfo = {u'title': title, u'original_title': originaltitle, u'year': year, u'img': img, u'info': info}
            iterator = int((float(i) / len(contentList)) * 100)
            dialogText = self.localize('Search and cache information for:')
            label = title
            title = contenter_title = title.encode('utf-8', 'ignore')
            search_url = {}
            if title:               search_url['title'] = title
            if img:                 search_url['img'] = img
            if originaltitle:       search_url['originaltitle'] = originaltitle
            if year:                search_url['year'] = str(year)
            if info.get('episode'): search_url['episode'] = str(info.get('episode'))
            if info.get('season'):  search_url['season'] = str(info.get('season'))

            if self.__settings__.getSetting("metadata") == 'true':

                if originaltitle:
                    search = [originaltitle, label]
                else:
                    search = [label]

                if info.get('tvshowtitle'):
                    scraper = 'tvdb'
                else:
                    scraper = 'tmdb'

                progressBar.update(iterator, dialogText, title, scrapers[scraper])
                meta = self.Scraper.scraper(scraper, {'label': title, 'search': search, 'year': year}, self.language)
                #print 'meta:'+str(meta)
                if self.language == 'ru':
                    if not meta.get('info').get('title') or \
                            not meta.get('properties').get('fanart_image') or not meta.get('icon'):
                        scraper = 'kinopoisk'
                        progressBar.update(iterator, dialogText, title, scrapers[scraper])
                        if info.get('tvshowtitle'):
                            if originaltitle:
                                search = [originaltitle, label + u' (??????)']
                            else:
                                search = [label + u' (??????)']
                        kinometa = self.Scraper.scraper(scraper, {'label': title, 'search': search,
                                                                  'year': year}, self.language)

                        #print 'kinometa:'+str(kinometa)

                        for section in kinometa.keys():
                            if isinstance(kinometa[section], dict):
                                if not meta.get(section):
                                    meta[section] = kinometa[section]
                                    continue
                                else:
                                    for sitem in kinometa[section].keys():
                                        meta[section][sitem] = kinometa[section][sitem]
                            elif not meta.get(section):
                                meta[section] = kinometa[section]

                #print 'meta:'+str(meta)
                #if self.debug and meta.get('info').get('title') and meta.get('info').get('title').encode('utf-8')==title: continue

                #print 'meta: '+str((scraper, {'label': title, 'search': [label, originaltitle],
                #                                 'year': year}))
                debug = 0
                if meta.get('info').get('title'):
                    if self.debug and 1 == debug:
                        title = meta.get('info').get('title').encode('utf-8') + '/' + title + '/'
                        if originaltitle: title += originaltitle.encode('utf-8')
                    else:
                        title = meta.get('info').get('title')

            listitem = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img)
            listitem.setInfo(type='Video', infoLabels=info)
            if meta:
                listitem=itemScrap(listitem, meta)
                if meta.get('icon'):
                    search_url['img'] = meta.get('icon')
                if meta.get('info').get('title'):
                    search_url['title'] = meta.get('info').get('title').encode('utf-8')
                    if search_url['title'] != contenter_title:
                        search_url['contenter_title'] = contenter_title
                if meta.get('info').get('originaltitle'):
                    search_url['originaltitle'] = meta.get('info').get('originaltitle').encode('utf-8')

            contextMenu = [(self.localize('Search Control Window'),
                            'xbmc.RunScript(%s,)' % os.path.join(ROOT, 'controlcenter.py'))]
            if params.get('action') == 'List':
                contextMenu.append((self.localize('Delete from %s') % self.localize('Personal List'),
                                    ListString % ('delete', 'addtime', str(num * -1))))
            else:
                contextMenu.append((self.localize('Add to %s') % self.localize('Personal List'),
                                    ListString % ('add', 'info', urllib.quote_plus(json.dumps(ListInfo)))), )

            contextMenu.append((self.localize('Information'), 'xbmc.Action(Info)'))

            listitem.addContextMenuItems(contextMenu, replaceItems=False)
            url = '%s?action=%s&url=%s' % (sys.argv[0], 'searchOption', urllib.quote_plus(json.dumps(search_url)))
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

            if progressBar.iscanceled():
                self.breakdown = True
                showMessage('< %s >' % self.localize('Content Lists'), self.localize('Canceled by User'))
                break
                #break

        progressBar.update(0)
        progressBar.close()
        if self.debug and 1 == debug: lockView('wide')

     

Example 31

From project xbmc-addon-service-watchedlist-master, under directory , in source file service.py.

Score: 5
vote
vote
def write_wl_wdata(self):
        """Go through all watched movies from xbmc and check whether they are up to date in the addon database

        Returns:
            return code:
            0    successfully written WL
            1    program exception
            2    database loading error
        """
        
        buggalo.addExtraData('self_sqlcursor', self.sqlcursor); buggalo.addExtraData('self_sqlcon', self.sqlcon);
        if self.sqlcursor == 0 or self.sqlcon == 0:
            if self.load_db():
                return 2
        for modus in ['movie', 'episode']:
            buggalo.addExtraData('modus', modus);
            if modus == 'movie' and utils.getSetting("w_movies") != 'true':
                continue
            if modus == 'episode' and utils.getSetting("w_episodes") != 'true':
                continue
            utils.log(u'write_wl_wdata: Write watched %ss to WL database' % modus, xbmc.LOGDEBUG)
            count_insert = 0
            count_update = 0
            if utils.getSetting("progressdialog") == 'true':
                DIALOG_PROGRESS = xbmcgui.DialogProgress()
                DIALOG_PROGRESS.create( utils.getString(32101) , utils.getString(32105))
            if modus == 'movie':
                list_length = len(self.watchedmovielist_xbmc)
            else:
                list_length = len(self.watchedepisodelist_xbmc)
                
            for i in range(list_length):
                if xbmc.abortRequested: break # this loop can take some time in debug mode and prevents xbmc exit
                if utils.getSetting("progressdialog") == 'true' and DIALOG_PROGRESS.iscanceled():
                    if modus == 'movie': strno = 32202
                    else: strno = 32203;
                    utils.showNotification(utils.getString(strno), utils.getString(32301)%(count_insert, count_update))
                    return 2
                if modus == 'movie':
                    row_xbmc = self.watchedmovielist_xbmc[i]
                else:
                    row_xbmc = self.watchedepisodelist_xbmc[i]

                if utils.getSetting("progressdialog") == 'true':
                    DIALOG_PROGRESS.update(100*(i+1)/list_length, utils.getString(32105), utils.getString(32610) % (i+1, list_length, row_xbmc[5]) )  

                try:
                    count = self.wl_update_media(modus, row_xbmc, 0, 0)
                    count_insert += count[0]; count_update += count[1];

                except sqlite3.Error as e:
                    try:
                        errstring = e.args[0] # TODO: Find out, why this does not work some times
                    except:
                        errstring = ''
                    utils.log(u'write_wl_wdata: SQLite Database error ''%s'' while updating %s %s' % (errstring, modus, row_xbmc[5]), xbmc.LOGERROR)
                    # error at this place is the result of duplicate movies, which produces a DUPLICATE PRIMARY KEY ERROR
                    return 1
                except mysql.connector.Error as err:
                    utils.log(u'write_wl_wdata: MySQL Database error ''%s'' while updating %s %s' % (err, modus, row_xbmc[5]), xbmc.LOGERROR)
                    self.close_db()
                    return 1 # error while writing. Do not continue with episodes, if movies raised an exception
                except:
                    utils.log(u'write_wl_wdata: Error while updating %s %s: %s' % (modus, row_xbmc[5], sys.exc_info()[2]), xbmc.LOGERROR)
                    self.close_db()
                    if utils.getSetting("progressdialog") == 'true': DIALOG_PROGRESS.close()
                    buggalo.addExtraData('count_update', count_update); buggalo.addExtraData('count_insert', count_insert); 
                    buggalo.onExceptionRaised()  
                    return 1 
                    
            if utils.getSetting("progressdialog") == 'true': DIALOG_PROGRESS.close()
            # only commit the changes if no error occured to ensure database persistence
            if count_insert > 0 or count_update > 0:
                self.database_copy()
                self.sqlcon.commit()
            if modus == 'movie': strno = [32202, 32301]
            else: strno = [32203, 32301];
            utils.showNotification(utils.getString(strno[0]), utils.getString(strno[1])%(count_insert, count_update))
        self.close_db()
        return 0