def _shuffle_slides( tmp_slides, watched ):
    utils.log( "Sorting Watched/Unwatched and Shuffing Slides ", xbmc.LOGNOTICE )
    slide_playlist = []
    # randomize the groups and create our play list
    count = 0
    while count <6:
        shuffle( tmp_slides, random )
        count += 1
    # now create our final playlist
    # loop thru slide groups and skip already watched groups
    for slides in tmp_slides:
        # has this group been watched
        if ( not slide_settings[ "trivia_unwatched_only" ] or ( slides[ 0 ] and xbmc.getCacheThumbName( slides[ 0 ] ) not in watched ) or
              ( slides[ 1 ] and xbmc.getCacheThumbName( slides[ 1 ] ) not in watched ) or
              ( slides[ 2 ] and xbmc.getCacheThumbName( slides[ 2 ] ) not in watched ) ):
            # loop thru slide group only include non blank slides
            for slide in slides:
                # only add if non blank
                if ( slide ):
                    # add slide
                    slide_playlist += [ slide ]
            utils.log( "-------- Unwatched --------     included - %s, %s, %s" % ( os.path.basename( slides[ 0 ] ), os.path.basename( slides[ 1 ] ), os.path.basename( slides[ 2 ] ), ) )
            
        else:
            utils.log( "-------- Watched --------     skipped - %s, %s, %s" % ( os.path.basename( slides[ 0 ] ), os.path.basename( slides[ 1 ] ), os.path.basename( slides[ 2 ] ), ) )

    utils.log( "-----------------------------" )
    utils.log( "Total slides selected: %d" % len( slide_playlist ), xbmc.LOGNOTICE )

    # reset watched automatically if no slides are left
    if ( len( slide_playlist ) == 0 and slide_settings[ "trivia_unwatched_only" ] and len( watched ) > 0 ):
        watched = _reset_watched()
        #attempt to load our playlist again
        _shuffle_slides( tmp_slides, watched )
    return slide_playlist
    def _shuffle_slides( self ):
        # randomize the groups and create our play list
        shuffle( self.tmp_slides )
        # now create our final playlist
        print "-----------------------------------------"
        # loop thru slide groups and skip already watched groups
        for slides in self.tmp_slides:
            # has this group been watched
            if ( not self.settings[ "trivia_unwatched_only" ] or ( slides[ 0 ] and xbmc.getCacheThumbName( slides[ 0 ] ) not in self.watched ) or
                  ( slides[ 1 ] and xbmc.getCacheThumbName( slides[ 1 ] ) not in self.watched ) or
                  ( slides[ 2 ] and xbmc.getCacheThumbName( slides[ 2 ] ) not in self.watched ) ):
                # loop thru slide group only include non blank slides
                for slide in slides:
                    # only add if non blank
                    if ( slide ):
                        # add slide
                        self.slide_playlist += [ slide ]

                print "included - %s, %s, %s" % ( os.path.basename( slides[ 0 ] ), os.path.basename( slides[ 1 ] ), os.path.basename( slides[ 2 ] ), )
            else:
                print "----------------------------------------------------"
                print "skipped - %s, %s, %s" % ( os.path.basename( slides[ 0 ] ), os.path.basename( slides[ 1 ] ), os.path.basename( slides[ 2 ] ), )
                print "----------------------------------------------------"
        print
        print "total slides selected: %d" % len( self.slide_playlist )
        print
Exemple #3
0
def getCachedThumb(file):
        if file[0:8] == 'stack://':
            commaPos = file.find(' , ')
            file = xbmc.getCacheThumbName(file[8:commaPos].strip())

        crc = xbmc.getCacheThumbName(file.lower())
        return xbmc.translatePath('special://profile/Thumbnails/Video/%s/%s' % (crc[0], crc))
 def _shuffle_trailers( self ):
     # randomize the groups and create our play list
     log( "%s - Shuffling Trailers" % logmessage, xbmc.LOGNOTICE )
     shuffle( self.tmp_trailers )
     # reset counter
     count = 0
     # now create our final playlist
     for trailer in self.tmp_trailers:
         # user preference to skip watch trailers
         if ( self.settings[ "trailer_unwatched_only" ] and xbmc.getCacheThumbName( trailer ) in self.watched ):
             continue
         # add trailer to our final list
         trailer_info = _set_trailer_info( trailer )
         trailer_genre = trailer_info[ 9 ].split(" / ")
         trailer_rating = trailer_info[ 6 ].replace("Rated ", "")
         if self.settings[ "trailer_limit_genre" ] and ( not list(set(trailer_genre) & set(self.genre) ) ):
             log( "%s - Genre Not Matched - Skipping Trailer" % logmessage )
             continue
         if self.settings[ "trailer_limit_mpaa" ] and ( not trailer_rating or not trailer_rating == self.mpaa ):
             log( "%s - MPAA Not Matched - Skipping Trailer" % logmessage )
             continue
         self.trailers += [ trailer_info ]
         # add id to watched file TODO: maybe don't add if not user preference
         self.watched += [ xbmc.getCacheThumbName( trailer ) ]
         # increment counter
         count += 1
         # if we have enough exit
         if ( count == self.settings[ "trailer_count" ] ):
             break
     if ( len(self.trailers) == 0 and self.settings[ "trailer_unwatched_only" ] and len( self.watched ) > 0 ):
         self._reset_watched()
         #attempt to load our playlist again
         self._shuffle_trailers()
 def _shuffle_trailers( self ):
     # randomize the groups and create our play list
     utils.log( "Shuffling Trailers", xbmc.LOGNOTICE )
     shuffle( self.tmp_trailers )
     count = 0
     # now create our final playlist
     for trailer in self.tmp_trailers:
         # user preference to skip watch trailers
         if ( self.settings[ "trailer_unwatched_only" ] and xbmc.getCacheThumbName( trailer ) in self.watched ):
             continue
         # add trailer to our final list
         trailer_info = _set_trailer_info( trailer )
         trailer_genre = trailer_info[ 9 ].split(" / ")
         trailer_rating = trailer_info[ 6 ].replace("Rated ", "")
         if self.settings[ "trailer_limit_genre" ]:
             if len( set( trailer_genre ).intersection( self.genre ) ) < 1:
                 utils.log("Genre Not Matched - Skipping Trailer: %s != %s" % (trailer_genre, self.genre) )
                 continue
         if self.settings[ "trailer_limit_mpaa" ]:
             trailer_mpaa = self.mpaa_ratings.index( trailer_rating )
             if trailer_mpaa > self.mpaa:
                 utils.log("MPAA too high - Skipping Trailer: %s > %s" % ( trailer_rating, self.mpaa_ratings[ self.mpaa ] ) )
                 continue 
         self.trailers += [ trailer_info ]
         # add id to watched file TODO: maybe don't add if not user preference
         self.watched += [ xbmc.getCacheThumbName( trailer ) ]
         # increment counter
         count += 1
         # if we have enough exit
         if ( count == self.settings[ "trailer_count" ] ):
             break
     if ( len( self.trailers ) == 0 and self.settings[ "trailer_unwatched_only" ] and len( self.watched ) > 0 ):
         self._reset_watched()
         #attempt to load our playlist again
         self._shuffle_trailers()
 def _shuffle_trailers( self ):
     # randomize the groups and create our play list
     shuffle( self.tmp_trailers )
     # reset counter
     count = 0
     # now create our final playlist
     for trailer in self.tmp_trailers:
         # user preference to skip watch trailers
         if ( self.settings[ "trailer_unwatched_only" ] and xbmc.getCacheThumbName( trailer[ 0 ] ) in self.watched ):
             ##print "SKIPPED:", repr(trailer[ 0 ])
             continue
         # set all info
         tmp_trailer = self._set_trailer_info( trailer )
         # convert mpaa if necessary
         if ( self.mpaa_conversion is not None ):
             tmp_trailer[ 6 ] = self.mpaa_conversion.get( tmp_trailer[ 6 ], "NR" )
         # do we need to skip this one
         if ( self.mpaa_ratings.get( self.mpaa, self.settings[ "unrated_rating_index" ] ) < self.mpaa_ratings.get( tmp_trailer[ 6 ], self.settings[ "unrated_rating_index" ] ) ):
             ##LOG( "Skipping trailer: %s  - Movie: %s, Unrated: %s, Trailer: %s" % ( repr( tmp_trailer[ 1 ] ), self.mpaa, ("G","PG","PG-13","R","NC-17",)[ self.settings[ "mpaa_rating" ] ], tmp_trailer[ 6 ], ) )
             continue
         # add id to watched file
         if ( self.settings[ "trailer_unwatched_only" ] ):
             self.watched += [ xbmc.getCacheThumbName( trailer[ 0 ] ) ]
         # add trailer to our final list
         self.trailers += [ tmp_trailer ]
         # increment counter
         count += 1
         # if we have enough exit
         if ( count == self.settings[ "trailer_count" ] ):
             break
	def getCacheThumb( self, path, file ):
		play_path = fanart_path = thumb_path = path + file
		if ( file.startswith( "stack://" ) ):
			play_path = fanart_path = file
			thumb_path = file[ 8 : ].split( " , " )[ 0 ]
		if ( file.startswith( "rar://" ) or file.startswith( "zip://" ) ):
			play_path = fanart_path = thumb_path = file
		return xbmc.getCacheThumbName( thumb_path ), xbmc.getCacheThumbName( fanart_path ), play_path
