Ejemplo n.º 1
0
  def play(self, page, mode=''):
    if Debug: self.LOG('DEBUG: _play()\nurl: %s' % page)
    # Get current list item details...
    title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
    thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")

    if mode == 'smil':
      smil = BSS(self._get(page))
      rtmp = smil.meta['base']
      video = smil.video['src']
      swfUrl = 'http://medici.tv/medici.swf'
      # rtmpdump script for console use 
      rtmpdump = "rtmpdump -r %s --swfUrl http://medici.tv/medici.swf --tcUrl '%s' --playpath '%s' -o '%s.mp4'" % \
                  (rtmp, rtmp, saxutils.unescape(video), saxutils.unescape(title))
      # Build rtmp url...
      video_url = rtmp + ' swfUrl=' + swfUrl + ' tcUrl=' + rtmp + ' playpath=' + saxutils.unescape(video)
      if Debug: self.LOG('DEBUG: rtmp link details.\n\trtmp: %s\n\tswfUrl: %s\n\ttcUrl: %s\n\tplaypath: %s\n\trtmpdump: %s' % \
                         (rtmp, swfUrl, rtmp, saxutils.unescape(video), rtmpdump))
    elif mode == 'rtmp_daily':
      video_url = page.split('&rtmp=1')[0]
      if Debug: self.LOG('DEBUG: video link details.\n\turl: %s' % video_url)
    else:
      video_url = ''
      if Debug: self.LOG('DEBUG: no video link!')
      raise
    # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2
    listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
    # set listitem information
    listitem.setInfo('video', {'title': title,
                               'label' : title,
                               'plot': plot,
                               'plotoutline': plot, })
    # Play video...
    xbmc.Player().play(video_url , listitem)
def play(params,url,category):
	xbmc.output("[skai_folders.py] play")

	title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "UTF-8" )
	thumbnail = urllib.unquote_plus( params.get("thumbnail") )
	plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "UTF-8" )
	server = "Directo"
	
    # --------------------------------------------------------
	# DDownload page
	# --------------------------------------------------------
	
	data = scrapertools.cachePage(url)
	pattern = 'rtmp://cp67754.edgefcs.net/ondemand/mp4:content/Fakeloi/20.*?mp4'
	matches = re.compile(pattern,re.DOTALL).findall(data)
	
	xbmc.output("[skai_folders.py] matches are")
		
	
	if len(matches)==0:
		xbmctools.alerterrorpagina()
		return

	url = matches[0]
	xbmc.output("url="+url)
	
	
	plot= HTMLParser.HTMLParser().unescape(plot)+"_UNESCAPED_"

	xbmctools.playvideo(CHANNELCODE,server,url,category,title,thumbnail,plot)
    def set_content_header(self, content_type):
        '''sets a window propery which can be used as headertitle'''
        self.win.clearProperty("SkinHelper.ContentHeader")
        itemscount = xbmc.getInfoLabel("Container.NumItems")
        if itemscount:
            if xbmc.getInfoLabel("Container.ListItemNoWrap(0).Label").startswith(
                    "*") or xbmc.getInfoLabel("Container.ListItemNoWrap(1).Label").startswith("*"):
                itemscount = int(itemscount) - 1

            headerprefix = ""
            if content_type == "movies":
                headerprefix = xbmc.getLocalizedString(36901)
            elif content_type == "tvshows":
                headerprefix = xbmc.getLocalizedString(36903)
            elif content_type == "seasons":
                headerprefix = xbmc.getLocalizedString(36905)
            elif content_type == "episodes":
                headerprefix = xbmc.getLocalizedString(36907)
            elif content_type == "sets":
                headerprefix = xbmc.getLocalizedString(36911)
            elif content_type == "albums":
                headerprefix = xbmc.getLocalizedString(36919)
            elif content_type == "songs":
                headerprefix = xbmc.getLocalizedString(36921)
            elif content_type == "artists":
                headerprefix = xbmc.getLocalizedString(36917)

            if headerprefix:
                self.win.setProperty("SkinHelper.ContentHeader", "%s %s" % (itemscount, headerprefix))
Ejemplo n.º 4
0
def main():
    path = xbmc.getInfoLabel('ListItem.Path')    
    db_type = xbmc.getInfoLabel('ListItem.DBTYPE')
    if db_type == "tvshow":
        path = urllib.quote_plus(path)
        url = "plugin://{0}/tv/set_library_player/{1}".format(pluginid, path)
        xbmc.executebuiltin("RunPlugin({0})".format(url))
Ejemplo n.º 5
0
    def myPlayerChanged( self, event, force_update=False ):
        LOG( LOG_DEBUG, "%s (rev: %s) GUI::myPlayerChanged [%s]", __scriptname__, __svn_revision__, [ "stopped","ended","started" ][ event ] )
        if ( event < 2 ): 
            self.exit_script()
        else:
            for cnt in range( 5 ):
                song = xbmc.getInfoLabel( "MusicPlayer.Title" )
                #print "Song" + song

                artist = xbmc.getInfoLabel( "MusicPlayer.Artist" )
                #print "Artist" + artist                
                if ( song and ( not artist or self.settings[ "use_filename" ] ) ):
                    artist, song = self.get_artist_from_filename( xbmc.Player().getPlayingFile() )
                if ( song and ( self.song != song or self.artist != artist or force_update ) ):
                    self.artist = artist
                    self.song = song
                    self.lock.acquire()
                    try:
                        self.timer.cancel()
                    except:
                        pass
                    self.lock.release()
                    self.get_lyrics( artist, song )
                    break
                xbmc.sleep( 50 )
            if (self.allowtimer and self.settings[ "smooth_scrolling" ] and self.getControl( 110 ).size() > 1):
                self.lock.acquire()
                try:
                    self.timer.cancel()
                except:
                    pass
                self.lock.release()
                self.refresh()
Ejemplo n.º 6
0
 def view(self, content):
     try:
         skin = xbmc.getSkinDir()
         skinPath = xbmc.translatePath('special://skin/')
         xml = os.path.join(skinPath,'addon.xml')
         file = xbmcvfs.File(xml)
         read = file.read().replace('\n','')
         file.close()
         try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0]
         except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0]
         src = os.path.join(skinPath, src)
         src = os.path.join(src, 'MyVideoNav.xml')
         file = xbmcvfs.File(src)
         read = file.read().replace('\n','')
         file.close()
         views = re.compile('<views>(.+?)</views>').findall(read)[0]
         views = [int(x) for x in views.split(',')]
         for view in views:
             label = xbmc.getInfoLabel('Control.GetLabel(%s)' % (view))
             if not (label == '' or label == None): break
         record = (skin, content, str(view))
         dbcon = database.connect(addonSettings)
         dbcur = dbcon.cursor()
         dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");")
         dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1]))
         dbcur.execute("INSERT INTO views Values (?, ?, ?)", record)
         dbcon.commit()
         viewName = xbmc.getInfoLabel('Container.Viewmode')
         index().infoDialog('%s%s%s' % (language(30301).encode("utf-8"), viewName, language(30302).encode("utf-8")))
     except:
         return
 def get_folderandprefix(self):
     '''get the current folder and prefix'''
     cur_folder = ""
     cont_prefix = ""
     try:
         widget_container = self.win.getProperty("SkinHelper.WidgetContainer").decode('utf-8')
         if xbmc.getCondVisibility("Window.IsActive(movieinformation)"):
             cont_prefix = ""
             cur_folder = xbmc.getInfoLabel(
                 "movieinfo-$INFO[Container.FolderPath]"
                 "$INFO[Container.NumItems]"
                 "$INFO[Container.Content]").decode('utf-8')
         elif widget_container:
             cont_prefix = "Container(%s)." % widget_container
             cur_folder = xbmc.getInfoLabel(
                 "widget-%s-$INFO[Container(%s).NumItems]-$INFO[Container(%s).ListItemAbsolute(1).Label]" %
                 (widget_container, widget_container, widget_container)).decode('utf-8')
         else:
             cont_prefix = ""
             cur_folder = xbmc.getInfoLabel(
                 "$INFO[Container.FolderPath]$INFO[Container.NumItems]$INFO[Container.Content]").decode(
                 'utf-8')
     except Exception as exc:
         log_exception(__name__, exc)
         cur_folder = ""
         cont_prefix = ""
     return (cur_folder, cont_prefix)
Ejemplo n.º 8
0
def get_setting_videostream():  

    stream = 'h264 1500'

    stream_prefs = '0'
    try:
        stream_prefs = addoncompat.get_setting('video_stream')
    except:
        pass
        
    # Auto|H.264 (480kb)|H.264 (800kb)|H.264 (1500kb)|H.264 (3200kb)
    if stream_prefs == '0':
        environment = os.environ.get( "OS" )
        # check for xbox as we set a lower default for xbox (although it can do 1500kbit streams)
        if environment == 'xbox':
            stream = 'h264 800'
        else:
            # play full HD if the screen is large enough (not all programmes have this resolution)
            Y = int(xbmc.getInfoLabel('System.ScreenHeight'))
            X = int(xbmc.getInfoLabel('System.ScreenWidth'))
            # if the screen is large enough for HD
            if Y > 832 and X > 468:
                stream = 'h264 3200'
    elif stream_prefs == '1':
        stream = 'h264 480'
    elif stream_prefs == '2':
        stream = 'h264 800'
    elif stream_prefs == '3':
        stream = 'h264 1500'
    elif stream_prefs == '4':
        stream = 'h264 3200'

    logging.info("Video stream prefs %s - %s", stream_prefs, stream)
    return stream
def detail(params, url, category):
    logger.info("[documentalesatonline.py] detail")

    title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
    thumbnail = urllib.unquote_plus(params.get("thumbnail"))
    plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")

    # Descarga la página
    data = scrapertools.cachePage(url)
    # logger.info(data)

    # ------------------------------------------------------------------------------------
    # Busca los enlaces a los videos
    # ------------------------------------------------------------------------------------
    listavideos = servertools.findvideos(data)

    for video in listavideos:
        xbmctools.addvideo(CHANNELNAME, "Megavideo - " + video[0], video[1], category, video[2])
        # ------------------------------------------------------------------------------------

        # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=pluginhandle, category=category)

    # Disable sorting...
    xbmcplugin.addSortMethod(handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # End of directory...
    xbmcplugin.endOfDirectory(handle=pluginhandle, succeeded=True)
Ejemplo n.º 10
0
 def view(self, content):
     try:
         skin = xbmc.getSkinDir()
         skinPath = xbmc.translatePath('special://skin/')
         xml = os.path.join(skinPath,'addon.xml')
         file = xbmcvfs.File(xml)
         read = file.read().replace('\n','')
         file.close()
         try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0]
         except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0]
         src = os.path.join(skinPath, src)
         if xbmcgui.getCurrentWindowId() == 10501: src = os.path.join(src, 'MyMusicSongs.xml')
         else: src = os.path.join(src, 'MyMusicNav.xml')
         file = xbmcvfs.File(src)
         read = file.read().replace('\n','')
         file.close()
         views = re.compile('<views>(.+?)</views>').findall(read)[0]
         views = [int(x) for x in views.split(',')]
         for view in views:
             label = xbmc.getInfoLabel('Control.GetLabel(%s)' % (view))
             if not (label == '' or label is None): break
         file = xbmcvfs.File(viewData)
         read = file.read()
         file.close()
         file = open(viewData, 'w')
         for line in re.compile('(".+?\n)').findall(read):
             if not line.startswith('"%s"|"%s"|"' % (skin, content)): file.write(line)
         file.write('"%s"|"%s"|"%s"\n' % (skin, content, str(view)))
         file.close()
         viewName = xbmc.getInfoLabel('Container.Viewmode')
         index().infoDialog('%s%s%s' % (language(30301).encode("utf-8"), viewName, language(30302).encode("utf-8")))
     except:
         return