Exemple #8
0
    def PrepareCacheDirs(self, item):
        chandirname = xbmc.getCacheThumbName(item.channel.link).replace(".tbn","")
        tpath = xbmc.translatePath('special://masterprofile/Thumbnails/RSS/%s' % chandirname)
        checkDir(tpath)

        itemdirname = xbmc.getCacheThumbName(item.link).replace(".tbn","")
        tpath = os.path.join(tpath, itemdirname)
        checkDir(tpath)

        item.multiimagepath = tpath
Exemple #9
0
 def _get_media( self, path, file ):
     # set default values
     play_path = fanart_path = thumb_path = path + file
     # we handle stack:// media special
     if ( file.startswith( "stack://" ) ):
         play_path = fanart_path = file
         thumb_path = file[ 8 : ].split( " , " )[ 0 ]
     # we handle rar:// and zip:// media special
     if ( file.startswith( "rar://" ) or file.startswith( "zip://" ) ):
         play_path = fanart_path = thumb_path = file
     # return media info
     return xbmc.getCacheThumbName( thumb_path ), xbmc.getCacheThumbName( fanart_path ), play_path
Exemple #10
0
 def _fetch_music_info( self ):
         # Current Working Directory
         # sql statement
         if ( self.ALBUMS ):
             sql_music = "select * from albumview order by RANDOM() limit %d" % ( self.LIMIT, )
             # query the database for recently added albums
             music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), )
             # separate the records
             items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL )
             # enumerate thru our records and set our properties
             for count, item in enumerate( items ):
                 # separate individual fields
                 fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL )
                 # set properties
                 self.WINDOW.setProperty( "RandomSong.%d.Title" % ( count + 1, ), fields[ 1 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Year" % ( count + 1, ), fields[ 8 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Artist" % ( count + 1, ), fields[ 6 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Rating" % ( count + 1, ), fields[ 18 ] )
                 # Album Path  (ID)
                 path = 'XBMC.RunScript(script.randomitems,albumid=' + fields[ 0 ] + ')'
                 self.WINDOW.setProperty( "RandomSong.%d.Path" % ( count + 1, ), path )
                 # get cache name of path to use for fanart
                 cache_name = xbmc.getCacheThumbName( fields[ 6 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) )
                 self.WINDOW.setProperty( "RandomSong.%d.Thumb" % ( count + 1, ), fields[ 9 ] )
         else:
             # set our unplayed query
             unplayed = ( "", "where lastplayed is null ", )[ self.UNPLAYED ]
             # sql statement
             sql_music = "select * from songview %sorder by RANDOM() limit %d" % ( unplayed, self.LIMIT, )
             # query the database
             music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), )
             # separate the records
             items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL )
             # enumerate thru our records and set our properties
             for count, item in enumerate( items ):
                 # separate individual fields
                 fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL )
                 # set properties
                 self.WINDOW.setProperty( "RandomSong.%d.Title" % ( count + 1, ), fields[ 3 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Year" % ( count + 1, ), fields[ 6 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Artist" % ( count + 1, ), fields[ 24 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Album" % ( count + 1, ), fields[ 21 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Rating" % ( count + 1, ), fields[ 18 ] )
                 path = fields[ 22 ]
                 # don't add song for albums list TODO: figure out how toplay albums
                 ##if ( not self.ALBUMS ):
                 path += fields[ 8 ]
                 self.WINDOW.setProperty( "RandomSong.%d.Path" % ( count + 1, ), path )
                 # get cache name of path to use for fanart
                 cache_name = xbmc.getCacheThumbName( fields[ 24 ] )
                 self.WINDOW.setProperty( "RandomSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) )
                 self.WINDOW.setProperty( "RandomSong.%d.Thumb" % ( count + 1, ), fields[ 27 ] )
 def _get_media( self, path, file ):
     # set default values
     play_path = fanart_path = thumb_path = path + file
     # we handle stack:// media special
     if ( file.startswith( "stack://" ) ):
         play_path = fanart_path = file
         thumb_path = file[ 8 : ].split( " , " )[ 0 ]
     # we handle rar:// and zip:// media special
     if ( file.startswith( "rar://" ) or file.startswith( "zip://" ) ):
         play_path = fanart_path = thumb_path = file
     # strip username/password
     return xbmc.getCacheThumbName( re.sub( "//.+?@", "//", thumb_path ) ), xbmc.getCacheThumbName( re.sub( "//.+?@", "//", fanart_path ) ), play_path
 def get_cached_thumb(self, filename):
     if filename.startswith("stack://"):
         filename = strPath[ 8 : ].split(" , ")[ 0 ]
     if filename.endswith("folder.jpg"):
         cachedthumb = xbmc.getCacheThumbName(filename)
         thumbpath = os.path.join( THUMBS_CACHE_PATH, cachedthumb[0], cachedthumb ).replace( "/Video" , "")
     else:
         cachedthumb = xbmc.getCacheThumbName(filename)
         if ".jpg" in filename:
             cachedthumb = cachedthumb.replace("tbn" ,"jpg")
         elif ".png" in filename:
             cachedthumb = cachedthumb.replace("tbn" ,"png")      
         thumbpath = os.path.join( THUMBS_CACHE_PATH, cachedthumb[0], cachedthumb ).replace( "/Video" , "")    
     return thumbpath         
Exemple #13
0
 def get_path( self, pack_type, icon ):
     if ( pack_type == "scripts" ):
         path = xbmc.translatePath( os.path.join( "Q:\\%s" % pack_type, icon + "\\" ) )
         cached_thumbnail = xbmc.getCacheThumbName( os.path.join( path, "default.py" ) )
         if ( os.path.isdir( path ) ):
             return path, cached_thumbnail, None
     else:
         for source in ( "video", "music", "pictures", "programs", ):
             path = xbmc.translatePath( os.path.join( "Q:\\%s" % pack_type, source, icon + "\\" ) )
             cached_thumbnail = xbmc.getCacheThumbName( path )
             root_cached_thumbnail = xbmc.getCacheThumbName( "plugin://video/" + icon + "/" )
             if ( os.path.isdir( path ) ):
                 return path, cached_thumbnail, root_cached_thumbnail
     return None, None, None
    def move_movie(self, movie, old_path, new_path):
        ## Update file with new id
        # Create query
        query = "UPDATE files \
                 SET    idPath=? \
                 WHERE  idFile=?"
        # Create values
        value = new_path.meta, movie.meta
        # Create a cursor
        c = self.db.create_cursor()
        # Launch query
        c.execute(query, value)

        ### Move file
        ## Get filename
        # Create query
        query = "SELECT f.strFilename \
                 FROM   files f \
                 WHERE  f.idFile = ?"
        # Create values
        value = (movie.meta,)
        # Launch query
        c.execute(query, value)
        # Build result
        mfile = unicode(c.fetchone()[0])
        # mfile = unicode( c.fetchone()[0] )

        ## Deal with stacked files
        if mfile.startswith("stack://"):
            logging.dbg("Dealing with stacked files")
            # Update db file with new values
            query = "UPDATE files \
                     SET    strFilename=? WHERE idFile=?"
            # Create values
            strfn = mfile.replace(old_path, new_path)
            value = strfn, movie.meta
            # Launch query
            c.execute(query, value)
            # Get fanart cache filename and move it
            srcfn = xbmc.translatePath("special://thumbnails/Video") + "/Fanart/" + xbmc.getCacheThumbName(mfile)
            dstfn = xbmc.translatePath("special://thumbnails/Video") + "/Fanart/" + xbmc.getCacheThumbName(strfn)
            try:
                shutil.move(srcfn, dstfn)
                logging.dbg("move %s %s" % (srcfn, dstfn))
            except IOError, e:
                logging.err("Error moving %s %s: %s" % (srcfn, dstfn, e))
                pass
            # Create file list with removed whites spaces arround names
            mfiles = map(lambda x: x.strip(), mfile[8:].split(","))
Exemple #15
0
    def clean_thumbnail(self, video_url):
        """
        Clean thumb
        This is done because XBMC does not use the right thumb in the case of sub categories
        The reason is the Cache Thumb Name is based on a URL such as 'plugin://plugin.video.M6Replay/?display_pos=0'
        Which can reprensent different category (for the same URL) depending on the change in the XML
        """
        try:
            filename = xbmc.getCacheThumbName(video_url)
            filepath = xbmc.translatePath(
                os.path.join(THUMB_CACHE_PATH, filename[0], filename))
            if os.path.isfile(filepath):
                os.remove(filepath)
                if self.debug_mode:
                    print "Deleted %s thumb matching to %s video" % (filepath,
                                                                     video_url)
            elif self.debug_mode:
                print "No thumb found %s thumb matching to %s video" % (
                    filepath, video_url)

            return True
        except:
            print "Error: clean_thumbnail()"
            print_exc()
            return False
Exemple #16
0
    def searchGames(self):
        log('|==================================|')
        log('searchGames().start')

        listItems = []
        self.getControl(191).setLabel('[B]Games[/B]')
        gamesSQL = 'SELECT xbeDescription, strFileName FROM files WHERE strFileName LIKE "F:\GAMES%" AND xbeDescription LIKE "%' + self.SEARCH_STRING + '%"'
        log('searchGames().sql = ' + gamesSQL)
        gamesXML = xbmc.executehttpapi(
            "QueryProgramDatabase(%s)" % quote_plus(gamesSQL), )
        games = re.findall("<record>(.+?)</record>", gamesXML, re.DOTALL)
        results = len(games)

        log('searchGames().results: ' + str(results))

        for count, game in enumerate(games):
            fields = re.findall("<field>(.*?)</field>", game, re.DOTALL)
            thumb_cache = xbmc.getCacheThumbName(fields[1])
            thumb = "special://profile/Thumbnails/Programs/%s/%s" % (
                thumb_cache[0],
                thumb_cache,
            )
            listItem = xbmcgui.ListItem(fields[0], fields[0], thumb, thumb)
            listItem.setProperty('path', fields[1])
            listItem.setProperty('content', 'game')
            listItems.append(listItem)

        if results > 0:
            log('searchGames().success')
            self.getControl(201).addItems(listItems)
            self.getControl(200).setLabel(str(results))
            self.getControl(209).setVisible(True)
            self.CONTENT_FOUND = 'true'
        log('searchGames().end')
Exemple #17
0
def get_thumbnail( thumbnail_url, fanart=0, default='DefaultTouTv.png' ):
    global badthumbs, STRBADTHUMBS
    default = ( default, "" )[ fanart ]
    if thumbnail_url and thumbnail_url not in STRBADTHUMBS:
        try:
            filename = xbmc.getCacheThumbName( thumbnail_url )
            if fanart:
                filename = filename.replace( ".tbn", os.path.splitext( thumbnail_url )[ 1 ] )
                basedir  = os.path.dirname( BASE_CACHE_PATH )
            else:
                basedir = BASE_CACHE_PATH
            filepath = os.path.join( BASE_CACHE_PATH, filename[ 0 ], filename )

            if not os.path.exists( filepath ):
                if not os.path.exists( os.path.dirname( filepath ) ):
                    os.makedirs( os.path.dirname( filepath ) )
                fp, h = urllib.urlretrieve( thumbnail_url, filepath )
                if h[ "Content-Type" ] == "text/html":
                    print "bad thumb: %r" % thumbnail_url
                    print fp, str( h ).replace( "\r", "" )
                    try: os.remove( fp )
                    except: pass
                    filepath = ""

                    STRBADTHUMBS += thumbnail_url + "\n"
                    badthumbs.write( thumbnail_url + "\n" )
            thumbnail_url = filepath
        except:
            print_exc()
    elif thumbnail_url and thumbnail_url in STRBADTHUMBS:
        thumbnail_url = ""
    return thumbnail_url or default
def itemHashwithPath(item, thepath):
    if isXBMC:
        thumb = xbmc.getCacheThumbName(item).replace('.tbn', '')
    else:
        thumb = hashlib.md5( item.encode() ).hexdigest()
    thumbpath = os.path.join( thepath, thumb.encode( 'utf-8' ) )
    return thumbpath
 def _save_thumb(self):
     # create thumb cache path
     cached_thumb = os.path.join(
         xbmc.translatePath("special://thumbnails/"),
         xbmc.getCacheThumbName(self.movie["thumbnail"])[0],
         xbmc.getCacheThumbName(self.movie["thumbnail"]).replace(
             ".tbn", os.path.splitext(self.movie["thumbnail"].split("|")[0])[1]
         ),
     ).decode("UTF-8")
     # create saved thumb path
     saved_thumb = u"{root}.tbn".format(
         root=os.path.splitext(self.filepath)[0]  # ,
         # ext=os.path.splitext(self.movie["thumbnail"].split("|")[0])[1]
     ).decode("UTF-8")
     # copy thumb
     xbmcvfs.copy(cached_thumb, saved_thumb)
def favouritesDataGen():
    file = xbmcvfs.File(FAVOURITES_PATH)
    contents = file.read().decode('utf-8')
    file.close()

    namePattern = re.compile('name="([^"]+)')
    thumbPattern = re.compile('thumb="([^"]+)')

    for entryMatch in re.finditer('(<favourite\s[^<]+</favourite>)', contents):
        entry = entryMatch.group(1)

        match = namePattern.search(entry)
        name = PARSER.unescape(match.group(1)) if match else ''

        match = thumbPattern.search(entry)
        if match:
            thumb = PARSER.unescape(match.group(1))
            cacheFilename = xbmc.getCacheThumbName(thumb)
            if 'ffffffff' not in cacheFilename:
                if '.jpg' in thumb:
                    cacheFilename = cacheFilename.replace('.tbn', '.jpg', 1)
                if '.png' in thumb:
                    cacheFilename = cacheFilename.replace('.tbn', '.png', 1)
                thumb = THUMBNAILS_PATH_FORMAT.format(folder=cacheFilename[0],
                                                      file=cacheFilename)
        else:
            thumb = ''

        # Yield a 3-tuple of name, thumb-url and the original content of the favourites entry.
        yield name, thumb, entry
 def startPlayBack(self):
     print "onPlayBackStarted started"
     if xbmc.Player().isPlayingAudio() == True:
         currentlyPlayingTitle = xbmc.Player().getMusicInfoTag().getTitle()
         print currentlyPlayingTitle + " started playing"
         currentlyPlayingArtist = xbmc.Player().getMusicInfoTag().getArtist(
         )
         self.countFoundTracks = 0
         if (self.firstRun == 1):
             self.firstRun = 0
             #print "firstRun - clearing playlist"
             album = xbmc.Player().getMusicInfoTag().getAlbum()
             cache_name = xbmc.getCacheThumbName(
                 os.path.dirname(xbmc.Player().getMusicInfoTag().getURL()))
             print "Playing file: %s" % xbmc.Player().getMusicInfoTag(
             ).getURL()
             thumb = "special://profile/Thumbnails/Music/%s/%s" % (
                 cache_name[:1],
                 cache_name,
             )
             duration = xbmc.Player().getMusicInfoTag().getDuration()
             listitem = self.getListItem(currentlyPlayingTitle,
                                         currentlyPlayingArtist, album,
                                         thumb, duration)
             xbmc.PlayList(0).clear()
             xbmc.executebuiltin('XBMC.ActivateWindow(10500)')
             xbmc.PlayList(0).add(
                 url=xbmc.Player().getMusicInfoTag().getURL(),
                 listitem=listitem)
             self.addedTracks += [xbmc.Player().getMusicInfoTag().getURL()]
         #print "Start looking for similar tracks"
         self.fetch_similarTracks(currentlyPlayingTitle,
                                  currentlyPlayingArtist)
def blur(input_img, radius=25):
    if not input_img:
        return {}
    if not xbmcvfs.exists(IMAGE_PATH):
        xbmcvfs.mkdir(IMAGE_PATH)
    input_img = utils.translate_path(urllib.unquote(input_img.encode("utf-8")))
    input_img = input_img.replace("image://", "").rstrip("/")
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = "%s-radius_%i.png" % (cachedthumb, radius)
    targetfile = os.path.join(IMAGE_PATH, filename)
    vid_cache_file = os.path.join("special://profile/Thumbnails/Video",
                                  cachedthumb[0], cachedthumb)
    cache_file = os.path.join("special://profile/Thumbnails", cachedthumb[0],
                              cachedthumb[:-4] + ".jpg")
    if xbmcvfs.exists(targetfile):
        img = PIL.Image.open(targetfile)
        return {"ImageFilter": targetfile, "ImageColor": get_colors(img)}
    try:
        if xbmcvfs.exists(cache_file):
            utils.log("image already in xbmc cache: " + cache_file)
            img = PIL.Image.open(utils.translate_path(cache_file))
        elif xbmcvfs.exists(vid_cache_file):
            utils.log("image already in xbmc video cache: " + vid_cache_file)
            img = PIL.Image.open(utils.translate_path(vid_cache_file))
        else:
            xbmcvfs.copy(input_img, targetfile)
            img = PIL.Image.open(targetfile)
        img.thumbnail((200, 200), PIL.Image.ANTIALIAS)
        imgfilter = MyGaussianBlur(radius=radius)
        img = img.convert('RGB').filter(imgfilter)
        img.save(targetfile)
    except Exception:
        utils.log("Could not get image for %s" % input_img)
        return {}
    return {"ImageFilter": targetfile, "ImageColor": get_colors(img)}
 def FindBug(self, chtype, chname):
     self.log("FindBug, chname = " + chname)
     try:
         setImage = ''
         BugFLE = xbmc.translatePath(os.path.join(LOGO_LOC,(chname + '.png')))
         cachedthumb = xbmc.getCacheThumbName(BugFLE)
         cachefile = xbmc.translatePath(os.path.join(ART_LOC, cachedthumb[0], cachedthumb[:-4] + ".png")).replace("\\", "/")
         DefaultBug = self.getDefaultBug(chname)
         
         # no channel bug for livetv/internettv
         if chtype in [8,9]:
             return 'NA.png' 
         else:
             if REAL_SETTINGS.getSetting('UNAlter_ChanBug') == 'true':
                 if FileAccess.exists(BugFLE) == False:
                     BugFLE = DefaultBug
                 return BugFLE
             else:
                 if FileAccess.exists(cachefile) == True:
                     return cachefile
                 elif FileAccess.exists(BugFLE) == False:
                     return DefaultBug
                 return self.ConvertBug(BugFLE, cachefile)
     except Exception,e:  
         self.log("FindBug, Failed" + str(e), xbmc.LOGERROR)
         return 'NA.png'
Exemple #24
0
 def startPlayBack(self):
     print "[LFM PLG(PM)] onPlayBackStarted started"
     if xbmc.Player().isPlayingAudio() == True:
         currentlyPlayingTitle = xbmc.Player().getMusicInfoTag().getTitle()
         currentlyPlayingArtist = xbmc.Player().getMusicInfoTag().getArtist(
         )
         print "[LFM PLG(PM)] " + currentlyPlayingArtist + " - " + currentlyPlayingTitle + " started playing"
         self.countFoundTracks = 0
         if (self.firstRun == 1):
             self.firstRun = 0
             album = xbmc.Player().getMusicInfoTag().getAlbum()
             cache_name = xbmc.getCacheThumbName(
                 os.path.dirname(xbmc.Player().getMusicInfoTag().getURL()))
             print "[LFM PLG(PM)] Playing file: %s" % xbmc.Player(
             ).getMusicInfoTag().getURL()
             thumb = "special://profile/Thumbnails/Music/%s/%s" % (
                 cache_name[:1],
                 cache_name,
             )
             duration = xbmc.Player().getMusicInfoTag().getDuration()
             fanart = ""
             listitem = self.getListItem(currentlyPlayingTitle,
                                         currentlyPlayingArtist, album,
                                         thumb, fanart, duration)
             xbmc.PlayList(0).clear()
             xbmc.executebuiltin('XBMC.ActivateWindow(10500)')
             xbmc.PlayList(0).add(
                 url=xbmc.Player().getMusicInfoTag().getURL(),
                 listitem=listitem)
             self.addedTracks += [
                 self.unicode_normalize_string(
                     xbmc.Player().getMusicInfoTag().getURL())
             ]
         self.main_similarTracks(currentlyPlayingTitle,
                                 currentlyPlayingArtist)
Exemple #25
0
    def _get_tags(self):
        # get track tags
        artist = self.getMusicInfoTag().getArtist().decode("utf-8")
        album = self.getMusicInfoTag().getAlbum().decode("utf-8")
        title = self.getMusicInfoTag().getTitle().decode("utf-8")
        duration = str(self.getMusicInfoTag().getDuration())
        # get duration from xbmc.Player if the MusicInfoTag duration is invalid
        if int(duration) <= 0:
            duration = str(int(self.getTotalTime()))
        track = str(self.getMusicInfoTag().getTrack())
        path = self.getPlayingFile().decode("utf-8")
        thumb = xbmc.getCacheThumbName(path)
        #log('artist: ' + artist)
        #log('title: ' + title)
        #log('album: ' + album)
        #log('track: ' + str(track))
        #log('duration: ' + str(duration))
        #log('path: ' + path)
        #log('local path: ' + user)
        #log('thumb: ' + thumb)

        #log('cover art: ' + str(xbmc.getInfoLabel('MusicPlayer.Cover')))
        #log('thumb art: ' + str(xbmc.getInfoLabel('Player.Art(thumb)')))
        #log('fan art: ' + str(xbmc.getInfoLabel('MusicPlayer.Property(Fanart_Image)')))

        return [artist, title]
Exemple #26
0
 def run(self):
     cachedthumb = xbmc.getCacheThumbName(self.url)
     xbmc_cache_file = os.path.join(xbmc.translatePath("special://profile/Thumbnails/Video"), cachedthumb[0], cachedthumb)
     if xbmcvfs.exists(xbmc_cache_file):
         log("Cached Image: " + self.url)
         return xbmc_cache_file
     else:
         try:
             log("Download: " + self.url)
             request = urllib2.Request(self.url)
             request.add_header('Accept-encoding', 'gzip')
             response = urllib2.urlopen(request)
             data = response.read()
             response.close()
             log('image downloaded')
         except:
             log('image download failed')
             return ""
         if data != '':
             try:
                 tmpfile = open(xbmc_cache_file, 'wb')
                 tmpfile.write(data)
                 tmpfile.close()
                 return xbmc_cache_file
             except:
                 log('failed to save image')
                 return ""
         else:
             return ""
def itemHashwithPath(item, thepath):
    if isXBMC:
        thumb = xbmc.getCacheThumbName(item).replace('.tbn', '')
    else:
        thumb = hashlib.md5(item.encode()).hexdigest()
    thumbpath = os.path.join(thepath, thumb.encode('utf-8'))
    return thumbpath
Exemple #28
0
 def _fetch_tvshow_info(self):
     # set our unplayed query
     unplayed = ("", "where playCount is null ")[self.UNPLAYED]
     # sql statement
     if self.RANDOM_ORDER:
         # random order
         sql_episodes = "select * from episodeview %sorder by RANDOM() limit %d" % (unplayed, self.LIMIT)
     elif self.RECENT:
         # recently added
         sql_episodes = "select * from episodeview %sorder by idEpisode desc limit %d" % (unplayed, self.LIMIT)
     else:
         # tv shows not finished
         sql_episodes = (
             "select episodeview.*, bookmark.timeInSeconds from episodeview join bookmark on (episodeview.idFile = bookmark.idFile) %sorder by episodeview.strTitle limit %d"
             % (unplayed, self.LIMIT)
         )
     # query the database
     episodes_xml = xbmc.executehttpapi("QueryVideoDatabase(%s)" % quote_plus(sql_episodes))
     # separate the records
     episodes = re.findall("<record>(.+?)</record>", episodes_xml, re.DOTALL)
     # enumerate thru our records and set our properties
     for count, episode in enumerate(episodes):
         # separate individual fields
         fields = re.findall("<field>(.*?)</field>", episode, re.DOTALL)
         # set properties
         self.WINDOW.setProperty("LatestEpisode.%d.ShowTitle" % (count + 1,), fields[28])
         self.WINDOW.setProperty("LatestEpisode.%d.EpisodeTitle" % (count + 1,), fields[2])
         self.WINDOW.setProperty(
             "LatestEpisode.%d.EpisodeNo" % (count + 1,), "s%02de%02d" % (int(fields[14]), int(fields[15]))
         )
         self.WINDOW.setProperty("LatestEpisode.%d.Rating" % (count + 1,), fields[5])
         self.WINDOW.setProperty("LatestEpisode.%d.EpisodeSeason" % (count + 1,), fields[14])
         self.WINDOW.setProperty("LatestEpisode.%d.EpisodeNumber" % (count + 1,), fields[15])
         self.WINDOW.setProperty("LatestEpisode.%d.Plot" % (count + 1,), fields[3])
         # get cache names of path to use for thumbnail/fanart and play path
         thumb_cache, fanart_cache, play_path = self._get_media(fields[25], fields[24])
         if not os.path.isfile(
             xbmc.translatePath("special://profile/Thumbnails/Video/%s/%s" % ("Fanart", fanart_cache))
         ):
             fanart_cache = xbmc.getCacheThumbName(os.path.join(os.path.split(os.path.split(fields[25])[0])[0], ""))
         if os.path.isfile(
             "%s.dds"
             % (
                 xbmc.translatePath(
                     "special://profile/Thumbnails/Video/%s/%s" % ("Fanart", os.path.splitext(fanart_cache)[0])
                 )
             )
         ):
             fanart_cache = "%s.dds" % (os.path.splitext(fanart_cache)[0],)
         self.WINDOW.setProperty("LatestEpisode.%d.Path" % (count + 1,), play_path)
         self.WINDOW.setProperty(
             "LatestEpisode.%d.Fanart" % (count + 1,),
             "special://profile/Thumbnails/Video/%s/%s" % ("Fanart", fanart_cache),
         )
         # initial thumb path
         thumb = "special://profile/Thumbnails/Video/%s/%s" % (thumb_cache[0], thumb_cache)
         # if thumb does not exist use an auto generated thumb path
         if not os.path.isfile(xbmc.translatePath(thumb)):
             thumb = "special://profile/Thumbnails/Video/%s/auto-%s" % (thumb_cache[0], thumb_cache)
         self.WINDOW.setProperty("LatestEpisode.%d.Thumb" % (count + 1,), thumb)
Exemple #29
0
 def _play_video(self):
     # Youtube client
     client = YoutubeClient(authkey=xbmcplugin.getSetting("authkey"))
     # construct the video url with session id and get video details
     url, title, director, genre, rating, runtime, count, date, thumbnail, plotoutline, video_id = client.construct_video_url(
         self.args.video_url, (
             18,
             22,
         )[xbmcplugin.getSetting("hd_videos") == "true"])
     # get cached thumbnail, no need to redownload
     thumbnail = xbmc.getCacheThumbName(sys.argv[0] + sys.argv[2])
     thumbnail = os.path.join(xbmc.translatePath("special://profile"),
                              "Thumbnails", "Video", thumbnail[0],
                              thumbnail)
     # construct our listitem
     listitem = xbmcgui.ListItem(title, thumbnailImage=thumbnail, path=url)
     # set the key information
     listitem.setInfo(
         "video", {
             "Title": title,
             "Plotoutline": plotoutline,
             "Plot": plotoutline,
             "Director": director,
             "Genre": genre,
             "Rating": rating,
             "Date": date
         })
     # Resolve url
     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
Exemple #30
0
def get_thumbnail(thumbnail_url, allowDownload=True):
    log("get_thumbnail() %s" % thumbnail_url)
    # make the proper cache filename and path so duplicate caching is unnecessary
    if (not thumbnail_url.startswith("http://")): return thumbnail_url
    try:
        filename = xbmc.getCacheThumbName(thumbnail_url)
        filepath = xbmc.translatePath(
            os.path.join(BASE_CACHE_PATH, filename[0], filename))
        # if the cached thumbnail does not exist fetch the thumbnail
        if not os.path.isfile(filepath):
            if allowDownload:
                # fetch thumbnail and save to filepath
                log("get_thumbnail() downloading from=%s to %s" %
                    (thumbnail_url, filepath))
                info = urlretrieve(thumbnail_url, filepath)
                # cleanup any remaining urllib cache
                urlcleanup()
            else:
                return thumbnail_url
        else:
            log("get_thumbnail() use existing=" + filepath)
        return filepath
    except:
        # return empty string if retrieval failed
        print str(sys.exc_info()[1])
        return thumbnail_url
Exemple #31
0
def cacheImage(source,dest_path):
	f, ext = os.path.splitext(source)  # @UnusedVariable
	base = xbmc.getCacheThumbName(source)[:-4]
	dest = os.path.join(dest_path,base + ext)
	with open(dest,'wb') as f:
		f.write(urllib2.urlopen(source).read())
	return dest
Exemple #32
0
def get_cached_thumb(filename):
    if filename.startswith("stack://"):
        filename = strPath[8:].split(" , ")[0]
    if filename.endswith("folder.jpg"):
        cachedthumb = xbmc.getCacheThumbName(filename)
        thumbpath = os.path.join(THUMBS_CACHE_PATH, cachedthumb[0],
                                 cachedthumb).replace("/Video", "")
    else:
        cachedthumb = xbmc.getCacheThumbName(filename)
        if ".jpg" in filename:
            cachedthumb = cachedthumb.replace("tbn", "jpg")
        elif ".png" in filename:
            cachedthumb = cachedthumb.replace("tbn", "png")
        thumbpath = os.path.join(THUMBS_CACHE_PATH, cachedthumb[0],
                                 cachedthumb).replace("/Video", "")
    return thumbpath
Exemple #33
0
 def _fetch_movie_info( self ):
     # sql statement
     if ( self.RECENT ):
         # recently added
         sql_movies = "select * from movieview order by idMovie desc limit %d" % ( self.LIMIT, )
     else:
         # movies not finished
         sql_movies = "select movieview.*, bookmark.timeInSeconds from movieview join bookmark on (movieview.idFile = bookmark.idFile) order by movieview.c00 limit %d" % ( self.LIMIT, )
     # query the database
     movies_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_movies ), )
     # separate the records
     movies = re.findall( "<record>(.+?)</record>", movies_xml, re.DOTALL )
     # enumerate thru our records and set our properties
     for count, movie in enumerate( movies ):
         # separate individual fields
         fields = re.findall( "<field>(.*?)</field>", movie, re.DOTALL )
         # set title
         self.WINDOW.setProperty( "LatestMovie.%d.Title" % ( count + 1, ), fields[ 1 ] )
         # set year
         self.WINDOW.setProperty( "LatestMovie.%d.Year" % ( count + 1, ), fields[ 8 ] )
         # set running time
         self.WINDOW.setProperty( "LatestMovie.%d.RunningTime" % ( count + 1, ), fields[ 12 ] )
         # set played time (only valid for unfinished list)
         try:
             self.WINDOW.setProperty( "LatestMovie.%d.PlayedTime" % ( count + 1, ), fields[ 27 ] )
         except:
             self.WINDOW.clearProperty( "LatestMovie.%d.PlayedTime" % ( count + 1, ) )
         # set path
         self.WINDOW.setProperty( "LatestMovie.%d.Path" % ( count + 1, ), fields[ 24 ] + fields[ 23 ] )
         # set cached thumb name
         cache_name = xbmc.getCacheThumbName( fields[ 24 ] + fields[ 23 ] )
         # set fanart
         self.WINDOW.setProperty( "LatestMovie.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", cache_name, ) )
         # set thumbnail
         self.WINDOW.setProperty( "LatestMovie.%d.Thumb" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( cache_name[ 0 ], cache_name, ) )