Ejemplo n.º 11
0
 def __init__(self):
     self.log("__init__")
     # InfoLabel Parameters  
     self.Label       = xbmc.getInfoLabel('ListItem.Label')
     self.Path        = xbmc.getInfoLabel('ListItem.FolderPath')
     self.FileName    = xbmc.getInfoLabel('ListItem.FilenameAndPath')
     self.DBIDType    = xbmc.getInfoLabel('ListItem.DBTYPE')
     self.AddonName   = xbmc.getInfoLabel('Container.PluginName')
     self.AddonType   = xbmc.getInfoLabel('Container.Property(addoncategory)')
     self.Description = xbmc.getInfoLabel('ListItem.Property(Addon.Description)')
     self.plot        = xbmc.getInfoLabel('ListItem.Plot')
     self.plotOutline = xbmc.getInfoLabel('ListItem.PlotOutline')
     self.isPlayable  = xbmc.getInfoLabel('ListItem.Property(IsPlayable)').lower() == 'true'
     self.isFolder    = xbmc.getCondVisibility('ListItem.IsFolder') == 1
     
     if not self.plot:
         if self.plotOutline:
             self.Description = self.plotOutline
         elif not self.Description:   
             self.Description = self.Label
     else:  
         self.Description = self.plot
       
     if self.AddonName:
         ADDON = xbmcaddon.Addon(id=self.AddonName)
         ADDON_ID = ADDON.getAddonInfo('id')
         self.AddonName = ADDON.getAddonInfo('name')
         
     self.chnlst = ChannelList()
     self.Label = self.chnlst.cleanLabels(self.Label)
     self.Description  = self.chnlst.cleanLabels(self.Description)
     self.AddonName = self.chnlst.cleanLabels(self.AddonName)
     self.log("%s, %s, %s, %s, %s, %s, %s, %s, %s"%(self.Label,self.Path,self.FileName,self.DBIDType,self.AddonName,self.AddonType,self.Description,str(self.isPlayable),str(self.isFolder)))
     self.ImportChannel()
Ejemplo n.º 12
0
  def playing_type(self):
    type = 'unkown'
    if type == 'unkown':
		
		oncenb=0
	  
    if (self.isPlayingAudio()):
		type = "music"
		oncenb=1
	
    if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
        filename = ''
        isMovie = True
        try:
          filename = self.getPlayingFile()
        except:
          pass
        if filename != '':
          for string in self.substrings:
            if string in filename:
              isMovie = False
              break
        if isMovie:
          type = "movie"
    if xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
        # Check for tv show title and season to make sure it's really an episode
        if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
           type = "episode"
		
	#else:
		#type = 'unkown'
		
    return 'type=' + type 
Ejemplo n.º 13
0
  def onPlayBackStopped(self):
	log('player stops')
	type = 'unkown'
	if (self.isPlayingAudio()):
	  type = "music"
	else:
		if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
			filename = ''
			isMovie = True
		try:
			filename = self.getPlayingFile()
		except:
			pass
		if filename != '':
			for string in self.substrings:
				if string in filename:
					isMovie = False
					break
		if isMovie:
			type = "movie"
		elif xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
	  # Check for tv show title and season to make sure it's really an episode
			if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
				type = "episode"
	typevar=type
	
	if typevar!="music":
		global script_playerV_stops
		log('Going to execute script = "' + script_playerV_stops + '"')
		xbmc.executebuiltin('XBMC.RunScript('+script_playerV_stops+ ", " + self.playing_type()+')')
	if typevar=="music":
		global script_playerA_stops
		log('Going to execute script = "' + script_playerA_stops + '"')
		xbmc.executebuiltin('XBMC.RunScript('+script_playerA_stops+ ", " + self.playing_type()+')')
Ejemplo n.º 14
0
def JumpToLetter(letter):
    if not xbmc.getInfoLabel("ListItem.Sortletter")[0] == letter:
        xbmc.executebuiltin("SetFocus(50)")
        if letter in ["A", "B", "C", "2"]:
            jumpsms_id = "2"
        elif letter in ["D", "E", "F", "3"]:
            jumpsms_id = "3"
        elif letter in ["G", "H", "I", "4"]:
            jumpsms_id = "4"
        elif letter in ["J", "K", "L", "5"]:
            jumpsms_id = "5"
        elif letter in ["M", "N", "O", "6"]:
            jumpsms_id = "6"
        elif letter in ["P", "Q", "R", "S", "7"]:
            jumpsms_id = "7"
        elif letter in ["T", "U", "V", "8"]:
            jumpsms_id = "8"
        elif letter in ["W", "X", "Y", "Z", "9"]:
            jumpsms_id = "9"
        else:
            jumpsms_id = None
        if jumpsms_id:
            for i in range(1, 5):
                # xbmc.executebuiltin("jumpsms" + jumpsms_id)
                xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": { "action": "jumpsms%s" }, "id": 1 }' % (jumpsms_id))
                # prettyprint(response)
                xbmc.sleep(15)
                if xbmc.getInfoLabel("ListItem.Sortletter")[0] == letter:
                    break
        xbmc.executebuiltin("SetFocus(24000)")
Ejemplo n.º 15
0
def CreateDialogYesNo(header="", line1="", nolabel="", yeslabel="", noaction="", yesaction=""):
    if yeslabel == "":
        yeslabel = xbmc.getInfoLabel("Window.Property(Dialog.yes.Label)")
        if yeslabel == "":
            yeslabel = "yes"
    if nolabel == "":
        nolabel = xbmc.getInfoLabel("Window.Property(Dialog.no.Label)")
        if nolabel == "":
            nolabel = "no"
    if yesaction == "":
        yesaction = xbmc.getInfoLabel("Window.Property(Dialog.yes.Builtin)")
    if noaction == "":
        noaction = xbmc.getInfoLabel("Window.Property(Dialog.no.Builtin)")
    dialog = xbmcgui.Dialog()
    ret = dialog.yesno(heading=header, line1=line1, nolabel=nolabel, yeslabel=yeslabel)  # autoclose missing
    if ret:
        for builtin in yesaction.split("||"):
            xbmc.executebuiltin(builtin)
            xbmc.sleep(30)
    else:
        for builtin in noaction.split("||"):
            xbmc.executebuiltin(builtin)
            xbmc.sleep(30)
    xbmc.executebuiltin("ClearProperty(Dialog.yes.Label")
    xbmc.executebuiltin("ClearProperty(Dialog.no.Label")
    xbmc.executebuiltin("ClearProperty(Dialog.yes.Builtin")
    xbmc.executebuiltin("ClearProperty(Dialog.no.Builtin")
    return ret
Ejemplo n.º 16
0
def play(params,url,category):
	xbmc.output("[argia.py] play")
	
	# Page downloading
	data = scrapertools.cachePage(url)
	
	##
	## PARSE VIDEO DATA
	##
	'''
s1.addVariable('file','/multimedia/docs/bideoak/dantzaTradizioa.flv');
	'''
	#pattern = 'file=(.*?).flv'
	pattern = "s1\.addVariable\('file','([^']+)'\)"
	matches = re.compile(pattern,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)
	
	try:
		url = MAINURL+matches[0]
	except:
		url = ""
	
	title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
	thumbnail = urllib.unquote_plus( params.get("thumbnail") )
	plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
	server = "Directo"

	xbmctools.playvideo(CHANNELCODE,server,url,category,title,thumbnail,plot)
Ejemplo n.º 17
0
 def doFunction(self, url):
     func = url[0:2]
     url  = url[2:]
     if func == 'AL':
         name = xbmc.getInfoLabel('ListItem.Title')
         profile = self.addon.getAddonInfo('profile').decode(UTF8)
         moviesDir = xbmc.translatePath(os.path.join(profile,'TV Shows'))
         movieDir = xbmc.translatePath(os.path.join(moviesDir, name))
         if not os.path.isdir(movieDir):
             os.makedirs(movieDir)
         ilist = []
         ilist = self.getAddonEpisodes(url, ilist, getFileData = True)
         for season, episode, url in ilist:
             se = 'S%sE%s' % (str(season), str(episode))
             xurl = '%s?mode=GV&url=%s' % (sys.argv[0], qp(url))
             strmFile = xbmc.translatePath(os.path.join(movieDir, se+'.strm'))
             with open(strmFile, 'w') as outfile:
                 outfile.write(xurl)         
     elif func == 'AM':
         name  = xbmc.getInfoLabel('ListItem.Title')
         profile = self.addon.getAddonInfo('profile').decode(UTF8)
         moviesDir  = xbmc.translatePath(os.path.join(profile,'Movies'))
         movieDir  = xbmc.translatePath(os.path.join(moviesDir, name))
         if not os.path.isdir(movieDir):
             os.makedirs(movieDir)
         strmFile = xbmc.translatePath(os.path.join(movieDir, name+'.strm'))
         with open(strmFile, 'w') as outfile:
             outfile.write('%s?mode=GV&url=%s' %(sys.argv[0], url))
     json_cmd = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan", "params": {"directory":"%s/"},"id":1}' % movieDir.replace('\\','/')
     jsonRespond = xbmc.executeJSONRPC(json_cmd)
Ejemplo n.º 18
0
def getCast():
    value = xbmc.getInfoLabel('%sListItem.%s' % (getPrefix(), 'castandrole'))
    if value:
        return [tuple(cr.split(' as ', 1)) for cr in value.split('\n')]

    value = xbmc.getInfoLabel('Container(%d).ListItem.%s' % (id, 'cast'))
    if value:
        return [tuple([cr, '']) for cr in value.split('\n')]

    castItems = []

    type = xbmc.getInfoLabel('Container(%d).ListItem.DBTYPE' % id)
   
    if type == 'movie':
        castItems = getMovieCast()

    elif type == 'tvshow':
        castItems = getTVShowCast()

    elif type == 'episode':
        castItems = getEpisodeCast()

    elif type == 'season':
        castItems = getSeasonCast()

    cast = []
    for item in castItems:
        name  = item['name']
        role = item['role']
        cast.append((name, role))

    return cast
Ejemplo n.º 19
0
 def _init_vars( self ):
     self.WINDOW = xbmcgui.Window( int(self.WINDOWID) )
     self.WINDOW.clearProperty( "ArtistSlideshow.CleanupComplete" )
     if( self.ARTISTFIELD == '' ):
         self.SKINARTIST = ''
     else:
         self.SKINARTIST = "Window(%s).Property(%s)" % ( self.WINDOWID, self.ARTISTFIELD )
     if( self.TITLEFIELD == '' ):
         self.SKINTITLE = ''
     else:
         self.SKINTITLE = "Window(%s).Property(%s)" % ( self.WINDOWID, self.TITLEFIELD )
     self.ARTISTSLIDESHOW = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshow" )
     self.ARTISTSLIDESHOWRUNNING = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshowRunning" )
     self.EXTERNALCALL = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshow.ExternalCall" )
     self.EXTERNALCALLSTATUS = xbmc.getInfoLabel( self.EXTERNALCALL )
     log( 'external call is set to ' + xbmc.getInfoLabel( self.EXTERNALCALL ) )
     self.NAME = ''
     self.ALLARTISTS = []
     self.LocalImagesFound = False
     self.CachedImagesFound = False
     self.ImageDownloaded = False
     self.DownloadedAllImages = False
     self.UsingFallback = False
     self.BlankDir = xbmc.translatePath('special://profile/addon_data/%s/transition' % __addonname__ )
     self.MergeDir = xbmc.translatePath('special://profile/addon_data/%s/merge' % __addonname__ )    
     self.InitDir = xbmc.translatePath('%s/resources/black' % __addonpath__ )
     LastfmApiKey = 'fbd57a1baddb983d1848a939665310f6'
     HtbackdropsApiKey = '96d681ea0dcb07ad9d27a347e64b652a'
     self.LastfmURL = 'http://ws.audioscrobbler.com/2.0/?autocorrect=1&api_key=' + LastfmApiKey
     self.HtbackdropsQueryURL = 'http://htbackdrops.com/api/' + HtbackdropsApiKey + '/searchXML?default_operator=and&fields=title&aid=1'
     self.HtbackdropsDownloadURL = 'http://htbackdrops.com/api/' + HtbackdropsApiKey + '/download/'
Ejemplo n.º 20
0
def play_program(listitem, type = "program"):
	programid = listitem.GetProperty("id");
	nocharge = listitem.GetProperty('nocharge');
	dp = xbmcgui.DialogProgress()
	dialog = xbmcgui.Dialog()

	path = listitem.GetPath();
		
	username = xbmc.getInfoLabel('App.String(username)')
	password = xbmc.getInfoLabel('App.String(password)')
		
	try:
		if (nocharge != "1"):
			if(username == ""):
				raise Exception("Du er ikke logget ind!");				
			if not (login_user(username, password)):
				raise Exception("Kunne ikke logge dig ind!");
			if not (login_user(username, password)):
				raise Exception("Kunne ikke logge dig ind!");
		newpath = str('flash://sputnik.dk/src=' + urllib.quote_plus("http://sputnik-dyn.tv2.dk/player/simple/id/"+programid+"/type/"+type+"/") + '&bx-ourl=' + urllib.quote_plus(path) + '&bx-jsactions=' + urllib.quote_plus('http://dl.dropbox.com/u/93155/boxee/controls.js'))
		listitem.SetPath(newpath)
		mc.GetPlayer().PlayWithActionMenu(listitem)
		listitem.SetPath(path)
			
	except Exception, e:
		dialog.ok('Error', str(e))
		dp.close()
Ejemplo n.º 21
0
 def doFunction(self, url):
     func = url[0:2]
     url = url[2:]
     if func == 'DP':
         isrc, pid = url.split('pid',1)
         self.updateList(pid = pid, token = None, cmd = 'DELITEM', isrc = isrc)
     elif func == 'AP':
         token, uid = self.getAutho(getMe = True)
         html = self.getRequest(VEVOAPI + ('/user/%s/playlists?token=%s' % (uid,token)))
         a = json.loads(html)
         ilist=[]
         nlist=[]
         for b in a:
             nlist.append(b['name'])
             ilist.append(b['playlistId'])
         dialog = xbmcgui.Dialog()
         choice = dialog.select('Choose a playlist', nlist)
         pid = ilist[choice]
         self.updateList(pid = pid, token = token, cmd = 'ADDITEM', isrc = url)
     elif func == 'AL':
         artist = xbmc.getInfoLabel('ListItem.Artist').split('/',1)[0]
         artist = artist.replace(':','').replace('-','').replace('?','%3F')
         title = xbmc.getInfoLabel('ListItem.Title').split('(',1)[0]
         title = title.replace(':','').replace('-','').replace('?','%3F')
         name = artist.strip() + ' - ' + title.strip()
         profile = self.addon.getAddonInfo('profile').decode(UTF8)
         videosDir  = xbmc.translatePath(os.path.join(profile,'Videos'))
         videoDir  = xbmc.translatePath(os.path.join(videosDir, name))
         if not os.path.isdir(videoDir):
             os.makedirs(videoDir)
         strmFile = xbmc.translatePath(os.path.join(videoDir, name+'.strm'))
         with open(strmFile, 'w') as outfile:
             outfile.write('%s?mode=GV&url=%s' %(sys.argv[0], url))
         json_cmd = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan", "params": {"directory":"%s/"},"id":1}' % videoDir.replace('\\','/')
         jsonRespond = xbmc.executeJSONRPC(json_cmd)
Ejemplo n.º 22
0
    def downloadPlaying(self):
        title = xbmc.getInfoLabel('Player.Title')
        # xbmc.getInfoLabel('Player.Filenameandpath')
        url = xbmc.Player().getPlayingFile()
        thumbnail = xbmc.getInfoLabel('Player.Art(thumb)')
        extra = None
        if '|' in url:
            url, extra = url.rsplit('|', 1)
            url = url.rstrip('?')
        import time
        info = {'url': url, 'title': title, 'thumbnail': thumbnail,
                'id': int(time.time()), 'media_type': 'video'}
        if extra:
            try:
                import urlparse
                for k, v in urlparse.parse_qsl(extra):
                    if k.lower() == 'user-agent':
                        info['user_agent'] = v
                        break
            except:
                util.ERROR(hide_tb=True)

        util.LOG(repr(info), debug=True)

        from lib import YDStreamExtractor
        YDStreamExtractor.handleDownload(info, bg=True)
Ejemplo n.º 23
0
    def getControls( self ):
        coordinates = self.getControl( 2000 ).getPosition()

        c_anim = []
        try:
            import re
            for anim in re.findall( "(\[.*?\])", xbmc.getInfoLabel( "Control.GetLabel(1999)" ), re.S ):
                try: c_anim.append( tuple( eval( anim ) ) )
                except: pass
        except:
            print_exc()

        self.controls[ "background" ] = Control( self.getControl( 2001 ), coordinates, c_anim )

        self.controls[ "heading" ] = Control( self.getControl( 2002 ), coordinates, c_anim )

        self.controls[ "label" ] = Control( self.getControl( 2003 ), coordinates, c_anim )

        try:
            v = xbmc.getInfoLabel( "Control.GetLabel(2045)" ).replace( ", ", "," )
            progressTextures = dict( [ k.split( "=" ) for k in v.split( "," ) ] )
        except:
            progressTextures = {}

        self.controls[ "progress1" ] = Control( self.getControl( 2004 ), coordinates, c_anim, **progressTextures )

        self.controls[ "progress2" ] = Control( self.getControl( 2005 ), coordinates, c_anim, **progressTextures )

        self.controls[ "button" ] = Control( self.getControl( 2006 ), coordinates, c_anim )
Ejemplo n.º 24
0
 def setupvars(self):
     xbmcgui.lock()
     self.unreadvalue = 0
     self.click = 0
     self.ziplist = []
     self.subject = self.emailsettings[1][0]
     self.emfrom = self.emailsettings[1][1]
     self.to = self.myemail.get('to').replace("\n","")
     self.cc = self.myemail.get('Cc')
     if self.cc == None:
         self.cc = ""
     else:self.cc = self.cc.replace("\n","")
     date = self.myemail.get('date')
     if date == None:
         mytime = time.strptime(xbmc.getInfoLabel("System.Date") + xbmc.getInfoLabel("System.Time"),'%A , %B %d, %Y %I:%M %p')
         self.sent = time.strftime('%a, %d %b %Y %X +0000',mytime).replace("\n","")
     else:self.sent = str(date).replace("\n","")
     self.attachments = []
     self.replyvalue = 0
     self.curpos = 0
     self.showing = False
     self.returnvalue = "-"
     self.control_action = XinBox_Util.setControllerAction()
     self.attachlist = False
     xbmc.executebuiltin("Skin.Reset(attachlistnotempty)")
     xbmc.executebuiltin("Skin.Reset(emaildialog)")
Ejemplo n.º 25
0
def get_current_list_item():
    import xbmc
    ret = {"info": {}}
    keys = {
        "label": "ListItem.Label",
        "label2": "ListItem.Label2",
        "icon": "ListItem.Icon",
        "thumbnail": "ListItem.Thumb",
    }
    info_keys = {
        "title": "ListItem.Title",
        "genre": "ListItem.Genre",
        "plot": "ListItem.Plot",
        "plot_outline": "ListItem.PlotOutline",
        "tagline": "ListItem.Tagline",
        "rating": "ListItem.Rating",
        "mpaa": "ListItem.Mpaa",
        "cast": "ListItem.Cast",
        "castandrole": "ListItem.CastAndRole",
        "tvshowtitle": "ListItem.TVShowTitle",
        "studio": "ListItem.Studio",
        "picturepath": "ListItem.PicturePath",
        "year": "ListItem.Year",
        "season": "ListItem.Season",
        "episode": "ListItem.Episode",
    }
    for key, infolabel in keys.items():
        ret[key] = xbmc.getInfoLabel(infolabel)
    for key, infolabel in info_keys.items():
        ret["info"][key] = xbmc.getInfoLabel(infolabel)
    return ret
Ejemplo n.º 26
0
 def add_next_video(self):
     result = 2
     if (xbmc.Player().isPlayingVideo()):
         try: result = (int(xbmc.getInfoLabel('Playlist.Length(video)')) - int(xbmc.getInfoLabel('Playlist.Position(video)')))
         except: pass
         if result < 2:
             self.add_video()
Ejemplo n.º 27
0
def mirror_sub(id, filename, sub_file):
    try:
        playerid_query = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'
        playerid = json.loads(xbmc.executeJSONRPC(playerid_query))['result'][0]['playerid']
        imdb_id_query = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": ' + str(playerid) + ', "properties": ["imdbnumber"]}, "id": 1}'
        imdb_id = json.loads(xbmc.executeJSONRPC (imdb_id_query))['result']['item']['imdbnumber']
    except:
        imdb_id = 0

    values = {}
    values['id'] = id
    values['versioname'] = filename
    values['source'] = 'ktuvit'
    values['year'] = xbmc.getInfoLabel("VideoPlayer.Year")
    values['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))
    values['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
    values['imdb'] = str(imdb_id)
    values['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
    values['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))
    values['file_original_path'] = urllib.unquote(unicode(xbmc.Player().getPlayingFile(), 'utf-8'))
    url = 'http://api.wizdom.xyz/upload.php'
    try:
        post(url, files={'sub': open(sub_file, 'rb')}, data=values)
    except:
        pass
 def onPlayBackStarted(self):
     xbmc.sleep(1000)
     # Set values based on the file content
     if (self.isPlayingAudio()):
         self.type = "music"
     else:
         if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
             filename = ''
             isMovie = True
             try:
                 filename = self.getPlayingFile()
             except:
                 pass
             if filename != '':
                 for string in self.substrings:
                     if string in filename:
                         isMovie = False
                         break
             if isMovie:
                 self.type = "movie"
         elif xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
             # Check for tv show title and season
             # to make sure it's really an episode
             if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
                 self.type = "episode"
         elif xbmc.getCondVisibility('VideoPlayer.Content(musicvideos)'):
             self.type = "musicvideo"
Ejemplo n.º 29
0
def play(params,url,category):
	xbmc.output("[terratv.py] play")

	title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
	thumbnail = urllib.unquote_plus( params.get("thumbnail") )
	plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
	server = "Directo"
	xbmc.output("[terratv.py] thumbnail="+thumbnail)

	# Abre dialogo
	dialogWait = xbmcgui.DialogProgress()
	dialogWait.create( 'Descargando datos del vídeo...', title )

	# --------------------------------------------------------
	# Descarga pagina detalle
	# --------------------------------------------------------
	data = scrapertools.cachePage(url)
	patron = "'(http\:\/\/www\.terra\.tv\/templates\/getVideo\.aspx[^']+)'"
	matches = re.compile(patron,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)
	url = matches[0]
	xbmc.output("url="+url)

	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	data=response.read()
	response.close()
	xbmc.output("data="+data)

	patron = '<ref href="([^"]+)"'
	matches = re.compile(patron,re.DOTALL).findall(data)

	if len(matches)==0:
		patron = '<video src="([^"]+)"'
		matches = re.compile(patron,re.DOTALL).findall(data)

	url = matches[0]
	xbmc.output("url="+url)
	
	# --------------------------------------------------------
	# Amplia el argumento
	# --------------------------------------------------------
	patron = '<div id="encuesta">\s*<div class="cab">.*?</div>(.*?)</div>'
	matches = re.compile(patron,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)
	if len(matches)>0:
		plot = "%s" % matches[0]
		plot = plot.replace("<p>","")
		plot = plot.replace("</p>"," ")
		plot = plot.replace("<strong>","")
		plot = plot.replace("</strong>","")
		plot = plot.replace("<br />"," ")
		plot = plot.strip()
	
	# Cierra dialogo
	dialogWait.close()
	del dialogWait

	xbmctools.playvideo(CHANNELNAME,server,url,category,title,thumbnail,plot)
Ejemplo n.º 30
0
def login():
	dialog = xbmcgui.Dialog()
	dp = xbmcgui.DialogProgress()

	username = xbmc.getInfoLabel('App.String(username)')
	password = xbmc.getInfoLabel('App.String(password)')
		
	if(len(username)>0):
		if not dialog.yesno('Ændre login', 'Vil du ændre nuværende login?'):
			return
		
	username = ""
	password = ""
		
	while len(username)==0 or len(password)==0:
		xbmc.executebuiltin('App.SetString(username,,Indtast sputnik brugernavn)')
		xbmc.executebuiltin('App.SetString(password,,Indtast sputnik adgangskode,true)')
		
		username = xbmc.getInfoLabel('App.String(username)')
		password = xbmc.getInfoLabel('App.String(password)')
		
		try:
			dp.create( "", "", "" )
			if(login_user(username, password)):
				dialog.ok('Sådan!', 'Du er nu logget ind!');
				break

			username = ""
			password = ""
			if not dialog.yesno('Login fejlet', 'Vi kunne ikke logge dig ind - Vil du prøve igen?'):
				break
							
		except Exception, e:
			dp.close()
			dialog.ok('Error', str(e))
import xbmc

function = 'Action(%s)' % sys.argv[1]
setFocusTo = 'SetFocus(%s)' % sys.argv[2]
setFocusBackTo = 'SetFocus(%s)' % sys.argv[3]

xbmc.executebuiltin(setFocusTo)
xbmc.executebuiltin(function)
xbmc.executebuiltin(setFocusBackTo)

if (len(sys.argv) > 4):
    xbmc.sleep(100)
    getLabel = 'Control.GetLabel(%s)' % sys.argv[4]
    folderLabel = xbmc.getInfoLabel(getLabel)
    mainFolder = xbmc.getLocalizedString(20108)
    if (folderLabel == mainFolder):
        xbmc.executebuiltin(setFocusTo)
Ejemplo n.º 32
0
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]

    return param


params = get_params()
if params['action'] in ['search', 'manualsearch']:
    log(__scriptname__, "action '%s' called" % (params['action']))
    item = {}
    item['temp'] = False
    item['rar'] = False
    item['year'] = xbmc.getInfoLabel("VideoPlayer.Year")  # Year
    item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))  # Season
    item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))  # Episode
    item['tvshow'] = params['searchstring'] if params['action'] == 'manualsearch' \
        else normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))   # Show
    item['title'] = params['searchstring'] if params['action'] == 'manualsearch' \
        else normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
    item['file_original_path'] = urllib.unquote(
        xbmc.Player().getPlayingFile().decode(
            'utf-8'))  # Full path of a playing file
    item['3let_language'] = []

    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        item['3let_language'].append(xbmc.convertLanguage(
            lang, xbmc.ISO_639_2))