Exemple #34
0
    def _get_tags(self):
        # get track tags
        artist = self.getMusicInfoTag().getArtist().decode("utf-8")
        album = self.getMusicInfoTag().getAlbum().decode("utf-8")
        title = self.getMusicInfoTag().getTitle().decode("utf-8")
        duration = str(self.getMusicInfoTag().getDuration())
        # get duration from xbmc.Player if the MusicInfoTag duration is invalid
        if int(duration) <= 0:
            duration = str(int(self.getTotalTime()))
        track = str(self.getMusicInfoTag().getTrack())
        path = self.getPlayingFile().decode("utf-8")
        thumb = xbmc.getCacheThumbName(path)
        #log('artist: ' + artist)
        #log('title: ' + title)
        #log('album: ' + album)
        #log('track: ' + str(track))
        #log('duration: ' + str(duration))
        #log('path: ' + path)
        #log('local path: ' + user)
        #log('thumb: ' + thumb)

        #log('cover art: ' + str(xbmc.getInfoLabel('MusicPlayer.Cover')))
        #log('thumb art: ' + str(xbmc.getInfoLabel('Player.Art(thumb)')))
        #log('fan art: ' + str(xbmc.getInfoLabel('MusicPlayer.Property(Fanart_Image)')))

        return [artist, title]