Ejemplo n.º 33
0
def getKodiVersion():
    return xbmc.getInfoLabel("System.BuildVersion").split(".")[0]
Ejemplo n.º 34
0
def Play_Video(video,
               showbusy=True,
               content='video',
               ignore_dp=False,
               timeout=10,
               item=None,
               player=xbmc.Player()):
    """
This will attempt to play a video and return True or False on
whether or not playback was successful. This function is similar
to Check_Playback but this actually tries a number of methods to
play the video whereas Check_Playback does not actually try to
play a video - it will just return True/False on whether or not
a video is currently playing.

If you have m3u or m3u8 playlist links please use the M3U_Selector
function to get the final resolved url.

CODE: Play_Video(video, [showbusy, content, ignore_dp, timeout, item])

AVAILABLE PARAMS:

    (*) video  -  This is the path to the video, this can be a local
    path, online path or a channel number from the PVR.

    showbusy  -  By default this is set to True which means while the
    function is attempting to playback the video the user will see the
    busy dialog. Set to False if you prefer this not to appear but do
    bare in mind a user may navigate to another section and try playing
    something else if they think this isn't doing anything.

    content  -  By default this is set to 'video', however if you're
    passing through audio you may want to set this to 'music' so the
    system can correctly set the tags for artist, song etc.

    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

    item  -  By default this is set to None and in this case the metadata
    will be auto-populated from the previous Add_Dir so you'll just get the
    basics like title, thumb and description. If you want to send through your
    own metadata in the form of a dictionary you can do so and it will override
    the auto-generation. If anything else sent through no metadata will be set,
    you would use this option if you've already set metadata in a previous function.


EXAMPLE CODE:
isplaying = koding.Play_Video('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""

    xbmc.log('### ORIGINAL VIDEO: %s' % video)
    import urlresolver
    try:
        import simplejson as json
    except:
        import json

    if not item:
        meta = {}
        for i in [
                'title', 'originaltitle', 'tvshowtitle', 'year', 'season',
                'episode', 'genre', 'rating', 'votes', 'director', 'writer',
                'plot', 'tagline'
        ]:
            try:
                meta[i] = xbmc.getInfoLabel('listitem.%s' % i)
            except:
                pass
        meta = dict((k, v) for k, v in meta.iteritems() if not v == '')
        if 'title' not in meta:
            meta['title'] = xbmc.getInfoLabel('listitem.label')
        icon = xbmc.getInfoLabel('listitem.icon')
        item = xbmcgui.ListItem(path=video,
                                iconImage=icon,
                                thumbnailImage=icon)
        if content == "music":
            try:
                meta['artist'] = xbmc.getInfoLabel('listitem.artist')
                item.setInfo(type='Music',
                             infoLabels={
                                 'title': meta['title'],
                                 'artist': meta['artist']
                             })
            except:
                item.setInfo(type='Video', infoLabels=meta)
        else:
            item.setInfo(type='Video', infoLabels=meta)

    elif type(item).__name__ == 'dict':
        item.setInfo(type='Video', infoLabels=meta)

    else:
        pass

    playback = False
    if showbusy:
        Show_Busy()

# if a plugin path is sent we try activate window
    if video.startswith('plugin://'):
        try:
            xbmc.log('Attempting to play via xbmc.Player().play() method')
            player.play(video)
            playback = Check_Playback(ignore_dp, timeout)
        except:
            xbmc.log(Last_Error())

# If an XBMC action has been sent through we do an executebuiltin command
    elif video.startswith('ActivateWindow') or video.startswith(
            'RunAddon') or video.startswith('RunScript') or video.startswith(
                'PlayMedia'):
        try:
            xbmc.log('Attempting to play via xbmc.executebuiltin method')
            xbmc.executebuiltin('%s' % video)
            playback = Check_Playback(ignore_dp, timeout)
        except:
            xbmc.log(Last_Error())

    elif ',' in video:
        # Standard xbmc.player method (a comma in url seems to throw urlresolver off)
        try:
            xbmc.log('Attempting to play via xbmc.Player.play() method')
            player.play('%s' % video, item)
            playback = Check_Playback(ignore_dp, timeout)

# Attempt to resolve via urlresolver
        except:
            try:
                xbmc.log('Attempting to resolve via urlresolver module')
                xbmc.log('video = %s' % video)
                hmf = urlresolver.HostedMediaFile(url=video,
                                                  include_disabled=False,
                                                  include_universal=True)
                if hmf.valid_url() == True:
                    video = hmf.resolve()
                    xbmc.log('### VALID URL, RESOLVED: %s' % video)
                player.play('%s' % video, item)
                playback = Check_Playback(ignore_dp, timeout)
            except:
                xbmc.log(Last_Error())

# Play from a db entry - untested
    elif video.isdigit():
        xbmc.log('### Video is digit, presuming it\'s a db item')
        command = (
            '{"jsonrpc": "2.0", "id":"1", "method": "Player.Open","params":{"item":{"channelid":%s}}}'
            % url)
        xbmc.executeJSONRPC(command)
        playback = Check_Playback(ignore_dp, timeout)

    else:
        # Attempt to resolve via urlresolver
        try:
            xbmc.log('Attempting to resolve via urlresolver module')
            xbmc.log('video = %s' % video)
            hmf = urlresolver.HostedMediaFile(url=video,
                                              include_disabled=False,
                                              include_universal=True)
            if hmf.valid_url() == True:
                video = hmf.resolve()
                xbmc.log('### VALID URL, RESOLVED: %s' % video)
            player.play('%s' % video, item)
            playback = Check_Playback(ignore_dp, timeout)

# Standard xbmc.player method
        except:
            try:
                xbmc.log('Attempting to play via xbmc.Player.play() method')
                player.play('%s' % video, item)
                playback = Check_Playback(ignore_dp, timeout)
            except:
                xbmc.log(Last_Error())

    xbmc.log('Playback status: %s' % playback)
    Show_Busy(False)
    counter = 1
    dialogprogress = xbmc.getCondVisibility('Window.IsActive(progressdialog)')
    if not ignore_dp:
        while dialogprogress:
            dp.create('Playback Good', 'Closing dialog...')
            xbmc.log('Attempting to close dp #%s' % counter)
            dp.close()
            xbmc.sleep(1000)
            counter += 1
            dialogprogress = xbmc.getCondVisibility(
                'Window.IsActive(progressdialog)')

    return playback
Ejemplo n.º 35
0
def Check_Playback(ignore_dp=False, timeout=10):
    """
This function will return true or false based on video playback. Simply start a stream
(whether via an add-on, direct link to URL or local storage doesn't matter), the code will
then work out if playback is successful. This uses a number of checks and should take into
account all potential glitches which can occur during playback. The return should happen
within a second or two of playback being successful (or not).

CODE: Check_Playback()

AVAILABLE PARAMS:

    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

EXAMPLE CODE:
xbmc.Player().play('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
isplaying = koding.Check_Playback()
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""
    if not ignore_dp:
        isdialog = True
        counter = 1

        # Check if the progress window is active and wait for playback
        while isdialog and counter < 60:
            if xbmc.getCondVisibility('Window.IsActive(progressdialog)'):
                try:
                    if dp.iscanceled():
                        dp.close()
                        break
                except:
                    pass
            xbmc.log('### Current Window: %s' %
                     xbmc.getInfoLabel('System.CurrentWindow'))
            xbmc.log('### Current XML: %s' %
                     xbmc.getInfoLabel('Window.Property(xmlfile)'))
            xbmc.log('### Progress Dialog active, sleeping for %s seconds' %
                     counter)
            xbmc.sleep(1000)
            if xbmc.getCondVisibility('Window.IsActive(progressdialog)') or (
                    xbmc.getInfoLabel('Window.Property(xmlfile)')
                    == 'DialogProgress.xml'):
                isdialog = True
            else:
                isdialog = False
            counter += 1
            xbmc.log('counter: %s' % counter)

            # Given the DialogProgress 10 seconds to finish and it's still up - time to close it
            if counter >= 10:
                try:
                    xbmc.log('attempting to send click to close dp')
                    xbmc.executebuiltin('SendClick()')
                    if dp.iscanceled():
                        dp.close()
                    try:
                        dp.close()
                    except:
                        pass
                except:
                    xbmc.log('### FAILED TO CLOSE DP')
    try:
        dp.close()
    except:
        pass

    isplaying = xbmc.Player().isPlaying()
    counter = 1
    if xbmc.Player().isPlayingAudio():
        return True
# If xbmc player is not yet active give it some time to initialise
    while not isplaying and counter < timeout:
        xbmc.sleep(1000)
        isplaying = xbmc.Player().isPlaying()
        xbmc.log('### XBMC Player not yet active, sleeping for %s seconds' %
                 counter)
        counter += 1

    success = 0
    counter = 0

    # If it's playing give it time to physically start streaming then attempt to pull some info
    if isplaying:
        xbmc.sleep(1000)
        while not success and counter < 5:
            try:
                if xbmc.Player().isPlayingVideo():
                    infotag = xbmc.Player().getVideoInfoTag()
                vidtime = xbmc.Player().getTime()
                if vidtime > 0:
                    success = 1

# If playback doesn't start automatically (buffering) we force it to play
                else:
                    xbmc.log(
                        '### Playback active but time at zero, trying to unpause'
                    )
                    xbmc.executebuiltin('PlayerControl(Play)')
                    xbmc.sleep(2000)
                    vidtime = xbmc.Player().getTime()
                    if vidtime > 0:
                        success = 1

# If no infotag or time could be pulled then we assume playback failed, try and stop the xbmc.player
            except:
                counter += 1
                xbmc.sleep(1000)

# Check if the busy dialog is still active from previous locked up playback attempt
    isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')
    counter = 1
    while isbusy:
        xbmc.log('### Busy dialog active, sleeping for %ss' % counter)
        xbmc.sleep(1000)
        isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')
        counter += 1
        if counter >= 5:
            xbmc.executebuiltin('Dialog.Close(busydialog)')

    if not success:
        xbmc.executebuiltin('PlayerControl(Stop)')
        xbmc.log('### Failed playback, stopped stream')
        return False
    else:
        return True
Ejemplo n.º 36
0
def Link_Tester(video='',
                local_check=True,
                proxy_list=None,
                proxy_url='https://free-proxy-list.net/',
                ip_col=0,
                port_col=1,
                table=0):
    """
Send through a link and test whether or not it's playable on other devices.
Many links include items in the query string which lock the content down to your
IP only so what may open fine for you may not open for anyone else!

This function will attempt to load the page using a proxy. If when trying to access
the link via a proxy the header size and content-type match then we assume the
link will play on any device. This is not fool proof and could potentially return
false positives depending on the security used on the website being accessed.

The return you'll get is a dictionary of the following items:

    'plugin_path' - This will have the path for a plugin, it means the stream was
    originally passed through an add-on to get the final link. If this is not set
    to None then it "should" work on any device so long as that add-on is installed
    (e.g. YouTube).

    'url' - This is the final resolved url which Kodi was playing, you need to check
    the status though to find out whether or not that link is locked to your IP only.

    'status' - This will return one of the following status codes:
        good - The link should work on all IPs.

        bad_link - The link was not valid, won't even play on your current Kodi setup.

        proxy_fail - None of the proxies sent through worked.

        locked - The url only works on this device, if this is the case consider using
        the plugin_path which should generally work on all devices (although this does
        depend on how the developer of that add-on coded up their add-on).

CODE: Link_Tester([proxy_list, url, ip_col, port_col, table])

AVAILABLE PARAMS:

    video  -  This is the url of the video you want to check

    local_check - By default this is set to True and this function will first of
    all attempt to play the video locally with no proxy just to make sure the
    link is valid in the first place. If you want to skip this step then set
    this to False.

    proxy_list  -  If you already have a list of proxies you want to test with
    send them through in the form of a list of dictionaries. Use the following
    format: [{"ip":"0.0.0.0","port":"80"},{"ip":"127.0.0.1","port":"8080"}]

    proxy_url  -  If you want to scrape for online proxies and loop through until a
    working one has been found you can set the url here. If using this then
    proxy_list can be left as the default (None). If you open this Link_Tester
    function with no params the defaults are setup to grab from:
    free-proxy-list.net but there is no guarantee this will always
    work, the website may well change it's layout/security over time.

    ip_col  -  If you've sent through a proxy_url then you'll need to set a column number
    for where in the table the IP address is stored. The default is 0

    port_col  -  If you've sent through a proxy_url then you'll need to set a column number
    for where in the table the port details are stored. The default is 1

    table  -  If you've sent through a proxy_url then you'll need to set a table number.
    The default is 0 - this presumes we need to use the first html table found on the
    page, if you require a different table then alter accordingly - remember zero is the
    first instance so if you want the 3rd table on the page you would set to 2.

EXAMPLE CODE:
vid_test = Link_Tester(video='http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
if vid_test['status'] == 'bad_link':
    dialog.ok('BAD LINK','The link you sent through cannot even be played on this device let alone another one!')
elif vid_test['status'] == 'proxy_fail':
    dialog.ok('PROXIES EXHAUSTED','It was not possible to get any working proxies as a result it\'s not possible to fully test whether this link will work on other devices.')
elif vid_test['status'] == 'locked':
    dialog.ok('NOT PLAYABLE','Although you can play this link locally the tester was unable to play it when using a proxy so this is no good.')
    if vid_test['plugin_path']:
        dialog.ok('THERE IS SOME GOOD NEWS!','Although the direct link for this video won\'t work on other IPs it "should" be possible to open this using the following path:\n[COLOR dodgerblue]%s[/COLOR]'%vid_test['plugin_path'])
else:
    dialog.ok('WORKING!!!','Congratulations this link can be resolved and added to your playlist.')
~"""
    import random
    import urllib
    from guitools import Notify
    from vartools import Table_Convert
    from systemtools import System
    # xbmc.executebuiltin('RunScript(special://home/addons/script.module.python.koding.aio/lib/koding/localproxy.py)')
    Notify('PLEASE WAIT', 'Checking Link - Step 1', '5000', 'Video.png')
    isplaying = xbmc.Player().isPlaying()

    # If video not yet playing try playing it
    if not isplaying:
        xbmc.Player().play(video)

    if Check_Playback(True):
        xbmclink = xbmc.Player().getPlayingFile()
        active_plugin = System(command='addonid')
        plugin_path = System(command='currentpath')
        vid_title = ''
        title_count = 0

        while vid_title == '' and title_count < 10:
            vid_title = xbmc.getInfoLabel('Player.Title')
            xbmc.sleep(100)
            title_count += 1

        xbmc.Player().stop()
        video_orig = Last_Played()
        xbmc.log('VIDEO: %s' % video_orig, 2)
        if video_orig.startswith('plugin://'):
            video = xbmclink
            xbmc.log('NEW VIDEO: %s' % video, 2)
        else:
            video = video_orig
        r = requests.head(url=video, timeout=5)
        orig_header = r.headers
        try:
            orig_size = orig_header['Content-Length']
        except:
            orig_size = 0
        try:
            orig_type = orig_header['Content-Type']
        except:
            orig_type = ''
        proxies = Table_Convert(url=proxy_url,
                                contents={
                                    "ip": ip_col,
                                    "port": port_col
                                },
                                table=table)
        myproxies = []
        used_proxies = []
        for item in proxies:
            myproxies.append({
                'http':
                'http://%s:%s' % (item['ip'], item['port']),
                'https':
                'https://%s:%s' % (item['ip'], item['port'])
            })
        success = False
        if video_orig.startswith('plugin://'):
            dp.create(
                '[COLOR gold]CHECKING PROXIES[/COLOR]',
                'This video is being parsed through another add-on so using the plugin path should work. Now checking the final resolved link...',
                '')
        else:
            dp.create('[COLOR gold]CHECKING PROXIES[/COLOR]', 'Please wait...',
                      '')

        counter = 1
        while (not success) and (len(myproxies) > 0):
            dp.update(counter / len(myproxies), 'Checking proxy %s' % counter)
            counter += 1
            proxychoice = random.choice(range(0, len(myproxies)))
            currentproxy = myproxies[proxychoice]

            # Find a working proxy and play the video through it
            try:
                xbmc.log(repr(currentproxy), 2)
                r = requests.head(url=video, proxies=currentproxy, timeout=5)
                headers = r.headers
                try:
                    new_size = headers['Content-Length']
                except:
                    new_size = 0
                try:
                    new_type = headers['Content-Type']
                except:
                    new_type = ''
                xbmc.log('orig size: %s' % orig_size, 2)
                xbmc.log('new size: %s' % new_size, 2)
                xbmc.log('orig type: %s' % orig_type, 2)
                xbmc.log('new type: %s' % new_type, 2)
                xbmc.log('VIDEO: %s' % video, 2)
                if orig_size != 0 and (orig_size
                                       == new_size) and (orig_type
                                                         == new_type):
                    dp.close()
                    success = True
            except:
                xbmc.log('failed with proxy: %s' % currentproxy, 2)

            myproxies.pop(proxychoice)
            if dp.iscanceled():
                dp.close()
                break
        plugin_path = None
        if video_orig.startswith('plugin://'):
            plugin_path = video_orig
        if len(myproxies) == 0 and not success:
            return {
                "plugin_path": plugin_path,
                "url": video,
                "status": "proxy_fail"
            }
        elif not success:
            return {
                "plugin_path": plugin_path,
                "url": video,
                "status": "locked"
            }
        else:
            return {"plugin_path": plugin_path, "url": video, "status": "good"}
    else:
        return {"plugin_path": None, "url": video, "status": "bad_link"}
        "Cached data obtained before before %s will be refreshed if details are missing"
        % (cut_off_date.strftime("%d-%m-%Y")), xbmc.LOGNOTICE)
    rt = RepeatedTimer(900, save_pickle, dict1, dict2, dict3, dict4, dict5,
                       dict6, dict7, dict8, dict9, dict10, dict11, dict12,
                       counts)

    # Main Loop
    while (not xbmc.abortRequested):
        if xbmc.getCondVisibility("Player.IsInternetStream"):
            if lastfm_first_time == 1:
                ct = datetime.datetime.now().time().second
                if lastfm_delay == ct:
                    current_track = get_lastfm_info(lastfm_username)
                    lastfm_delay = set_timer(5)
            else:
                current_track = xbmc.getInfoLabel("Player.Title")
                json_query = xbmc.executeJSONRPC(
                    '{"jsonrpc": "2.0", "method": "xbmc.GetInfoLabels", "params":{"labels": ["player.Filename"]}, "id": 1}'
                )
                file_playing = _json.loads(json_query).get('result').get(
                    'player.Filename')
            try:
                current_track = current_track.decode('utf-8')
            except BaseException:  # can't decode track
                pass  # continue with track as is
            if not file_playing:
                file_playing = current_track
            if firstpass == 0:
                firstpass = 1
                log("File playing is %s" % file_playing, xbmc.LOGDEBUG)
                log("Track playing is [%s]" % current_track, xbmc.LOGDEBUG)
Ejemplo n.º 38
0
 def status(self):
     return xbmc.getInfoLabel('Window(10000).Property(script.module.youtube.dl_STATUS)')
Ejemplo n.º 39
0
try:
    contentMode = params['contentMode'].lower() == 'true'
except:
    contentMode = False

doRefresh = False
doEnd = True
cacheToDisc = False
contentType = ''

if len(content) > 0:
    mode = _IGNORE
    folder = content
    try:
        path = xbmc.getInfoLabel('Skin.String(%s.Path)' % folder)

        if len(path) > 0:
            folder = ''
            import re
            plugin = re.compile('.+?"(.+?)"').search(path).group(1)

            prams = get_params(plugin)

            try:
                folder = urllib.unquote_plus(prams['folder'])
            except:
                pass

            if len(folder) == 0:
                mode = _FOLDER
Ejemplo n.º 40
0
    def loop(self):
        from kmediatorrent.utils import SafeDialogProgress

        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd), with_immunicity=False)
            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")
                    self.display_name = status["name"]
                    global buffer_percentage
                    global extension_message
                    global max_buffer_size
                    extension = self.getFileExtension(self.display_name)
                    BUFFERSIZE = self.getBufferSize(extension_message)
                    
                    if status["state"] >= 0 and buffer_percentage < 100 and BUFFERSIZE != max_buffer_size and extension_message == "":
                        dialog.update(int(buffer_percentage), *self._get_status_lines(status, "")) #buffering
                    elif status["state"] >= 0 and buffer_percentage >= 100 or BUFFERSIZE == max_buffer_size or extension_message != "": 
                        dialog.update(int(status["progress"] * 100), *self._get_status_lines(status, extension_message))#done buffering

                    if status["state"] >= 3 and not has_resolved: # Downloading?
                        files = t2h("ls")["files"]
                        progress = float(t2h("status")["progress"])
                        biggest_file = sorted(files, key=lambda x: x["size"])[-1]
                        biggest_file["name"] = biggest_file["name"].encode("utf-8")

                        # Estimate the video size using the biggest file size
                        # and the progress (progress is: <pcnt downloaded> / 100.0)
                        bytes_complete = float(biggest_file["size"]) * progress
                        mb_complete = bytes_complete / 1024.0 / 1024.0
                        buffer_percentage = (mb_complete / float(plugin.get_setting("min_download_size"))) * 100
                        if buffer_percentage >= 100 and BUFFERSIZE != max_buffer_size:
                            extension_message = self.getExtensionMessage(extension)
                        if extension_message == "File can not fast start. The whole file must download.":
                            BUFFERSIZE = max_buffer_size
                            
                        if mb_complete > BUFFERSIZE or bytes_complete >= biggest_file["size"]:
                            extension_message = ""
                            dialog.update(int(status["progress"] * 100), *self._get_status_lines(status, extension_message))
                            plugin.log.info("Resolving to http://%s/files/%s" % (t2h_instance.bind_address, biggest_file["name"]))
                            has_resolved = True
                            item = {
                                "path": "http://%s/files/%s" % (t2h_instance.bind_address, urllib.quote(biggest_file["name"])),
                            }
                            if not xbmc.getInfoLabel("ListItem.Title"):
                                item["label"] = self.display_name
                            plugin.set_resolved_url(item)
                            break
                    xbmc.sleep(TORRENT2HTTP_POLL)

            # We are now playing
            plugin.log.info("Now playing torrent...")
            last_playing_event = 0
            with closing(OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
                with nested(self.attach(overlay.show, self.on_playback_paused),
                            self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status"), extension_message))
                        now = time.time()
                        if (now - last_playing_event) > PLAYING_EVENT_INTERVAL:
                            track_event("video", "playing", self.display_name)
                            last_playing_event = now
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")
Ejemplo n.º 41
0
def showWeb(infile=None):  # Code qui s'occupe de liens TV du Web
    oGui = cGui()
    oInputParameterHandler = cInputParameterHandler()

    if infile is None:
        sUrl = oInputParameterHandler.getValue('siteUrl')

        playlist = parseM3U(sUrl=sUrl)
    else:
        playlist = parseM3U(infile=infile)

    if oInputParameterHandler.exist('AZ'):
        sAZ = oInputParameterHandler.getValue('AZ')
        string = filter(lambda t: t.title.strip().capitalize().startswith(sAZ),
                        playlist)
        playlist = sorted(string, key=lambda t: t.title.strip().capitalize())
    else:
        playlist = sorted(playlist, key=lambda t: t.title.strip().capitalize())

    if not playlist:
        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('siteUrl', 'http://')
        oGui.addText(
            SITE_IDENTIFIER,
            '[COLOR red]Problème de lecture avec la playlist[/COLOR]')

    else:
        total = len(playlist)
        progress_ = progress().VScreate(SITE_NAME)
        for track in playlist:
            progress_.VSupdate(progress_, total)
            if progress_.iscanceled():
                break
            sThumb = track.icon
            if not sThumb:
                sThumb = 'tv.png'

            # les + ne peuvent pas passer
            url2 = track.path.replace('+', 'P_L_U_S')
            if not xbmc.getInfoLabel('system.buildversion')[0:2] >= '19':
                if not '[' in url2 and not ']' in url2 and not '.m3u8' in url2 and not 'dailymotion' in url2:
                    url2 = 'plugin://plugin.video.f4mTester/?url=' + QuotePlus(
                        url2) + '&amp;streamtype=TSDOWNLOADER&name=' + Quote(
                            track.title)

            thumb = '/'.join([sRootArt, sThumb])

            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('siteUrl', url2)
            oOutputParameterHandler.addParameter('sMovieTitle', track.title)
            oOutputParameterHandler.addParameter('sThumbnail', thumb)

            oGuiElement = cGuiElement()
            oGuiElement.setSiteName(SITE_IDENTIFIER)
            oGuiElement.setFunction('play__')
            oGuiElement.setTitle(track.title)
            oGuiElement.setFileName(track.title)
            oGuiElement.setIcon('tv.png')
            oGuiElement.setMeta(0)
            oGuiElement.setThumbnail(thumb)
            oGuiElement.setDirectTvFanart()
            oGuiElement.setCat(6)

            oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                  SITE_IDENTIFIER, SITE_IDENTIFIER,
                                  'direct_epg', 'Guide tv Direct')
            oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                  SITE_IDENTIFIER, SITE_IDENTIFIER, 'soir_epg',
                                  'Guide tv Soir')
            oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                  SITE_IDENTIFIER, SITE_IDENTIFIER,
                                  'enregistrement', 'Enregistrement')
            oGui.createContexMenuBookmark(oGuiElement, oOutputParameterHandler)
            oGui.addFolder(oGuiElement, oOutputParameterHandler)

        progress_.VSclose(progress_)

    oGui.setEndOfDirectory()