def blur(input_img, radius=25):
    if not input_img:
        return {}
    if not xbmcvfs.exists(IMAGE_PATH):
        xbmcvfs.mkdir(IMAGE_PATH)
    input_img = utils.translate_path(urllib.unquote(input_img.encode("utf-8")))
    input_img = input_img.replace("image://", "").rstrip("/")
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = "%s-radius_%i.png" % (cachedthumb, radius)
    targetfile = os.path.join(IMAGE_PATH, filename)
    vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
    cache_file = os.path.join("special://profile/Thumbnails", cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if xbmcvfs.exists(targetfile):
        img = PIL.Image.open(targetfile)
        return {"ImageFilter": targetfile,
                "ImageColor": get_colors(img)}
    try:
        if xbmcvfs.exists(cache_file):
            utils.log("image already in xbmc cache: " + cache_file)
            img = PIL.Image.open(utils.translate_path(cache_file))
        elif xbmcvfs.exists(vid_cache_file):
            utils.log("image already in xbmc video cache: " + vid_cache_file)
            img = PIL.Image.open(utils.translate_path(vid_cache_file))
        else:
            xbmcvfs.copy(input_img, targetfile)
            img = PIL.Image.open(targetfile)
        img.thumbnail((200, 200), PIL.Image.ANTIALIAS)
        imgfilter = MyGaussianBlur(radius=radius)
        img = img.convert('RGB').filter(imgfilter)
        img.save(targetfile)
    except Exception:
        utils.log("Could not get image for %s" % input_img)
        return {}
    return {"ImageFilter": targetfile,
            "ImageColor": get_colors(img)}
Exemple #36
0
 def _fetch_tvshow_info( self ):
     # sql statement
     if ( self.RECENT ):
         # recently added
         sql_episodes = "select * from episodeview order by idepisode desc limit %d" % ( self.LIMIT, )
     else:
         # tv shows not finished
         sql_episodes = "select episodeview.*, bookmark.timeInSeconds from episodeview join bookmark on (episodeview.idFile = bookmark.idFile) order by episodeview.strTitle limit %d" % ( self.LIMIT, )
     # query the database
     episodes_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_episodes ), )
     # separate the records
     episodes = re.findall( "<record>(.+?)</record>", episodes_xml, re.DOTALL )
     # enumerate thru our records and set our properties
     for count, episode in enumerate( episodes ):
         # separate individual fields
         fields = re.findall( "<field>(.*?)</field>", episode, re.DOTALL )
         # set show title
         self.WINDOW.setProperty( "LatestEpisode.%d.ShowTitle" % ( count + 1, ), fields[ 27 ] )
         # set episode title
         self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeTitle" % ( count + 1, ), fields[ 1 ] )
         # set season/episode
         self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeNo" % ( count + 1, ), "s%02de%02d" % ( int( fields[ 13 ] ), int( fields[ 14 ] ), ) )
         # set played time (only valid for unfinished list)
         try:
             self.WINDOW.setProperty( "LatestEpisode.%d.PlayedTime" % ( count + 1, ), fields[ 31 ] )
         except:
             self.WINDOW.clearProperty( "LatestEpisode.%d.PlayedTime" % ( count + 1, ) )
         # set path
         self.WINDOW.setProperty( "LatestEpisode.%d.Path" % ( count + 1, ), fields[ 24 ] + fields[ 23 ] )
         # set cached thumb name
         cache_name = xbmc.getCacheThumbName( fields[ 24 ] + fields[ 23 ] )
         # set fanart
         self.WINDOW.setProperty( "LatestEpisode.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", cache_name, ) )
         # set thumbnail
         self.WINDOW.setProperty( "LatestEpisode.%d.Thumb" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( cache_name[ 0 ], cache_name, ) )
 def _show_slide(self, exiting=False):
     myslide = self.slide_playlist[self.image_count]
     self.slide_type = "still"
     if (re.search("__question__", myslide)):
         self.slide_type = "question"
         myslide = myslide.replace("__question__", "")
     elif (re.search("__answer__", myslide)):
         self.slide_type = "answer"
         myslide = myslide.replace("__answer__", "")
     elif (re.search("__clue__", myslide)):
         self.slide_type = "clue"
         myslide = myslide.replace("__clue__", "")
     elif (re.search("__still__", myslide)):
         self.slide_type = "still"
         myslide = myslide.replace("__still__", "")
     utils.log(
         "Slide #%s Type %s - %s" %
         (self.image_count, self.slide_type, myslide), xbmc.LOGNOTICE)
     xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty(
         "Slide", myslide)
     # add id to watched file TODO: maybe don't add if not user preference
     self.watched.append(
         xbmc.getCacheThumbName(self.slide_playlist[self.image_count]))
     # start slide timer
     self._get_slide_timer(self.slide_type, exiting)