Ejemplo n.º 42
0
    def XbmcFilmsRequest(self,
                         method,
                         url,
                         args=None,
                         returnStatus=False,
                         returnOnFailure=False,
                         silent=True,
                         passVersions=False,
                         hideResponse=False):
        raw = None
        data = None
        jdata = {}
        retries = getSettingAsInt('retries')

        if args is None:
            args = {}

        if not (method == 'POST' or method == 'GET'):
            Debug("[XbmcFilm] xbmcfilmRequest(): Unknown method '%s'." %
                  method)
            return None

        if method == 'POST':
            # debug log before username and sha1hash are injected
            Debug("[XbmcFilm] xbmcfilmRequest(): Request data: '%s'." %
                  str(json.dumps(args)))

            # inject username/pass into json data
            args['username'] = self.__username
            args['password'] = self.__password

            # check if plugin version needs to be passed
            if passVersions:
                args['plugin_version'] = scriptID
                args['media_center_version'] = xbmc.getInfoLabel(
                    'system.buildversion')
                args['media_center_date'] = xbmc.getInfoLabel(
                    'system.builddate')

            # convert to json data
            jdata = json.dumps(args)

        Debug(
            "[XbmcFilm] xbmcfilmRequest(): Starting retry loop, maximum %i retries."
            % retries)

        # start retry loop
        for i in range(retries):
            Debug("[XbmcFilm] xbmcfilmRequest(): (%i) Request URL '%s'" %
                  (i, url))

            # check if we are closing
            if xbmc.abortRequested:
                Debug(
                    "[XbmcFilm] xbmcfilmRequest(): (%i) xbmc.abortRequested" %
                    i)
                break

            try:
                # get data from xbmcfilm.tv
                raw = self.__getData(url, jdata)
            except XbmcFilmsError, e:
                if isinstance(e, XbmcFilmsServerBusy):
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) Server Busy (%s)" %
                        (i, e.value))
                    xbmc.sleep(5000)
                elif isinstance(e, XbmcFilmsAuthProblem):
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) Authentication Failure (%s)"
                        % (i, e.value))
                    setSetting('account_valid', False)
                    notification('xbmcfilm', getString(1110))
                    return
                elif isinstance(e, XbmcFilmsNetworkError):
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) Network error: %s"
                        % (i, e.value))
                    if e.timeout:
                        notification('xbmcfilm',
                                     getString(1108) +
                                     " (timeout)")  # can't connect to xbmcfilm
                    xbmc.sleep(5000)
                elif isinstance(e, XbmcFilmsUnknownError):
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) Other problem (%s)"
                        % (i, e.value))
                else:
                    pass

                xbmc.sleep(1000)
                continue

            # check if we are closing
            if xbmc.abortRequested:
                Debug(
                    "[XbmcFilm] xbmcfilmRequest(): (%i) xbmc.abortRequested" %
                    i)
                break

            # check that returned data is not empty
            if not raw:
                Debug(
                    "[XbmcFilm] xbmcfilmRequest(): (%i) JSON Response empty" %
                    i)
                xbmc.sleep(1000)
                continue

            try:
                # get json formatted data
                data = json.loads(raw)
                if hideResponse:
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) JSON response recieved, response not logged"
                        % i)
                else:
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) JSON response: '%s'"
                        % (i, str(data)))
            except ValueError:
                # malformed json response
                Debug(
                    "[XbmcFilm] xbmcfilmRequest(): (%i) Bad JSON response: '%s'"
                    % (i, raw))
                if not silent:
                    notification('xbmcfilm',
                                 getString(1109) +
                                 ": Bad response from xbmcfilm")  # Error

            # check for the status variable in JSON data
            if data and 'status' in data:
                if data['status'] == 'success':
                    break
                elif returnOnFailure and data['status'] == 'failure':
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): Return on error set, breaking retry."
                    )
                    break
                elif 'error' in data and data['status'] == 'failure':
                    Debug(
                        "[XbmcFilm] xbmcfilmRequest(): (%i) JSON Error '%s' -> '%s'"
                        % (i, data['status'], data['error']))
                    xbmc.sleep(1000)
                    continue
                else:
                    pass

            # check to see if we have data, an empty array is still valid data, so check for None only
            if not data is None:
                Debug(
                    "[XbmcFilm] xbmcfilmRequest(): Have JSON data, breaking retry."
                )
                break

            xbmc.sleep(500)
Ejemplo n.º 43
0
    def _try_get_color_from_skin():
        skin_dir = xbmc.getSkinDir()
        skin_color = None
        if not skin_dir:
            return None
        skin_theme = xbmc.getInfoLabel("Skin.CurrentTheme")
        if not skin_theme:
            return None
        skin_theme = skin_theme.lower()
        if skin_dir == "skin.confluence":
            skin_color = "FFEB9E17"
        elif skin_dir == "skin.estuary":
            if "brown" in skin_theme:
                skin_color = "FFFF4400"
            elif "charcoal" in skin_theme:
                skin_color = "FF11E7B1"
            elif "chartreuse" in skin_theme:
                skin_color = "FF24C6C9"
            elif "concrete" in skin_theme:
                skin_color = "FFFF8C00"
            elif "default" in skin_theme:
                skin_color = "FF11E7B1"
            elif "gold" in skin_theme:
                skin_color = "FFFFF000"
            elif "green" in skin_theme:
                skin_color = "FF14D519"
            elif "maroon" in skin_theme:
                skin_color = "FF24C6C9"
            elif "midnight" in skin_theme:
                skin_color = "FF5BE5EE"
            elif "orange" in skin_theme:
                skin_color = "FFFFF100"
            elif "pink" in skin_theme:
                skin_color = "FF94D800"
            elif "rose" in skin_theme:
                skin_color = "FFFF0261"
            elif "teal" in skin_theme:
                skin_color = "FFC67F03"
            elif "violet" in skin_theme:
                skin_color = "FFFF0054"
        elif skin_dir == "skin.estouchy":
            skin_color = "FF11E7B1"
        elif skin_dir == "skin.arctic.horizon":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.arctic.zephyr":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.arctic.zephyr.2":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.aura":
            skin_color = "ff0385b5 "
        elif skin_dir == "skin.eminence.2":
            skin_color = "ff287ba8"
        elif skin_dir == "skin.eminence":
            if "crimson" in skin_theme:
                skin_color = "ffdc143c"
            elif "emerald" in skin_theme:
                skin_color = "ff46b995"
            elif "lilac" in skin_theme:
                skin_color = "ffa682a6"
            elif "lime" in skin_theme:
                skin_color = "FFb5e533"
            elif "magenta" in skin_theme:
                skin_color = "FFe533b5"
            elif "orange" in skin_theme:
                skin_color = "ffd76c38"
            elif "default" in skin_theme:
                skin_color = "FF33b5e5"
        elif skin_dir == "skin.aura":
            skin_color = "ffededed"
        elif skin_dir == "skin.fuse.neue":
            skin_color = "ffe53564"
        elif skin_dir == "skin.auramod":
            skin_color = "ffededed"

        result = xbmc.getInfoLabel("Skin.String({})".format(
            "focuscolor.name")  # jurial based skins.
                                   )
        return result if result else skin_color
Ejemplo n.º 44
0
# Updated:	09.14.2011
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import urllib, os, re
import xbmc
from BeautifulSoup import *

# general variables
__dataPath__ = os.path.join('special://skin/system/D400040/Friend/')

__GamerAvatarFolder__ = __dataPath__ + "/avatars/"
__GamerPictureFolder__ = __dataPath__ + "/pictures/"
__GameIconFolder__ = __dataPath__ + "/icons/"

__XbmcFriend5__ = xbmc.getInfoLabel('$INFO[Skin.string(Friend5)]')
__XboxGamertag__ = __XbmcFriend5__.replace(" ", "%20")


def xebi(td):
    log('Skin.Setting : ' + td)
    xbmc.executebuiltin(td)


def log(msg):
    xbmc.log('XBox.Gamertag: ' + str(msg), level=xbmc.LOGDEBUG)


def downloadImage(url, destfold, dest=None):

    log('IMAGE URL: ' + url)
Ejemplo n.º 45
0
COOKIEFILE = os.path.join(pldatapath, 'cookies.lwp')
def_fanart = os.path.join(pluginpath, 'fanart.jpg')
na = 'not available'
BASE_URL = 'https://www.amazon.de'
ATV_URL = 'https://atv-eu.amazon.com'
UserAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
movielib = '/gp/video/%s/movie/'
tvlib = '/gp/video/%s/tv/'
lib = 'video-library'
wl = 'watchlist'
Ages = [('FSK 0', 'FSK 0'), ('FSK 6', 'FSK 6'), ('FSK 12', 'FSK 12'),
        ('FSK 16', 'FSK 16'), ('FSK 18', 'FSK 18')]
verbLog = addon.getSetting('logging') == 'true'
playMethod = int(addon.getSetting("playmethod"))
onlyGer = addon.getSetting('content_filter') == 'true'
kodi_mjver = int(xbmc.getInfoLabel('System.BuildVersion')[0:2])
Dialog = xbmcgui.Dialog()
socket.setdefaulttimeout(30)

try:
    pluginhandle = int(sys.argv[1])
    params = re.sub('<|>', '', sys.argv[2])
except IndexError:
    pluginhandle = -1
    params = ''
args = dict(urlparse.parse_qsl(urlparse.urlparse(params).query))

if addon.getSetting('ssl_verif') == 'true' and hasattr(
        ssl, '_create_unverified_context'):
    ssl._create_default_https_context = ssl._create_unverified_context
Ejemplo n.º 46
0
def parseM3U(sUrl=None, infile=None):  # Traite les m3u local
    oGui = cGui()
    oInputParameterHandler = cInputParameterHandler()
    sUrl = oInputParameterHandler.getValue('siteUrl')

    if infile is None:
        if 'iptv4sat' in sUrl or '.zip' in sUrl:
            sHtmlContent = getHtml(sUrl)
            zip_files = ZipFile(io.BytesIO(sHtmlContent))
            files = zip_files.namelist()

            for Title in files:
                oOutputParameterHandler = cOutputParameterHandler()
                oOutputParameterHandler.addParameter('sMovieTitle', Title)
                oOutputParameterHandler.addParameter('siteUrl', sUrl)

                oGui.addDir(SITE_IDENTIFIER, 'unZip', Title, 'tv.png',
                            oOutputParameterHandler)

            oGui.setEndOfDirectory()
            return

        elif '#EXTM3U' not in sUrl:
            site = infile
            headers = {'User-Agent': UA}

            oRequestHandler = cRequestHandler(sUrl)
            oRequestHandler.addHeaderEntry('User-Agent', UA)
            inf = oRequestHandler.request()

            if 'drive.google' in inf:
                inf = unGoogleDrive(inf)

            inf = inf.split('\n')
        else:
            inf = infile

    else:
        inf = infile

    try:
        line = inf.readline()
    finally:
        pass

    playlist = []
    song = track(None, None, None, None)
    ValidEntry = False

    for line in inf:
        if xbmc.getInfoLabel('system.buildversion')[0:2] >= '19':
            try:
                line = line.decode('utf-8')
            except AttributeError:
                pass

        line = line.strip()
        if line.startswith('#EXTINF:'):
            length, title = line.split('#EXTINF:')[1].split(',', 1)
            try:
                licon = line.split('#EXTINF:')[1].partition('tvg-logo=')[2]
                icon = licon.split('"')[1]
            except:
                icon = 'tv.png'
            ValidEntry = True
            song = track(length, title, None, icon)

        elif (len(line) != 0):
            if (ValidEntry) and (not (line.startswith('!')
                                      or line.startswith('#'))):
                ValidEntry = False
                song.path = line
                playlist.append(song)
                song = track(None, None, None, None)

    try:
        inf.close()
    finally:
        pass

    return playlist
Ejemplo n.º 47
0
#  This Program is distributed in the hope that it will be useful,             #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of              #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                #
#  GNU General Public License for more details.                                #
#                                                                              #
#  You should have received a copy of the GNU General Public License           #
#  along with XBMC; see the file COPYING.  If not, write to                    #
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.       #
#  http://www.gnu.org/copyleft/gpl.html                                        #
################################################################################

import zipfile, xbmcaddon, xbmc, uservar, sys, os, time

import wizard as wiz

KODIV = float(xbmc.getInfoLabel("System.BuildVersion")[:4])
if KODIV > 17:
    import zfile as zipfile  #FTG mod for Kodi 18
else:
    import zipfile

ADDON_ID = uservar.ADDON_ID
ADDONTITLE = uservar.ADDONTITLE
COLOR1 = uservar.COLOR1
COLOR2 = uservar.COLOR2
ADDON = wiz.addonId(ADDON_ID)
HOME = xbmc.translatePath('special://home/')
USERDATA = os.path.join(HOME, 'userdata')
GUISETTINGS = os.path.join(USERDATA, 'guisettings.xml')
KEEPFAVS = wiz.getS('keepfavourites')
KEEPSOURCES = wiz.getS('keepsources')
Ejemplo n.º 48
0
 def reload_profile():
     xbmc.executebuiltin('LoadProfile({})'.format(
         xbmc.getInfoLabel("system.profilename")))
Ejemplo n.º 49
0
 def isMusicVideoTitles():
     return xbmc.getInfoLabel(
         "container.folderpath") == "videodb://musicvideos/"
Ejemplo n.º 50
0
class PlexInterface(plexapp.AppInterface):
    _regs = {
        None: {},
    }
    _globals = {
        'platform': 'Kodi',
        'appVersionStr': util.ADDON.getAddonInfo('version'),
        'clientIdentifier': CLIENT_ID,
        'platformVersion': xbmc.getInfoLabel('System.BuildVersion'),
        'product': 'Plex for Kodi',
        'provides': 'player',
        'device': util.getPlatform() or plexapp.PLATFORM,
        'model': 'Unknown',
        'friendlyName': 'Kodi Add-on iOS',
        'supports1080p60': True,
        'vp9Support': True,
        'transcodeVideoQualities': [
            "10", "20", "30", "30", "40", "60", "60", "75", "100", "60", "75", "90", "100", "100"
        ],
        'transcodeVideoResolutions': [
            plexapp.Res((220, 180)),
            plexapp.Res((220, 128)),
            plexapp.Res((284, 160)),
            plexapp.Res((420, 240)),
            plexapp.Res((576, 320)),
            plexapp.Res((720, 480)),
            plexapp.Res((1024, 768)),
            plexapp.Res((1280, 720)),
            plexapp.Res((1280, 720)),
            maxVideoRes, maxVideoRes, maxVideoRes, maxVideoRes, maxVideoRes
        ],
        'transcodeVideoBitrates': [
            "64", "96", "208", "320", "720", "1500", "2000", "3000", "4000", "8000", "10000", "12000", "20000", "200000"
        ],
        'deviceInfo': plexapp.DeviceInfo()
    }

    def getPreference(self, pref, default=None):
        if pref == 'manual_connections':
            return self.getManualConnections()
        else:
            return util.getSetting(pref, default)

    def getManualConnections(self):
        conns = []
        for i in range(2):
            ip = util.getSetting('manual_ip_{0}'.format(i))
            if not ip:
                continue
            port = util.getSetting('manual_port_{0}'.format(i), 32400)
            conns.append({'connection': ip, 'port': port})
        return json.dumps(conns)

    def setPreference(self, pref, value):
        util.setSetting(pref, value)

    def getRegistry(self, reg, default=None, sec=None):
        if sec == 'myplex' and reg == 'MyPlexAccount':
            ret = util.getSetting('{0}.{1}'.format(sec, reg), default)
            if ret:
                return ret
            return json.dumps({'authToken': util.getSetting('auth.token')})
        else:
            return util.getSetting('{0}.{1}'.format(sec, reg), default)

    def setRegistry(self, reg, value, sec=None):
        util.setSetting('{0}.{1}'.format(sec, reg), value)

    def clearRegistry(self, reg, sec=None):
        util.setSetting('{0}.{1}'.format(sec, reg), '')

    def addInitializer(self, sec):
        pass

    def clearInitializer(self, sec):
        pass

    def getGlobal(self, glbl, default=None):
        if glbl == 'transcodeVideoResolutions':
            maxres = self.getPreference('allow_4k', True) and plexapp.Res((3840, 2160)) or plexapp.Res((1920, 1080))
            self._globals['transcodeVideoResolutions'][-5:] = [maxres] * 5
        return self._globals.get(glbl, default)

    def getCapabilities(self):
        return ''

    def LOG(self, msg):
        util.DEBUG_LOG('API: {0}'.format(msg))

    def DEBUG_LOG(self, msg):
        self.LOG('DEBUG: {0}'.format(msg))

    def WARN_LOG(self, msg):
        self.LOG('WARNING: {0}'.format(msg))

    def ERROR_LOG(self, msg):
        self.LOG('ERROR: {0}'.format(msg))

    def ERROR(self, msg=None, err=None):
        if err:
            self.LOG('ERROR: {0} - {1}'.format(msg, err.message))
        else:
            util.ERROR()

    def supportsAudioStream(self, codec, channels):
        return True
        # if codec = invalid then return true

        # canDownmix = (m.globals["audioDownmix"][codec] <> invalid)
        # supportsSurroundSound = m.SupportsSurroundSound()

        # if not supportsSurroundSound and canDownmix then
        #     maxChannels = m.globals["audioDownmix"][codec]
        # else
        #     maxChannels = firstOf(m.globals["audioDecoders"][codec], 0)
        # end if

        # if maxChannels > 2 and not canDownmix and not supportsSurroundSound then
        #     ' It's a surround sound codec and we can't do surround sound
        #     supported = false
        # else if maxChannels = 0 or maxChannels < channels then
        #     ' The codec is either unsupported or can't handle the requested channels
        #     supported = false
        # else
        #     supported = true

        # return supported

    def supportsSurroundSound(self):
        return True

    def getQualityIndex(self, qualityType):
        if qualityType == self.QUALITY_LOCAL:
            return self.getPreference("local_quality", 13)
        elif qualityType == self.QUALITY_ONLINE:
            return self.getPreference("online_quality", 8)
        else:
            return self.getPreference("remote_quality", 13)

    def getMaxResolution(self, quality_type, allow4k=False):
        qualityIndex = self.getQualityIndex(quality_type)

        if qualityIndex >= 9:
            if self.getPreference('allow_4k', True):
                return allow4k and 2160 or 1088
            else:
                return 1088
        elif qualityIndex >= 6:
            return 720
        elif qualityIndex >= 5:
            return 480
        else:
            return 360
Ejemplo n.º 51
0
 def isMovies():
     return xbmc.getCondVisibility("Container.Content(movies)") or (
         xbmc.getInfoLabel("ListItem.dbtype")
         == 'movie') or WindowShowing.isTvTunesOverrideMovie()
Ejemplo n.º 52
0
import sys
import xbmc

# functions that on kodi 19 moved to xbmcvfs
try:
    import xbmcvfs
    xbmc.translatePath = xbmcvfs.translatePath
    xbmc.validatePath = xbmcvfs.validatePath
    xbmc.makeLegalFilename = xbmcvfs.makeLegalFilename
except:
    pass
from platformcode import config, logger

logger.info("init...")

librerias = xbmc.translatePath(os.path.join(config.get_runtime_path(), 'lib'))
sys.path.insert(0, librerias)

if 'elsupremo' in xbmc.getInfoLabel('Container.FolderPath'):
    from platformcode.platformtools import dialog_ok
    dialog_ok('Kodi on Demand',
              'Non consentito sfruttare KoD da add-on esterni')
    exit()

from platformcode import launcher

if sys.argv[2] == "":
    launcher.start()

launcher.run()
Ejemplo n.º 53
0
 def isSeasons():
     return xbmc.getCondVisibility("Container.Content(Seasons)") or (
         xbmc.getInfoLabel("ListItem.dbtype")
         == 'season') or WindowShowing.isTvTunesOverrideTvShows()
Ejemplo n.º 54
0
 def isRecentEpisodesAdded():
     return xbmc.getInfoLabel(
         "container.folderpath") == "videodb://recentlyaddedepisodes/"
Ejemplo n.º 55
0
 def get_resolution(self):
     return int(xbmc.getInfoLabel('System.ScreenWidth')), int(
         xbmc.getInfoLabel('System.ScreenHeight'))
Ejemplo n.º 56
0
 def isEpisodes():
     return xbmc.getCondVisibility("Container.Content(Episodes)") or (
         xbmc.getInfoLabel("ListItem.dbtype")
         == 'episode') or WindowShowing.isTvTunesOverrideTvShows()