Exemple #38
0
 def _play_video(self):
     # Youtube client
     client = YoutubeClient()
     # construct the video url with session id and get video details
     url, g_title, g_director, g_genre, g_rating, g_runtime, g_count, g_date, g_thumbnail, g_plotoutline, video_id = client.construct_video_url(
         self.args.video_url, (
             0,
             6,
             18,
         )[int(xbmcplugin.getSetting("quality"))])
     # close the dialog
     pDialog.close()
     if (not pDialog.iscanceled()):
         # get cached thumbnail, no need to redownload
         g_thumbnail = xbmc.getCacheThumbName(sys.argv[0] + sys.argv[2])
         g_thumbnail = os.path.join(xbmc.translatePath("p:\\Thumbnails"),
                                    "Video", g_thumbnail[0], g_thumbnail)
         # construct our listitem
         listitem = xbmcgui.ListItem(g_title, thumbnailImage=g_thumbnail)
         # set the key information
         listitem.setInfo(
             "video", {
                 "Title": g_title,
                 "Plotoutline": g_plotoutline,
                 "Plot": g_plotoutline,
                 "Director": g_director,
                 "Genre": g_genre,
                 "Rating": g_rating,
                 "Date": g_date
             })
         # set special property
         listitem.setProperty("isVideo", "1")
         listitem.setProperty("RecommendLink", sys.argv[0] + sys.argv[2])
         # Play video with the proper core
         xbmc.Player(self.player_core).play(url, listitem)
	def startPlayBack(self):
		print "[LFM PLG(PM)] onPlayBackStarted started"
		if xbmc.Player().isPlayingAudio() == True:
			currentlyPlayingTitle = xbmc.Player().getMusicInfoTag().getTitle()
			print "[LFM PLG(PM)] " + currentlyPlayingTitle + " started playing"
			currentlyPlayingArtist = xbmc.Player().getMusicInfoTag().getArtist()
			self.countFoundTracks = 0
			if (self.firstRun == 1):
				self.firstRun = 0
				#print "firstRun - clearing playlist"
				album = xbmc.Player().getMusicInfoTag().getAlbum()
				cache_name = xbmc.getCacheThumbName(os.path.dirname(xbmc.Player().getMusicInfoTag().getURL()))
				print "[LFM PLG(PM)] Playing file: %s" % xbmc.Player().getMusicInfoTag().getURL()
				thumb = "special://profile/Thumbnails/Music/%s/%s" % ( cache_name[:1], cache_name, )
				duration = xbmc.Player().getMusicInfoTag().getDuration()
				fanart = ""
				listitem = self.getListItem(currentlyPlayingTitle,currentlyPlayingArtist,album,thumb,fanart,duration)
				xbmc.PlayList(0).clear()
				#xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Playlist.Clear", "params": { "playlistid": 0 }, "id": 1}')
				xbmc.executebuiltin('XBMC.ActivateWindow(10500)')
				xbmc.PlayList(0).add(url= xbmc.Player().getMusicInfoTag().getURL(), listitem = listitem)
				#trackPath = xbmc.Player().getMusicInfoTag().getURL()
				#xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Playlist.Add", "params": { "item": {"file": "%s"}, "playlistid": 0 }, "id": 1}' % trackPath)
				self.addedTracks += [xbmc.Player().getMusicInfoTag().getURL()]
			#print "Start looking for similar tracks"
			self.fetch_similarTracks(currentlyPlayingTitle,currentlyPlayingArtist)