Ejemplo n.º 57
0
def Adult_Toggle(adult_list=[], disable=True, update_status=0):
    """
Remove/Enable a list of add-ons, these are put into a containment area until enabled again.

CODE: Adult_Toggle(adult_list, [disable, update_status])

AVAILABLE PARAMS:
            
    (*) adult_list  -  A list containing all the add-ons you want to be disabled.

    disable  -  By default this is set to true so any add-ons in the list sent
    through will be disabled. Set to False if you want to enable the hidden add-ons.

    update_status  - When running this function it needs to disable the
    auto-update of add-ons by Kodi otherwise it risks crashing. This
    update_status paramater is the state you want Kodi to revert back to
    once the toggle of add-ons has completed. By default this is set to 0
    which is auto-update. You can also choose 1 (notify of updates) or 2
    (disable auto updates).

~"""
    from filetools import End_Path, Move_Tree, Physical_Path

    adult_store = Physical_Path(
        "special://profile/addon_data/script.module.python.koding.aio/adult_store"
    )
    disable_list = []
    if not xbmcvfs.exists(adult_store):
        xbmcvfs.mkdirs(adult_store)
    my_addons = Installed_Addons()
    if disable:
        for item in my_addons:
            if item != None:
                item = item["addonid"]
                if item in adult_list:
                    disable_list.append(item)

        Toggle_Addons(addon=disable_list,
                      enable=False,
                      safe_mode=True,
                      refresh=True,
                      update_status=update_status)
        for item in disable_list:
            try:
                addon_path = xbmcaddon.Addon(id=item).getAddonInfo("path")
            except:
                addon_path = Physical_Path(os.path.join(ADDONS, item))
            path_id = End_Path(addon_path)
            if os.path.exists(addon_path):
                Move_Tree(addon_path, os.path.join(adult_store, path_id))
    else:
        KODI_VER = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
        addon_vault = []
        if os.path.exists(adult_store):
            for item in os.listdir(adult_store):
                store_dir = os.path.join(adult_store, item)
                addon_dir = os.path.join(ADDONS, item)
                if os.path.exists(store_dir):
                    Move_Tree(store_dir, addon_dir)
                    addon_vault.append(item)

        if KODI_VER >= 16:
            Toggle_Addons(addon=addon_vault,
                          safe_mode=True,
                          refresh=True,
                          update_status=update_status)
        else:
            Refresh(['addons', 'repos'])
Ejemplo n.º 58
0
def run():

    # Init settings
    settings_update()

    cache_path_check()

    if not platform_check():
        return False

    # Clear any existing window properties
    homewindow.setProperty(PROP_DO_REFRESH, 'false')
    homewindow.setProperty(PROP_DO_DELETE, 'false')
    homewindow.setProperty(PROP_DO_EXPIRE, 'false')

    monitor = MyMonitor(update_settings=settings_update)

    lastMaintenance = 0
    lastPath = ''
    global refreshing
    if expireEnable:
        if cleanStartup:
            # Do maintenance without interruption so expired lists
            # are loaded immediately
            maintain_caches(interruptable=False)
            lastMaintenance = time.time()
        else:
            # Do maintenance at first idle
            lastMaintenance = time.time() - 2 * cleanIdleSeconds

    _log(u'Entering main loop')
    while not monitor.abortRequested():
        if homewindow.getProperty(PROP_DO_REFRESH) == 'true':
            homewindow.setProperty(PROP_DO_REFRESH, 'false')
            # Prevent multiple refreshes
            if not refreshing:
                file = get_current_cache_file()
                refresh_list(file)
        elif homewindow.getProperty(PROP_DO_DELETE) == 'true':
            homewindow.setProperty(PROP_DO_DELETE, 'false')
            delete_all_caches(ask=True)
        elif homewindow.getProperty(PROP_DO_EXPIRE) == 'true':
            homewindow.setProperty(PROP_DO_EXPIRE, 'false')
            dialog = xbmcgui.Dialog()
            if dialog.yesno(addonName, language(32505)):
                maintain_caches(interruptable=False, manual=True)
                lastMaintenance = time.time()
            del dialog

        # Do maintenance periodically when idling and allow interruption
        if (expireEnable and cleanIdle
                and (time.time() - lastMaintenance > cleanIdleSeconds)
                and (xbmc.getGlobalIdleTime() > IDLE_DELAY_SECONDS)):
            if maintain_caches(interruptable=True):
                lastMaintenance = time.time()

        # Detect video, music and picture file list windows
        if xbmcgui.getCurrentWindowId() in [
                WINDOW_VIDEO_NAV, WINDOW_MUSIC_FILES, WINDOW_PICTURES
        ]:

            # Only interested in plugin folders
            folderpath = xbmc.getInfoLabel('Container.FolderPath')
            if folderpath.startswith('plugin://'):
                # Use visibility of busy window to determine when
                # finished loading, favourites don't show busy window
                # so check numitems as well
                busy = xbmc.getCondVisibility('Window.IsVisible(' +
                                              str(WINDOW_DIALOG_BUSY) + ')')
                numitems = mk_int(xbmc.getInfoLabel('Container.NumItems'))

                if not busy and (numitems > 0):
                    if refreshing or (folderpath != lastPath):
                        refreshing = False
                        _log(u'Check cache for folderpath: ' + folderpath)
                        check_current_cache()
                        lastPath = folderpath
                else:
                    refreshing = True
            else:
                lastPath = ''

        monitor.waitForAbort(0.5)

    del monitor

    return True
Ejemplo n.º 59
0
# as any other add-ons which use this code. Thank you for your cooperation.

import datetime
import os
import sys
import shutil
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs

import filetools

ADDONS = 'special://home/addons'
XBMC_PATH = xbmc.translatePath('special://xbmc')
kodi_ver = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
dialog = xbmcgui.Dialog()


#----------------------------------------------------------------
# TUTORIAL #
def Addon_Genre(genre='adult', custom_url=''):
    """
Return a dictionary of add-ons which match a specific genre.

CODE: Addon_Genre([genre, custom_url])

AVAILABLE PARAMS:
    
    genre  -  By default this is set to 'adult' which will return
    a dictionary of all known adult add-ons. The genre details are pulled from the
Ejemplo n.º 60
0
def Toggle_Addons(addon='all',
                  enable=True,
                  safe_mode=True,
                  exclude_list=[],
                  new_only=True,
                  refresh=True,
                  update_status=0):
    """
Send through either a list of add-on ids or one single add-on id.
The add-ons sent through will then be added to the addons*.db
and enabled or disabled (depending on state sent through).

WARNING: If safe_mode is set to False this directly edits the
addons*.db rather than using JSON-RPC. Although directly amending
the db is a lot quicker there is no guarantee it won't cause
severe problems in later versions of Kodi (this was created for v17).
DO NOT set safe_mode to False unless you 100% understand the consequences!

CODE:  Toggle_Addons([addon, enable, safe_mode, exclude_list, new_only, refresh])

AVAILABLE PARAMS:
    (*) addon  -  This can be a list of addon ids, one single id or
    'all' to enable/disable all. If enabling all you can still use
    the exclude_list for any you want excluded from this function.
    enable  -  By default this is set to True, if you want to disable
    the add-on(s) then set this to False.
    
    safe_mode  -  By default this is set to True which means the add-ons
    are enabled/disabled via JSON-RPC which is the method recommended by
    the XBMC foundation. Setting this to False will result in a much
    quicker function BUT there is no guarantee this will work on future
    versions of Kodi and it may even cause corruption in future versions.
    Setting to False is NOT recommended and you should ONLY use this if
    you 100% understand the risks that you could break multiple setups.
    
    exclude_list  -  Send through a list of any add-on id's you do not
    want to be included in this command.
    
    new_only  -  By default this is set to True so only newly extracted
    add-on folders will be enabled/disabled. This means that any existing
    add-ons which have deliberately been disabled by the end user are
    not affected.
    
    refresh  - By default this is set to True, it will refresh the
    current container and also force a local update on your add-ons db.

    update_status  - When running this function it needs to disable the
    auto-update of add-ons by Kodi otherwise it risks crashing. This
    update_status paramater is the state you want Kodi to revert back to
    once the toggle of add-ons has completed. By default this is set to 0
    which is auto-update. You can also choose 1 (notify of updates) or 2
    (disable auto updates).

EXAMPLE CODE:
from systemtools import Refresh
xbmc.executebuiltin('ActivateWindow(Videos, addons://sources/video/)')
xbmc.sleep(2000)
dialog.ok('DISABLE YOUTUBE','We will now disable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=False, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
xbmc.sleep(2000)
dialog.ok('ENABLE YOUTUBE','When you click OK we will enable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=True, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
~"""
    from __init__ import dolog
    from filetools import DB_Path_Check, Get_Contents
    from database import DB_Query
    from systemtools import Last_Error, Refresh, Set_Setting, Sleep_If_Function_Active, Timestamp
    from vartools import Data_Type

    Set_Setting('general.addonupdates', 'kodi_setting', '2')
    dolog('disabled auto updates for add-ons')
    kodi_ver = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
    addons_db = DB_Path_Check('addons')
    data_type = Data_Type(addon)
    state = int(bool(enable))
    enabled_list = []
    disabled_list = []
    if kodi_ver >= 17:
        on_system = DB_Query(addons_db,
                             'SELECT addonID, enabled from installed')
        # Create a list of enabled and disabled add-ons already on system
        enabled_list = Addon_List(enabled=True)
        disabled_list = Addon_List(enabled=False)

# If addon has been sent through as a string we add into a list
    if data_type == 'unicode':
        addon = addon.encode('utf8')
        data_type = Data_Type(addon)

    if data_type == 'str' and addon != 'all':
        addon = [addon]

# Grab all the add-on ids from addons folder
    if addon == 'all':
        addon = []
        ADDONS = xbmc.translatePath('special://home/addons')
        my_addons = Get_Contents(path=ADDONS,
                                 exclude_list=['packages', 'temp'])
        for item in my_addons:
            addon_id = Get_Addon_ID(item)
            addon.append(addon_id)

# Find out what is and isn't enabled in the addons*.db
    temp_list = []
    for addon_id in addon:
        if not addon_id in exclude_list and addon_id != '':
            if addon_id in disabled_list and not new_only and enable:
                temp_list.append(addon_id)
            elif addon_id not in disabled_list and addon_id not in enabled_list:
                temp_list.append(addon_id)
            elif addon_id in enabled_list and not enable:
                temp_list.append(addon_id)
            elif addon_id in disabled_list and enable:
                temp_list.append(addon_id)
    addon = temp_list

    # If you want to bypass the JSON-RPC mode and directly modify the db (READ WARNING ABOVE!!!)
    if not safe_mode and kodi_ver >= 17:
        installedtime = Timestamp('date_time')
        insert_query = 'INSERT or IGNORE into installed (addonID , enabled, installDate) VALUES (?,?,?)'
        update_query = 'UPDATE installed SET enabled = ? WHERE addonID = ? '
        insert_values = [addon, state, installedtime]
        try:
            for item in addon:
                DB_Query(addons_db, insert_query, [item, state, installedtime])
                DB_Query(addons_db, update_query, [state, item])
        except:
            dolog(Last_Error())
        if refresh:
            Refresh()

# Using the safe_mode (JSON-RPC)
    else:
        mydeps = []
        final_enabled = []
        if state:
            my_value = 'true'
            log_value = 'ENABLED'
            final_addons = []
        else:
            my_value = 'false'
            log_value = 'DISABLED'
            final_addons = addon

        for my_addon in addon:

            # If enabling the add-on then we also check for dependencies and enable them first
            if state:
                dependencies = Dependency_Check(addon_id=my_addon,
                                                recursive=True)
                mydeps.append(dependencies)

    # if enable selected we traverse through the dependencies enabling addons with lowest amount of deps to highest
        if state:
            mydeps = sorted(mydeps, key=len)
            for dep in mydeps:
                counter = 0
                for item in dep:
                    enable_dep = True
                    if counter == 0:
                        final_addons.append(item)
                        enable_dep = False
                    elif item in final_enabled:
                        enable_dep = False
                    else:
                        enable_dep = True
                    if enable_dep:
                        if not item in exclude_list and not item in final_enabled and not item in enabled_list:
                            if Set_Setting(setting_type='addon_enable',
                                           setting=item,
                                           value='true'):
                                final_enabled.append(item)
                    counter += 1

    # Now the dependencies are enabled we need to enable the actual main add-ons
        for my_addon in final_addons:
            if not my_addon in final_enabled:
                if Set_Setting(setting_type='addon_enable',
                               setting=my_addon,
                               value=my_value):
                    final_enabled.append(addon)
    if refresh:
        Refresh(['addons', 'container'])
    Set_Setting('general.addonupdates', 'kodi_setting', '%s' % update_status)


#----------------------------------------------------------------