Exemple #40
0
    def FindBug(self, chtype, chname):
        self.log("FindBug, chname = " + chname)
        try:
            setImage = ''
            BugFLE = xbmc.translatePath(
                os.path.join(LOGO_LOC, (chname + '.png')))
            cachedthumb = xbmc.getCacheThumbName(BugFLE)
            cachefile = xbmc.translatePath(
                os.path.join(ART_LOC, cachedthumb[0],
                             cachedthumb[:-4] + ".png")).replace("\\", "/")
            DefaultBug = self.getDefaultBug(chname)

            # no channel bug for livetv/internettv
            if chtype in [8, 9]:
                return 'NA.png'
            else:
                if REAL_SETTINGS.getSetting('UNAlter_ChanBug') == 'true':
                    if FileAccess.exists(BugFLE) == False:
                        BugFLE = DefaultBug
                    return BugFLE
                else:
                    if FileAccess.exists(cachefile) == True:
                        return cachefile
                    elif FileAccess.exists(BugFLE) == False:
                        return DefaultBug
                    return self.ConvertBug(BugFLE, cachefile)
        except Exception, e:
            self.log("FindBug, Failed" + str(e), xbmc.LOGERROR)
            return 'NA.png'
Exemple #41
0
def get_thumbnail(thumbnail_url, fanart=0, default='DefaultTouTv.png'):
    global badthumbs, STRBADTHUMBS
    default = (default, "")[fanart]
    if thumbnail_url and thumbnail_url not in STRBADTHUMBS:
        try:
            filename = xbmc.getCacheThumbName(thumbnail_url)
            if fanart:
                filename = filename.replace(".tbn",
                                            os.path.splitext(thumbnail_url)[1])
                basedir = os.path.dirname(BASE_CACHE_PATH)
            else:
                basedir = BASE_CACHE_PATH
            filepath = os.path.join(BASE_CACHE_PATH, filename[0], filename)

            if not os.path.exists(filepath):
                if not os.path.exists(os.path.dirname(filepath)):
                    os.makedirs(os.path.dirname(filepath))
                fp, h = urllib.urlretrieve(thumbnail_url, filepath)
                if h["Content-Type"] == "text/html":
                    print "bad thumb: %r" % thumbnail_url
                    print fp, str(h).replace("\r", "")
                    try:
                        os.remove(fp)
                    except:
                        pass
                    filepath = ""

                    STRBADTHUMBS += thumbnail_url + "\n"
                    badthumbs.write(thumbnail_url + "\n")
            thumbnail_url = filepath
        except:
            print_exc()
    elif thumbnail_url and thumbnail_url in STRBADTHUMBS:
        thumbnail_url = ""
    return thumbnail_url or default
	def searchGames( self ):
		log( '|==================================|' )
		log( 'searchGames().start' )
		
		listItems = []
		self.getControl( 191 ).setLabel( '[B]Games[/B]' )
		gamesSQL = 'SELECT xbeDescription, strFileName FROM files WHERE strFileName LIKE "F:\GAMES%" AND xbeDescription LIKE "%' + self.SEARCH_STRING + '%"' 
		log( 'searchGames().sql = ' + gamesSQL )
		gamesXML = xbmc.executehttpapi( "QueryProgramDatabase(%s)" % quote_plus( gamesSQL ), )
		games = re.findall( "<record>(.+?)</record>", gamesXML, re.DOTALL )
		results = len( games )
		
		log( 'searchGames().results: ' + str( results ) )

		for count, game in enumerate( games ):
			fields = re.findall( "<field>(.*?)</field>", game, re.DOTALL )
			thumb_cache = xbmc.getCacheThumbName( fields[1] )
			thumb = "special://profile/Thumbnails/Programs/%s/%s" % ( thumb_cache[ 0 ], thumb_cache, )			
			listItem = xbmcgui.ListItem( fields[0], fields[0], thumb, thumb )
			listItem.setProperty( 'path', fields[1] )
			listItem.setProperty( 'content', 'game' )
			listItems.append( listItem )
		
		if results > 0:
			log( 'searchGames().success' )
			self.getControl( 201 ).addItems( listItems )
			self.getControl( 200 ).setLabel( str( results ) )
			self.getControl( 209 ).setVisible( True )
			self.CONTENT_FOUND = 'true'
		log( 'searchGames().end' )
Exemple #43
0
 def _fetch_music_info( self ):
     # sql statement
     if ( self.RANDOM_ORDER ):
         sql_music = "select * from albumview order by RANDOM() limit %d" % ( self.LIMIT, )
     else:
         sql_music = "select * from albumview order by idAlbum desc limit %d" % ( self.LIMIT, )
     # query the database for recently added albums
     music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), )
     # separate the records
     items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL )
     # enumerate thru our records and set our properties
     for count, item in enumerate( items ):
         # separate individual fields
         fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL )
         #print item
         # set properties
         self.WINDOW.setProperty( "LatestSong.%d.Genre" % ( count + 1, ), fields[ 7 ] )
         self.WINDOW.setProperty( "LatestSong.%d.Year" % ( count + 1, ), fields[ 8 ] )
         self.WINDOW.setProperty( "LatestSong.%d.Artist" % ( count + 1, ), fields[ 6 ] )
         self.WINDOW.setProperty( "LatestSong.%d.Album" % ( count + 1, ), fields[ 1 ] )
         self.WINDOW.setProperty( "LatestSong.%d.Review" % ( count + 1, ), fields[ 14 ] )
         # Album Path  (ID)
         path = 'XBMC.RunScript(' + CWD + 'extras.py,albumid=' + fields[ 0 ] + ')'
         self.WINDOW.setProperty( "LatestSong.%d.Path" % ( count + 1, ), path )
         # get cache name of path to use for fanart
         cache_name = xbmc.getCacheThumbName( fields[ 6 ] )
         self.WINDOW.setProperty( "LatestSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) )
         self.WINDOW.setProperty( "LatestSong.%d.Thumb" % ( count + 1, ), fields[ 9 ] )
Exemple #44
0
def get_clean_image(image):
    '''
    helper to strip all kodi tags/formatting of an image path/url
    Pass in either unicode or str; returns unicode
    '''
    if not image:
        return ""
    if not isinstance(image, str):
        image = image.encode('utf-8')
    if b"music@" in image:
        # fix for embedded images
        thumbcache = xbmc.getCacheThumbName(image)
        thumbcache = thumbcache.replace(b".tbn", b".jpg")
        thumbcache = b"special://thumbnails/%s/%s" % (thumbcache[0],
                                                      thumbcache)
        if not xbmcvfs.exists(thumbcache):
            xbmcvfs.copy(image, thumbcache)
        image = thumbcache
    if image and b"image://" in image:
        image = image.replace(b"image://", b"")
        image = utils.unquote(image)
        if image.endswith("/"):
            image = image[:-1]
        return image
    else:
        return image.decode('utf-8')
Exemple #45
0
def Filter_Fakelight(filterimage, pixels):
    md5 = hashlib.md5(filterimage).hexdigest()
    filename = md5 + "fakelight" + str(pixels) + ".png"
    targetfile = os.path.join(ADDON_DATA_PATH, filename)
    cachedthumb = xbmc.getCacheThumbName(filterimage)
    xbmc_vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
    xbmc_cache_file = os.path.join("special://profile/Thumbnails/", cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if filterimage == "":
        return ""
    if not xbmcvfs.exists(targetfile):
        img = None
        for i in range(1, 4):
            try:
                if xbmcvfs.exists(xbmc_cache_file):
                    
                    img = Image.open(xbmc.translatePath(xbmc_cache_file))
                    break
                elif xbmcvfs.exists(xbmc_vid_cache_file):
                    img = Image.open(xbmc.translatePath(xbmc_vid_cache_file))
                    break
                else:
                    filterimage = urllib.unquote(filterimage.replace("image://", "")).decode('utf8')
                    if filterimage.endswith("/"):
                        filterimage = filterimage[:-1]
                    xbmcvfs.copy(filterimage, targetfile)
                    img = Image.open(targetfile)
                    break
            except:
                xbmc.sleep(300)
        if not img:
            return ""
        img = fake_light(img,pixels)
        img.save(targetfile)
    return targetfile
 def _next_slide( self, slide=1, final_slide=False ):
     # cancel timer if it's running
     if self.slide_timer is not None:
         self.slide_timer.cancel()
     # increment/decrement count
     self.image_count += slide
     # check for invalid count, TODO: make sure you don't want to reset timer
     # check to see if playlist has come to an end
     if not xbmc.Player().isPlayingAudio() and int(self.settings[ "trivia_music" ]) > 0:
             #build_music_playlist()
             xbmc.Player().play( self.music_playlist )
     else:
         pass
     if self.image_count < 0:
         self.image_count = 0
     # if no more slides, exit
     if self.image_count > len( self.slide_playlist ) -1:
         self._exit_trivia()
     else:     
         # set the property the image control uses
         xbmcgui.Window( xbmcgui.getCurrentWindowId() ).setProperty( "Slide", self.slide_playlist[ self.image_count ] )
         # add id to watched file TODO: maybe don't add if not user preference
         self.watched += [ xbmc.getCacheThumbName( self.slide_playlist[ self.image_count ] ) ]
         # start slide timer
         self._get_slide_timer()
Exemple #47
0
def get_file(url):
	clean_url = translate_path(urllib.unquote(url)).replace('image://', '')
	clean_url = clean_url.rstrip('/')
	cached_thumb = xbmc.getCacheThumbName(clean_url)
	vid_cache_file = os.path.join('special://profile/Thumbnails/Video', cached_thumb[0], cached_thumb)
	cache_file_jpg = os.path.join('special://profile/Thumbnails/', cached_thumb[0], cached_thumb[:-4] + '.jpg').replace('\\', '/')
	cache_file_png = cache_file_jpg[:-4] + '.png'
	if xbmcvfs.exists(cache_file_jpg):
		log('cache_file_jpg Image: ' + url + '-->' + cache_file_jpg)
		return translate_path(cache_file_jpg)
	elif xbmcvfs.exists(cache_file_png):
		log('cache_file_png Image: ' + url + '-->' + cache_file_png)
		return cache_file_png
	elif xbmcvfs.exists(vid_cache_file):
		log('vid_cache_file Image: ' + url + '-->' + vid_cache_file)
		return vid_cache_file
	try:
		r = requests.get(clean_url, stream=True)
		if r.status_code != 200:
			return ''
		data = r.content
		log('image downloaded: ' + clean_url)
	except Exception as e:
		log('image download failed: ' + clean_url)
		return ''
	if not data:
		return ''
	image = cache_file_png if url.endswith('.png') else cache_file_jpg
	try:
		with open(translate_path(image), 'wb') as f:
			f.write(data)
		return translate_path(image)
	except Exception as e:
		log('failed to save image ' + url)
		return ''
Exemple #48
0
def _shuffle_slides(tmp_slides, watched):
    utils.log("Sorting Watched/Unwatched and Shuffing Slides ", xbmc.LOGNOTICE)
    slide_playlist = []
    # randomize the groups and create our play list
    count = 0
    while count < 6:
        shuffle(tmp_slides, random)
        count += 1
    # now create our final playlist
    # loop thru slide groups and skip already watched groups
    for slides in tmp_slides:
        # has this group been watched
        if (not slide_settings["trivia_unwatched_only"] or
            (slides[0] and xbmc.getCacheThumbName(slides[0]) not in watched) or
            (slides[1] and xbmc.getCacheThumbName(slides[1]) not in watched) or
            (slides[2] and xbmc.getCacheThumbName(slides[2]) not in watched)):
            # loop thru slide group only include non blank slides
            for slide in slides:
                # only add if non blank
                if (slide):
                    # add slide
                    slide_playlist += [slide]
            utils.log("-------- Unwatched --------     included - %s, %s, %s" %
                      (
                          os.path.basename(slides[0]),
                          os.path.basename(slides[1]),
                          os.path.basename(slides[2]),
                      ))

        else:
            utils.log("-------- Watched --------     skipped - %s, %s, %s" % (
                os.path.basename(slides[0]),
                os.path.basename(slides[1]),
                os.path.basename(slides[2]),
            ))

    utils.log("-----------------------------")
    utils.log("Total slides selected: %d" % len(slide_playlist),
              xbmc.LOGNOTICE)

    # reset watched automatically if no slides are left
    if (len(slide_playlist) == 0 and slide_settings["trivia_unwatched_only"]
            and len(watched) > 0):
        watched = _reset_watched()
        #attempt to load our playlist again
        _shuffle_slides(tmp_slides, watched)
    return slide_playlist
Exemple #49
0
 def get_cached_thumb( self, path1, path2, SPLIT=False ):
     # get the locally cached thumb
     filename = xbmc.getCacheThumbName( path1 )
     if SPLIT:
         thumb = os.path.join( filename[ 0 ], filename )
     else:
         thumb = filename
     return os.path.join( path2, thumb )
Exemple #50
0
 def get_fanarts( self, strLabel ):
     fanart = xbmc.getCacheThumbName( strLabel )
     actor_fanart  = self.VIDEO_THUMB_PATH + "Fanart/" + fanart
     artist_fanart = self.ARTIST_THUMB_PATH.replace( "Artists", "Fanart" ) + fanart
     if self.library_type == "artist":
         return  artist_fanart, actor_fanart
     else:
         return  actor_fanart, artist_fanart
Exemple #51
0
def kodi_get_cached_image_FN(image_FN):
    FileNameFactory.create
    THUMBS_CACHE_PATH_FN = FileNameFactory.create(
        'special://profile/Thumbnails')
    # >> This function return the cache file base name
    base_name = xbmc.getCacheThumbName(image_FN.getOriginalPath())
    cache_file_path = THUMBS_CACHE_PATH_FN.pjoin(base_name[0]).pjoin(base_name)

    return cache_file_path
def kodi_get_cached_image(image_path):
    THUMBS_CACHE_PATH = os.path.join(xbmc.translatePath('special://profile/' ), 'Thumbnails')

    # --- Get the Kodi cached image ---
    # This function return the cache file base name
    base_name = xbmc.getCacheThumbName(image_path)
    cache_file_path = os.path.join(THUMBS_CACHE_PATH, base_name[0], base_name)

    return cache_file_path
Exemple #53
0
def download(src, dst):
    tmpname = xbmc.translatePath('special://temp/%s' %
                                 xbmc.getCacheThumbName(src))

    if os.path.exists(tmpname):
        os.remove(tmpname)

    urllib.urlretrieve(src, filename=tmpname)
    os.rename(tmpname, dst)
Exemple #54
0
 def cache_thumb_name(thumb):
     """
     Находит кеш рисунка
     :param thumb:
     :return:
     """
     thumb_cached = xbmc.getCacheThumbName(thumb)
     thumb_cached = thumb_cached.replace('tbn', 'png')
     return os.path.join(os.path.join(xbmc.translatePath("special://thumbnails"), thumb_cached[0], thumb_cached))
Exemple #55
0
def Filter_Image(filterimage, radius):
    try:
        if not xbmcvfs.exists(ADDON_DATA_PATH):
            xbmcvfs.mkdir(ADDON_DATA_PATH)
        md5 = hashlib.md5(filterimage).hexdigest()
        filename = md5 + str(radius) + ".png"
        targetfile = os.path.join(ADDON_DATA_PATH, filename)
        cachedthumb = xbmc.getCacheThumbName(filterimage)
        xbmc_vid_cache_file = os.path.join(
            "special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
        xbmc_cache_file = os.path.join("special://profile/Thumbnails/",
                                       cachedthumb[0],
                                       cachedthumb[:-4] + ".jpg")
        if filterimage == "":
            return "", ""
        if not xbmcvfs.exists(targetfile):
            img = None
            for i in range(1, 4):
                try:
                    if xbmcvfs.exists(xbmc_cache_file):
                        log("image already in xbmc cache: " + xbmc_cache_file)
                        img = Image.open(xbmc.translatePath(xbmc_cache_file))
                        break
                    elif xbmcvfs.exists(xbmc_vid_cache_file):
                        log("image already in xbmc video cache: " +
                            xbmc_vid_cache_file)
                        img = Image.open(
                            xbmc.translatePath(xbmc_vid_cache_file))
                        break
                    else:
                        filterimage = urllib.unquote(
                            filterimage.replace("image://", "")).decode('utf8')
                        if filterimage.endswith("/"):
                            filterimage = filterimage[:-1]
                        log("copy image from source: " + filterimage)
                        xbmcvfs.copy(filterimage, targetfile)
                        img = Image.open(targetfile)
                        break
                except:
                    log("Could not get image for %s (try %i)" %
                        (filterimage, i))
                    xbmc.sleep(500)
            if not img:
                return "", ""
            img.thumbnail((200, 200), Image.ANTIALIAS)
            img = img.convert('RGB')
            imgfilter = MyGaussianBlur(radius=radius)
            img = img.filter(imgfilter)
            img.save(targetfile)
        else:
            log("blurred img already created: " + targetfile)
            img = Image.open(targetfile)
        imagecolor = Get_Colors(img)
        return targetfile, imagecolor
    except:
        return "", ""
Exemple #56
0
 def get_cached_thumb( self, path1, path2, SPLIT=False, SET_EXT=False ):
     # get the locally cached thumb
     filename = xbmc.getCacheThumbName( path1 )
     if SPLIT:
         thumb = os.path.join( filename[ 0 ], filename )
     else:
         thumb = filename
     if SET_EXT:
         thumb = os.path.splitext( thumb )[ 0 ] + os.path.splitext( path1 )[ 1 ]
     return os.path.join( path2, thumb )
Exemple #57
0
 def _shuffle_trailers( self ):
     # randomize the groups and create our play list
     shuffle( self.tmp_trailers )
     # reset counter
     count = 0
     # now create our final playlist
     for trailer in self.tmp_trailers:
         # user preference to skip watch trailers
         if ( self.settings[ "trailer_newest_only" ] and xbmc.getCacheThumbName( trailer ) in self.watched ):
             continue
         # add id to watched file TODO: maybe don't add if not user preference
         self.watched += [ xbmc.getCacheThumbName( trailer ) ]
         # add trailer to our final list
         self.trailers += [ self._set_trailer_info( trailer ) ]
         # increment counter
         count += 1
         # if we have enough exit
         if ( count == self.settings[ "trailer_count" ] ):
             break
Exemple #58
0
def filter_image(input_img, radius=25):
    if not xbmcvfs.exists(os.path.join(Utils.IMAGES_DATA_PATH)):
        xbmcvfs.mkdir(os.path.join(Utils.IMAGES_DATA_PATH))
    input_img = xbmc.translatePath(urllib.unquote(
        input_img.encode('utf-8'))).replace('image://', '')
    if input_img.endswith('/'):
        input_img = input_img[:-1]
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = '%s-radius_%i.png' % (cachedthumb, radius)
    targetfile = os.path.join(Utils.IMAGES_DATA_PATH, filename)
    xbmc_vid_cache_file = os.path.join('special://profile/Thumbnails/Video',
                                       cachedthumb[0], cachedthumb)
    xbmc_cache_file = os.path.join('special://profile/Thumbnails',
                                   cachedthumb[0], cachedthumb[:-4] + '.jpg')
    if input_img == '':
        return '', ''
    if not xbmcvfs.exists(targetfile):
        img = None
        for i in range(1, 4):
            try:
                if xbmcvfs.exists(xbmc_cache_file):
                    Utils.log('image already in Kodi cache: ' +
                              xbmc_cache_file)
                    img = Image.open(xbmc.translatePath(xbmc_cache_file))
                    break
                elif xbmcvfs.exists(xbmc_vid_cache_file):
                    Utils.log('image already in Kodi video cache: ' +
                              xbmc_vid_cache_file)
                    img = Image.open(xbmc.translatePath(xbmc_vid_cache_file))
                    break
                else:
                    xbmcvfs.copy(unicode(input_img, 'utf-8', errors='ignore'),
                                 targetfile)
                    img = Image.open(targetfile)
                    break
            except:
                Utils.log('Could not get image for %s (try %i)' %
                          (input_img, i))
                xbmc.sleep(200)
        if not img:
            return '', ''
        try:
            img.thumbnail((200, 200), Image.ANTIALIAS)
            img = img.convert('RGB')
            imgfilter = MyGaussianBlur(radius=radius)
            img = img.filter(imgfilter)
            img.save(targetfile)
        except:
            Utils.log('PIL problem probably....')
            return '', ''
    else:
        Utils.log('blurred img already created: ' + targetfile)
        img = Image.open(targetfile)
    imagecolor = get_colors(img)
    return targetfile, imagecolor
Exemple #59
0
def filter_image(input_img, radius):
    if not xbmcvfs.exists(ADDON_DATA_PATH_IMAGES):
        xbmcvfs.mkdir(ADDON_DATA_PATH_IMAGES)
    input_img = xbmc.translatePath(urllib.unquote(
        input_img.encode("utf-8"))).replace("image://", "")
    if input_img.endswith("/"):
        input_img = input_img[:-1]
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = "%s-radius_%i.png" % (cachedthumb, radius)
    targetfile = os.path.join(ADDON_DATA_PATH_IMAGES, filename)
    xbmc_vid_cache_file = os.path.join("special://profile/Thumbnails/Video",
                                       cachedthumb[0], cachedthumb)
    xbmc_cache_file = os.path.join("special://profile/Thumbnails",
                                   cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if input_img == "":
        return "", ""
    if not xbmcvfs.exists(targetfile):
        img = None
        for i in range(1, 4):
            try:
                if xbmcvfs.exists(xbmc_cache_file):
                    log("image already in xbmc cache: " + xbmc_cache_file)
                    img = PIL.Image.open(xbmc.translatePath(xbmc_cache_file))
                    break
                elif xbmcvfs.exists(xbmc_vid_cache_file):
                    log("image already in xbmc video cache: " +
                        xbmc_vid_cache_file)
                    img = PIL.Image.open(
                        xbmc.translatePath(xbmc_vid_cache_file))
                    break
                else:
                    xbmcvfs.copy(unicode(input_img, 'utf-8', errors='ignore'),
                                 targetfile)
                    img = PIL.Image.open(targetfile)
                    break
            except:
                log("Could not get image for %s (try %i)" % (input_img, i))
                xbmc.sleep(500)
        if not img:
            return "", ""
        try:
            img.thumbnail((200, 200), PIL.Image.ANTIALIAS)
            img = img.convert('RGB')
            imgfilter = MyGaussianBlur(radius=radius)
            img = img.filter(imgfilter)
            img.save(targetfile)
        except:
            log("PIL problem probably....")
            return "", ""
    else:
        log("blurred img already created: " + targetfile)
        img = PIL.Image.open(targetfile)
    imagecolor = get_colors(img)
    return targetfile, imagecolor