Example #1
0
def build_music_playlist():
    log( "Building Music Playlist", xbmc.LOGNOTICE )
    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList( xbmc.PLAYLIST_MUSIC )
    track_location = []
    # check to see if playlist or music file is selected
    if trivia_settings[ "trivia_music" ] == 1:
        if trivia_settings[ "trivia_music_file" ].endswith(".m3u"):
            log( "Music Playlist: %s" % trivia_settings[ "trivia_music_file" ] )
            playlist_file = xbmcvfs.File( trivia_settings[ "trivia_music_file" ], 'rb')
            saved_playlist = playlist_file.read().splitlines()
            playlist_file.close()
            log( "Finished Reading Music Playlist" )
            track_info, track_location = parse_playlist( saved_playlist, xbmc.getSupportedMedia('music') )
        elif os.path.splitext( trivia_settings[ "trivia_music_file" ] )[1] in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append( trivia_settings[ "trivia_music_file" ] )
    # otherwise
    else:
        if trivia_settings[ "trivia_music_folder" ]:
            # search given folder and subfolders for files
            track_location = dirEntries( trivia_settings[ "trivia_music_folder" ], "music", "TRUE" )
    # shuffle playlist
    shuffle( track_location )
    for track in track_location:
        music_playlist.add( track,  )
Example #2
0
 def _get_items(self, paths, media_type):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch videos/pictures recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi("GetDirectory(%s)" %
                                       (path, )).split("\n")
         # enumerate through our entries list and check for valid media type
         for entry in entries:
             # remove <li> from item
             entry = entry.replace("<li>", "")
             # if folder add to our folder list to recursively fetch videos/pictures
             if (entry.endswith("/") or entry.endswith("\\")):
                 folders += [entry]
             # is this a valid video/picture file
             elif (entry and ((media_type.startswith("video")
                               and os.path.splitext(entry)[1]
                               in xbmc.getSupportedMedia("video")) or
                              (media_type.endswith("picture")
                               and os.path.splitext(entry)[1]
                               in xbmc.getSupportedMedia("picture")))):
                 # add our entry
                 self.tmp_paths += [entry]
     # if there are folders call again (we want recursive)
     if (folders):
         self._get_items(folders, media_type)
def build_music_playlist():
    xbmc.log( "%s - Building Music Playlist" % log_message, level=xbmc.LOGNOTICE)
    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList( xbmc.PLAYLIST_MUSIC )
    track_location = []
    # check to see if playlist or music file is selected
    if int( _S_( "trivia_music" ) ) == 1:
        if _S_( "trivia_music_file" ).endswith(".m3u"):
            xbmc.log( "%s - Music Playlist: %s" % ( log_message, _S_( "trivia_music_file" ) ), level=xbmc.LOGDEBUG)
            playlist_file = open( _S_( "trivia_music_file" ), 'rb')
            saved_playlist = playlist_file.readlines()
            xbmc.log( "%s - Finished Reading Music Playlist" % log_message, level=xbmc.LOGDEBUG)
            track_info, track_location = parse_playlist( saved_playlist, xbmc.getSupportedMedia('music') )
        elif os.path.splitext( _S_( "trivia_music_file" ) )[1] in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append( _S_( "trivia_music_file" ) )
    # otherwise
    else:
        if _S_( "trivia_music_folder" ):
            # search given folder and subfolders for files
            track_location = dirEntries( _S_( "trivia_music_folder" ), "music", "TRUE" )
    # shuffle playlist
    count = 0
    while count <6:
        shuffle( track_location, random )
        count+=1
    for track in track_location:
        music_playlist.add( track,  )
def _validateExtension(ext,info):
    #use Kodi's supported media to check for valid extension or return default
    if info.get('media_type') == 'video':
        if not ext in xbmc.getSupportedMedia('video'): return 'mp4'
    elif info.get('media_type') == 'audio':
        if not ext in xbmc.getSupportedMedia('music'): return 'mp3'
    elif info.get('media_type') == 'image':
        if not ext in xbmc.getSupportedMedia('picture'): return 'jpg'
    return ext
def _isValidMediaExtension(ext):
    # use Kodi's supported media to check for valid extension
    if (
        ext in xbmc.getSupportedMedia("video")
        or ext in xbmc.getSupportedMedia("music")
        or ext in xbmc.getSupportedMedia("picture")
    ):
        return True
    return False
Example #6
0
def getTypeFromExt(ext):
	ext = ext.lower()
	video = xbmc.getSupportedMedia('video').replace('.','').split('|')
	audio = xbmc.getSupportedMedia('music').replace('.','').split('|')
	image = xbmc.getSupportedMedia('picture').replace('.','').split('|')
	if ext in video:
		return 'videofile'
	elif ext in audio:
		return 'audiofile'
	elif ext in image:
		return 'imagefile'
	return None
def _validateExtension(ext, info):
    # use Kodi's supported media to check for valid extension or return default
    if info.get("media_type") == "video":
        if ext not in xbmc.getSupportedMedia("video"):
            return "mp4"
    elif info.get("media_type") == "audio":
        if ext not in xbmc.getSupportedMedia("music"):
            return "mp3"
    elif info.get("media_type") == "image":
        if ext not in xbmc.getSupportedMedia("picture"):
            return "jpg"
    return ext
Example #8
0
def getURLMediaType(url):
    if url.startswith('http'):
        videoTypes = xbmc.getSupportedMedia('video')
        musicTypes = xbmc.getSupportedMedia('music')
        imageTypes = xbmc.getSupportedMedia('picture')
        ext = url.rsplit('.',1)[-1]
        if ext in videoTypes:
            return 'video'
        elif ext in musicTypes:
            return 'audio'
        elif ext in imageTypes:
            return 'image'
    return protocolMediaType(url)
def getURLMediaType(url):
    if url.startswith("http"):
        videoTypes = xbmc.getSupportedMedia("video")
        musicTypes = xbmc.getSupportedMedia("music")
        imageTypes = xbmc.getSupportedMedia("picture")
        ext = url.rsplit(".", 1)[-1]
        if ext in videoTypes:
            return "video"
        elif ext in musicTypes:
            return "audio"
        elif ext in imageTypes:
            return "image"
    return protocolMediaType(url)
def getURLMediaType(url):
    if url.startswith('http'):
        videoTypes = xbmc.getSupportedMedia('video')
        musicTypes = xbmc.getSupportedMedia('music')
        imageTypes = xbmc.getSupportedMedia('picture')
        ext = url.rsplit('.',1)[-1]
        if ext in videoTypes:
            return 'video'
        elif ext in musicTypes:
            return 'audio'
        elif ext in imageTypes:
            return 'image'
    return protocolMediaType(url)
Example #11
0
def build_music_playlist():
    utils.log("Building Music Playlist", xbmc.LOGNOTICE)
    xbmc.executeJSONRPC(
        '{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    track_location = []
    # check to see if playlist or music file is selected
    if trivia_settings["trivia_music"] == 1:
        if (os.path.splitext(
                trivia_settings["trivia_music_file"])[1]).lower() in (".m3u",
                                                                      ".pls",
                                                                      ".asf",
                                                                      ".ram"):
            utils.log("Music Playlist: %s" %
                      trivia_settings["trivia_music_file"])
            if trivia_settings["trivia_music_file"].endswith(".m3u"):
                track_location = parser.parse_m3u(
                    trivia_settings["trivia_music_file"],
                    xbmc.getSupportedMedia('music'))
            elif trivia_settings["trivia_music_file"].endswith(".pls"):
                track_location = parser.parse_pls(
                    trivia_settings["trivia_music_file"],
                    xbmc.getSupportedMedia('music'))
            elif trivia_settings["trivia_music_file"].endswith(".asf"):
                track_location = parser.parse_asf(
                    trivia_settings["trivia_music_file"],
                    xbmc.getSupportedMedia('music'))
            elif trivia_settings["trivia_music_file"].endswith(".ram"):
                track_location = parser.parse_ram(
                    trivia_settings["trivia_music_file"],
                    xbmc.getSupportedMedia('music'))
        elif (os.path.splitext(
                trivia_settings["trivia_music_file"])[1]).replace(
                    ".", "") in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append(trivia_settings["trivia_music_file"])
    # otherwise
    else:
        if trivia_settings["trivia_music_folder"]:
            # search given folder and subfolders for files
            track_location = absolute_listdir(
                trivia_settings["trivia_music_folder"],
                media_type="music",
                recursive=True)
    # shuffle playlist
    shuffle(track_location)
    for track in track_location:
        music_playlist.add(track, )
def _get_slides( paths, movie_mpaa ):
    # reset folders list
    tmp_slides = []
    folders = []
    # mpaa ratings
    mpaa_ratings = { "G": 0, "PG": 1, "PG-13": 2, "R": 3, "NC-17": 4, "--": 5, "": 6 }
    # enumerate thru paths and fetch slides recursively
    for path in paths:
        # get the directory listing
        entries = dirEntries( path, media_type="files", recursive="FALSE" )
        # sort in case
        entries.sort()
        # get a slides.xml if it exists
        slidesxml_exists, mpaa, question_format, clue_format, answer_format, still_format = _get_slides_xml( path )
        # check if rating is ok
        log( "Movie MPAA: %s" % movie_mpaa )
        log( "Slide MPAA: %s" % mpaa )
        if ( slidesxml_exists and mpaa_ratings.get( movie_mpaa, -1 ) < mpaa_ratings.get( mpaa, -1 ) ):
            log( "Slide Rating above movie rating - skipping whole folder", xbmc.LOGNOTICE )
            continue
        # initialize these to True so we add a new list item to start
        question = clue = answer = still = True
        # enumerate through our entries list and combine question, clue, answer
        for entry in entries:
            # if folder add to our folder list to recursively fetch slides
            if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                folders += [ entry ]
            # sliders.xml was included, so check it
            elif ( slidesxml_exists ):
                # question
                if ( question_format and re.search( question_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( question ):
                        tmp_slides += [ [ "", "", "" ] ]
                        clue = answer = still = False
                    tmp_slides[ -1 ][ 0 ] = "__question__" + entry
                    # clue
                elif ( clue_format and re.search( clue_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( clue ):
                        tmp_slides += [ [ "", "", "" ] ]
                        question = answer = still = False
                    tmp_slides[ -1 ][ 1 ] = "__clue__" + entry
                # answer
                elif ( answer_format and re.search( answer_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( answer ):
                        tmp_slides += [ [ "", "", "" ] ]
                        question = clue = still = False
                    tmp_slides[ -1 ][ 2 ] = "__answer__" + entry
                    # still
                elif ( still_format and re.search( still_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( still ):
                        tmp_slides += [ [ "", "", "" ] ]
                        clue = answer = question = False
                    tmp_slides[ -1 ][ 0 ] = "__still__" + entry
            # add the file as a question TODO: maybe check for valid picture format?
            elif ( entry and os.path.splitext( entry )[ 1 ].lower() in xbmc.getSupportedMedia( "picture" ) ):
                tmp_slides += [ [ "", "", "__still__" + entry ] ] 
    # if there are folders call again (we want recursive)
    if ( folders ):
        tmp_slides.extend( _get_slides( folders, movie_mpaa ) )
    return tmp_slides
Example #13
0
 def get_user_input(self, itype, header, *args):
     """Get user input of type defined by 'itype'."""
     if itype == 'string':
         v = self.__get_from_keyboard(header)
     elif itype == 'directory':
         #v = os.getcwd()
         dialog = xbmcgui.Dialog()
         v = dialog.browse(3, header, 'files')
     elif itype == 'picture':
         mask = xbmc.getSupportedMedia('picture')
         mltp = False
         if len(args):
             mltp = args[0]
         dialog = xbmcgui.Dialog()
         # first testing if multiple selection patch is applied to FileBrowser,
         # otherwise fall back to old method call, but return tuple anyway.
         # required patch: http://trac.xbmc.org/ticket/10894
         # available since git commit dcad8dbd
         try:
             v = dialog.browse(2, header, "pictures", mask, False, False, mltp)
         except TypeError:
             v = dialog.browse(2, header, "pictures", mask)
             v = (v,)
     elif itype == 'select':
         dialog = xbmcgui.Dialog()
         v = dialog.select(header, *args)
     elif itype == 'number':
         v = xbmcgui.Dialog().numeric(0, header)
     else:
         v = None
     
     return v
Example #14
0
 def __init__(self):
     self.active = True
     self.list = []
     self.futurelist=[]
     self.toolkit = XBMCToolkit()
     self.pos = -1
     if not sim:
         self.supportedvideo = xbmc.getSupportedMedia('video').split('|')            
         self.supportedmusic = xbmc.getSupportedMedia('music').split('|')
         self.musicplaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
         self.videoplaylist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
         self.musicplaylist.clear()
         self.videoplaylist.clear()
         self.playlist = self.videoplaylist
         self.playerThread = Thread(target=self.callbackThread, args=())
         self.playerThread.start()
 def _get_items(self, paths, media_type):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch videos/pictures recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi("GetDirectory(%s)" % (path,)).split("\n")
         # enumerate through our entries list and check for valid media type
         for entry in entries:
             # remove <li> from item
             entry = entry.replace("<li>", "")
             # if folder add to our folder list to recursively fetch videos/pictures
             if entry.endswith("/") or entry.endswith("\\"):
                 folders += [entry]
             # is this a valid video/picture file
             elif entry and (
                 (media_type.startswith("video") and os.path.splitext(entry)[1] in xbmc.getSupportedMedia("video"))
                 or (
                     media_type.endswith("picture")
                     and os.path.splitext(entry)[1] in xbmc.getSupportedMedia("picture")
                 )
             ):
                 # add our entry
                 self.tmp_paths += [entry]
     # if there are folders call again (we want recursive)
     if folders:
         self._get_items(folders, media_type)
def absolute_listdir( path, media_type = "files", recursive = False, contains = "" ):
    absolute_files = []
    absolute_folders = []
    path = utils.smart_unicode( path )
    folders, files = xbmcvfs.listdir( path )
    for f in files:
        f = utils.smart_unicode( f )
        if media_type == "files":
            if not contains or ( contains and ( contains in f ) ):
                try:
                    absolute_files.append( os.path.join( path, f ).replace("\\\\","\\") )
                except UnicodeError:
                    utils.log( "Problem with path, skipping" )
                    utils.log( "Path: %s" % repr( path ) )
                    utils.log( "Filename: %s" % repr( path ) )
                except:
                    utils.log( "Problem with path, skipping" )
                    traceback.print_exc()
        else:
            if ( os.path.splitext( f )[ 1 ] ).lower() in ( xbmc.getSupportedMedia( media_type ) ).lower():
                if not contains or ( contains and ( contains in f ) ):
                    absolute_files.append( os.path.join( path, f ).replace("\\\\","\\") )
    if folders:
        absolute_folders = absolute_folder_paths( folders, path )
        if recursive:
            for folder in absolute_folders:
                absolute_files.extend( absolute_listdir( folder, media_type = media_type, recursive = recursive, contains = contains ) )
    return absolute_files
Example #17
0
 def __init__(self, library, path, xbmcif):
     FileSystemEventHandler.__init__(self)
     self.library = library
     self.path = path
     self.xbmcif = xbmcif
     self.supported_media = '|' + py2_decode(
         xbmc.getSupportedMedia(library)) + '|'
def build_music_playlist():
    utils.log( "Building Music Playlist", xbmc.LOGNOTICE )
    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList( xbmc.PLAYLIST_MUSIC )
    track_location = []
    # check to see if playlist or music file is selected
    if trivia_settings[ "trivia_music" ] == 1:
        if ( os.path.splitext( trivia_settings[ "trivia_music_file" ] )[ 1 ] ).lower() in ( "m3u", "pls", "asf", "ram" ):
            utils.log( "Music Playlist: %s" % trivia_settings[ "trivia_music_file" ] )
            if trivia_settings[ "trivia_music_file" ].endswith(".m3u"):
                track_location = parser.parse_m3u( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".pls"):
                track_location = parser.parse_pls( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".asf"):
                track_location = parser.parse_asf( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".ram"):
                track_location = parser.parse_ram( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
        elif os.path.splitext( trivia_settings[ "trivia_music_file" ] )[1] in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append( trivia_settings[ "trivia_music_file" ] )
    # otherwise
    else:
        if trivia_settings[ "trivia_music_folder" ]:
            # search given folder and subfolders for files
            track_location = absolute_listdir( trivia_settings[ "trivia_music_folder" ], media_type = "music", recursive = True )
    # shuffle playlist
    shuffle( track_location )
    for track in track_location:
        music_playlist.add( track,  )
Example #19
0
def absolute_listdir( path, media_type = "files", recursive = False, contains = "" ):
    absolute_files = []
    absolute_folders = []
    path = utils.smart_unicode( path )
    folders, files = xbmcvfs.listdir( path )
    for f in files:
        f = utils.smart_unicode( f )
        if media_type == "files":
            if not contains or ( contains and ( contains in f ) ):
                try:
                    absolute_files.append( os.path.join( path, f ).replace("\\\\","\\") )
                except UnicodeError:
                    utils.log( "Problem with path, skipping" )
                    utils.log( "Path: %s" % repr( path ) )
                    utils.log( "Filename: %s" % repr( path ) )
                except:
                    utils.log( "Problem with path, skipping" )
                    traceback.print_exc()
        else:
            if ( ( os.path.splitext( f )[ 1 ] ).lower() ).replace( ".", "" ) in ( xbmc.getSupportedMedia( media_type ) ).lower():
                if not contains or ( contains and ( contains in f ) ):
                    absolute_files.append( os.path.join( path, f ).replace("\\\\","\\") )
    if folders:
        absolute_folders = absolute_folder_paths( folders, path )
        if recursive:
            for folder in absolute_folders:
                absolute_files.extend( absolute_listdir( folder, media_type = media_type, recursive = recursive, contains = contains ) )
    return absolute_files
Example #20
0
def supported_video_extensions():
    try:
        from xbmc import getSupportedMedia
        supported_video_extensions = getSupportedMedia('video').split('|')
        return [
            i for i in supported_video_extensions if i != '' and i != '.zip'
        ]
    except:
        log_utils.error()
Example #21
0
def get_media_type(path: str) -> str:

    ext = get_file_extension(path)
    if is_musicdb(path) or is_audio_plugin(path) or is_pvr_radio_channel(
            path) or is_playlist(path) or ext and (
                ext + "|") in xbmc.getSupportedMedia("music"):
        return AUDIO

    elif is_videodb(path) or is_video_plugin(path) or is_pvr(path) or ext and (
            ext + "|") in xbmc.getSupportedMedia("video"):
        return VIDEO

    elif ext and (ext + "|") in xbmc.getSupportedMedia("picture"):
        return PICTURE

    else:
        paths, type = get_files_and_type(path, limit=100, no_leaves=True)
        return type
def _get_slides( paths, movie_mpaa ):
    # reset folders list
    tmp_slides = []
    folders = []
    # mpaa ratings
    mpaa_ratings = { "G": 0, "PG": 1, "PG-13": 2, "R": 3, "NC-17": 4, "--": 5, "": 6 }
    # enumerate thru paths and fetch slides recursively
    for path in paths:
        # get the directory listing
        entries = xbmc.executehttpapi( "GetDirectory(%s)" % ( path, ) ).split( "\n" )
        # sort in case
        entries.sort()
        # get a slides.xml if it exists
        slidesxml_exists, mpaa, question_format, clue_format, answer_format = _get_slides_xml( path )
        # check if rating is ok
        xbmc.log( "[script.cinema.experience] - Movie MPAA: %s" % movie_mpaa, level=xbmc.LOGDEBUG )
        xbmc.log( "[script.cinema.experience] - Slide MPAA: %s" % mpaa, level=xbmc.LOGDEBUG )
        if ( slidesxml_exists and mpaa_ratings.get( movie_mpaa, -1 ) < mpaa_ratings.get( mpaa, -1 ) ):
            xbmc.log( "[script.cinema.experience] - Slide Rating above movie rating - skipping whole folder", level=xbmc.LOGNOTICE)
            continue
        # initialize these to True so we add a new list item to start
        question = clue = answer = True
        # enumerate through our entries list and combine question, clue, answer
        for entry in entries:
            # remove <li> from item
            entry = entry.replace( "<li>", "" )
            # if folder add to our folder list to recursively fetch slides
            if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                folders += [ entry.replace( "<li>", "" ) ]
            # sliders.xml was included, so check it
            elif ( slidesxml_exists ):
                # question
                if ( question_format and re.search( question_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( question ):
                        tmp_slides += [ [ "", "", "" ] ]
                        clue = answer = False
                    tmp_slides[ -1 ][ 0 ] = entry
                # clue
                elif ( clue_format and re.search( clue_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( clue ):
                        tmp_slides += [ [ "", "", "" ] ]
                        question = answer = False
                    tmp_slides[ -1 ][ 1 ] = entry
                # answer
                elif ( answer_format and re.search( answer_format, os.path.basename( entry ), re.IGNORECASE ) ):
                    if ( answer ):
                        tmp_slides += [ [ "", "", "" ] ]
                        question = clue = False
                    tmp_slides[ -1 ][ 2 ] = entry
            # add the file as a question TODO: maybe check for valid picture format?
            elif ( entry and os.path.splitext( entry )[ 1 ].lower() in xbmc.getSupportedMedia( "picture" ) ):
                tmp_slides += [ [ "", "", entry ] ]
    # if there are folders call again (we want recursive)
    if ( folders ):
        tmp_slides.extend( _get_slides( folders, movie_mpaa ) )
    return tmp_slides
Example #23
0
def getBrowseDialog( default="", heading="", dlg_type=3, shares="files", mask=xbmc.getSupportedMedia( 'video' ), use_thumbs=False, treat_as_folder=False ):
    """ shows a browse dialog and returns a value
        - 0 : ShowAndGetDirectory
        - 1 : ShowAndGetFile
        - 2 : ShowAndGetImage
        - 3 : ShowAndGetWriteableDirectory
    """
    dialog = xbmcgui.Dialog()
    value  = dialog.browse( dlg_type, heading, shares, mask, use_thumbs, treat_as_folder, default )
    return value
Example #24
0
def showRarVideos( url ):
    VIDEO_EXTENTIONS = xbmc.getSupportedMedia('video').split('|')
    # remove some archive extensions
    VIDEO_EXTENTIONS.remove(".rar")
    VIDEO_EXTENTIONS.remove(".001")
    VIDEO_EXTENTIONS.remove(".url")

    found_video_file = False

    dp = xbmcgui.DialogProgress()
    dp.create("Finding video files in rar. Be Patient!")

    def info_callback(raritem):
        try:
            currently_reading_rar_volume_file = raritem.volume_file.split('/')[-1]
            completed = (raritem.volume+1 * 100) / 15
            dp.update(completed, 'Reading rar data for the following rar file...', currently_reading_rar_volume_file, 'VOLUME #%s' % raritem.volume)
            doLog("%s\n%s\n%s" % (raritem.file_offset, raritem.volume_file.split('/')[-1], raritem.type))
        except:
            pass

    rar_file = rarfile.RarFile( url, crc_check=False, info_callback=info_callback )
    if rar_file.needs_password():
        errorNotice = 'XBMC.Notification("RAR IS PASSWORD PROTECTED!","Cannot handle a password protected archive.", 5000)'
        xbmc.executebuiltin( errorNotice )
        dp.close()
        return False

    for filename in rar_file.namelist():
        file_info = rar_file.getinfo(filename)
        doLog( "\tRAR INFO needs_password: %s - volume: %s - volume_file: %s - compress_type: %s" % (file_info.needs_password(), file_info.volume, file_info.volume_file, file_info.compress_type))

        filename = filename.replace('\\','/')
        dp.update(0, filename)
        doLog( "FILENAME FOUND: %s" % filename )

        # test for an extension otherwise skip
        try:
            file_ext_lower = "." + filename.lower().split('.')[-1]
            doLog( "Checking Extension: %s" % file_ext_lower )
            if file_ext_lower in (".rar",".001"):
                errorNotice = 'XBMC.Notification("Archive within archive detected!","Cannot handle double packed archives.", 2000)'
                xbmc.executebuiltin( errorNotice )
            if file_ext_lower in VIDEO_EXTENTIONS:
                # use the rar volume_file which holds the actual url to where this video file starts in the set.
                # otherwise videos further in the set won't play. SWEET!
                video_url = urllib.quote( file_info.volume_file ).replace("-", "%2d").replace(".", "%2e").replace("/", "%2f")
                video_url = "rar://" + video_url + "/" + filename
                found_video_file = True
                doLog( "addLink( name=%s, url=%s)" % (filename, video_url))
                addLink( name=filename, url=video_url)
        except:
            pass
    dp.close()
    return found_video_file
 def _get_slides( self, paths ):
     # reset folders list
     folders = []
     # mpaa ratings
     mpaa_ratings = { "G": 0, "PG": 1, "PG-13": 2, "R": 3, "NC-17": 4, "--": 5, "": 6 }
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi( "GetDirectory(%s)" % ( path, ) ).split( "\n" )
         # sort in case
         entries.sort()
         # get a slides.xml if it exists
         slidesxml_exists, mpaa, question_format, clue_format, answer_format = self._get_slides_xml( path )
         # check if rating is ok
         if ( slidesxml_exists and mpaa_ratings.get( self.mpaa, -1 ) < mpaa_ratings.get( mpaa, -1 ) ):
             print "skipping whole folder", path
             continue
         # initialize these to True so we add a new list item to start
         question = clue = answer = True
         # enumerate through our entries list and combine question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace( "<li>", "" )
             # if folder add to our folder list to recursively fetch slides
             if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                 folders += [ entry.replace( "<li>", "" ) ]
             # sliders.xml was included, so check it
             elif ( slidesxml_exists ):
                 # question
                 if ( re.search( question_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( question ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         clue = answer = False
                     self.tmp_slides[ -1 ][ 0 ] = entry
                 # clue
                 elif ( re.search( clue_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( clue ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         question = answer = False
                     self.tmp_slides[ -1 ][ 1 ] = entry
                 # answer
                 elif ( re.search( answer_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( answer ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         question = clue = False
                     self.tmp_slides[ -1 ][ 2 ] = entry
             # add the file as a question
             elif ( entry and os.path.splitext( entry )[ 1 ].lower() in xbmc.getSupportedMedia( "picture" ) ):
                 self.tmp_slides += [ [ "", "", entry ] ]
     # if there are folders call again (we want recursive)
     if ( folders ):
         self._get_slides( folders )
Example #26
0
def get_video_extensions():
    '''Get the video extensions supported by xbmc.

    @return: a lowercase list of media extensions that xbmc claims to support (extensions only, no dots).
    @rtype: [str]
    '''
    try:
        return get_video_extensions._supported
    except AttributeError:
        get_video_extensions._supported = [ext.lstrip('.').lower()
                                           for ext in xbmc.getSupportedMedia('video').split('|')]
        logger.debug('supported video extensions are: ' + repr(get_video_extensions._supported))
        return get_video_extensions._supported
Example #27
0
 def _get_slides( self, paths, media_type ):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi( "GetDirectory(%s)" % ( path, ) ).splitlines()
         # sort in case
         entries.sort()
         # get a slides.xml if it exists
         slidesxml_exists, mpaa, theme, question_format, clue_format, answer_format = self._get_slides_xml( path )
         # check if rating is ok
         if ( slidesxml_exists and self.mpaa_ratings.get( self.mpaa, self.unrated_rating_index ) < self.mpaa_ratings.get( mpaa, self.unrated_rating_index ) ):
             xbmc.log( "Skipping whole folder: %s" % ( path, ), xbmc.LOGNOTICE )
             xbmc.log( "     Movie MPAA: %s - Folder MPAA: %s" % ( self.mpaa, mpaa, ), xbmc.LOGNOTICE )
             continue
         # initialize these to True so we add a new list item to start
         question = clue = answer = True
         # enumerate through our entries list and combine question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace( "<li>", "" )
             # if folder add to our folder list to recursively fetch slides
             if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                 folders += [ entry.replace( "<li>", "" ) ]
             # sliders.xml was included, so check it
             elif ( slidesxml_exists ):
                 # question
                 if ( re.search( question_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( question ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         clue = answer = False
                     self.tmp_slides[ -1 ][ 0 ] = entry
                 # clue
                 elif ( re.search( clue_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( clue ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         question = answer = False
                     self.tmp_slides[ -1 ][ 1 ] = entry
                 # answer
                 elif ( re.search( answer_format, os.path.basename( entry ), re.IGNORECASE ) ):
                     if ( answer ):
                         self.tmp_slides += [ [ "", "", "" ] ]
                         question = clue = False
                     self.tmp_slides[ -1 ][ 2 ] = entry
             # add the file as a question
             elif ( entry and os.path.splitext( entry )[ 1 ].lower() in xbmc.getSupportedMedia( "picture" ) ):
                 self.tmp_slides += [ [ "", "", entry ] ]
     # if there are folders call again (we want recursive)
     if ( folders ):
         self._get_slides( folders )
Example #28
0
def is_file_ext_valid(file_name):
    try:
        COMMON_VIDEO_EXTENSIONS = xbmc.getSupportedMedia('video').split('|')

        COMMON_VIDEO_EXTENSIONS = [
            i for i in COMMON_VIDEO_EXTENSIONS if i != '' and i != '.zip'
        ]
    except:
        pass

    if '.' + file_name.split('.')[-1] not in COMMON_VIDEO_EXTENSIONS:
        return False

    return True
 def _get_special_items( self, **kwargs ):
     # return if no items
     if ( not kwargs[ "items" ] ): return
     # if path is a file check if file exists
     if ( not kwargs[ "isfolder" ] and not kwargs[ "path" ].startswith( "http://" ) and not os.path.isfile( kwargs[ "path" ] ) ): return
     # set default paths list and temp playlist
     self.tmp_paths = [ kwargs[ "path" ] ]
     tmp_playlist = []
     # if path is a folder fetch # videos/images
     if ( kwargs[ "isfolder" ] ):
         # initialize our lists
         self.tmp_paths = []
         # get items
         self._get_items( [ kwargs[ "path" ] ] )
         # shuffle items
         shuffle( self.tmp_paths )
     ## here we divide functions to work like shuffle_slides
     # initialize our listitem
     listitem = None
     # enumerate thru and add our videos/images
     for count in range( kwargs[ "items" ] ):
         # no listitem for images
         if ( os.path.splitext( self.tmp_paths[ count ] )[ 1 ] in xbmc.getSupportedMedia( "video" ) ):
             # create the listitem and fill the infolabels
             listitem = self._get_listitem(
                 title = kwargs.get( "title", os.path.splitext( os.path.basename( self.tmp_paths[ count ] ) )[ 0 ] ),
                 url = self.tmp_paths[ count ],
                 thumbnail = kwargs.get( "thumbnail", None ),
                 plot = kwargs.get( "plot", "" ),
                 duration = kwargs.get( "duration", "" ),
                 mpaa = kwargs.get( "mpaa", "" ),
                 release_date = kwargs.get( "release_date", "0 0 0" ),
                 studio = kwargs.get( "studio", self.Addon.getAddonInfo( "Name" ) ),
                 genre = kwargs.get( "genre", self.Addon.getAddonInfo( "Name" ) ),
                 writer = kwargs.get( "writer", "" ),
                 director = kwargs.get( "director", "" )
             )
         # add our video/image to the temp playlist
         tmp_playlist += [ ( self.tmp_paths[ count ], listitem, ) ]
     # add reults to our experience
     if ( tmp_playlist ):
         kwargs[ "experience" ] += [ { 
             "type": kwargs[ "type" ],
             "playlist": tmp_playlist,
             "slideshow_duration": kwargs.get( "slideshow_duration", -1 ), #FIXME: probably is always -1 unless we combine slideshow
             "image_duration": kwargs.get( "image_duration", -1 ),
             "play_music": False,
         } ]
Example #30
0
def is_playable_media(filename, media="picture"):
    """
    getSupportedMedia(media) -- Returns the supported file types for the specific media as a string.
    media          : string - media type
    *Note, media type can be (video, music, picture).
           The return value is a pipe separated string of filetypes (eg. '.mov|.avi').
           You can use the above as keywords for arguments and skip certain optional arguments.
           Once you use a keyword, all following arguments require the keyword.
    example:
      - mTypes = xbmc.getSupportedMedia('video')
    """
    media_types = xbmc.getSupportedMedia(media).split("|")
    try:
        return os.path.splitext(filename)[1].lower() in media_types
    except:
        print_exc()
Example #31
0
def is_playable_media( filename, media="picture" ):
    """
    getSupportedMedia(media) -- Returns the supported file types for the specific media as a string.
    media          : string - media type
    *Note, media type can be (video, music, picture).
           The return value is a pipe separated string of filetypes (eg. '.mov|.avi').
           You can use the above as keywords for arguments and skip certain optional arguments.
           Once you use a keyword, all following arguments require the keyword.
    example:
      - mTypes = xbmc.getSupportedMedia('video')
    """
    media_types = xbmc.getSupportedMedia( media ).split( "|" )
    try:
        return os.path.splitext( filename )[ 1 ].lower() in media_types
    except:
        print_exc()
 def _set_listitem( self, item, **kwargs ):
     # no listitem for images
     if ( not os.path.splitext( item )[ 1 ] in xbmc.getSupportedMedia( "video" ) ): return None
     # create the listitem and fill the infolabels
     return self._get_listitem(
         title = kwargs.get( "title", os.path.splitext( os.path.basename( item ) )[ 0 ] ),
         url = item,
         thumbnail = kwargs.get( "thumbnail", None ),
         plot = kwargs.get( "plot", "" ),
         duration = kwargs.get( "duration", "" ),
         mpaa = kwargs.get( "mpaa", "" ),
         release_date = kwargs.get( "release_date", "0 0 0" ),
         studio = kwargs.get( "studio", self.Addon.getAddonInfo( "Name" ) ),
         genre = kwargs.get( "genre", self.Addon.getAddonInfo( "Name" ) ),
         writer = kwargs.get( "writer", "" ),
         director = kwargs.get( "director", "" )
     )
Example #33
0
def getVideoList(rootDir):
    stackCounter = 1
    activeStack = ''
    fileList = []
    for filename in library.getFileList(rootDir):
        stackPart = 'cd' + str(stackCounter)
        if stackPart in filename:
            if stackCounter == 1:
                if not activeStack == '':
                    if not activeStack in fileList:
                        fileList.append(activeStack)
                activeStack = 'stack://' + filename
                stackCounter = 2
            else:
                activeStack = activeStack + ' , ' + filename
                stackCounter = stackCounter + 1
        else:
            if not activeStack == '':
                if not activeStack in fileList:
                    fileList.append(activeStack)
                    stackCounter = 1
                    activeStack = ''
            else:
                if not filename in fileList:
                    fileList.append(filename)
    if not activeStack == '':
        if not activeStack in fileList:
            fileList.append(activeStack)
    vidFiles = []
    for vidFileName in sorted(fileList):
        vidFile = {}
        vidFile['path'] = vidFileName
        if __addon__.getSetting("cleanFilenames") == 'true':
            vidFile['title'] = os.path.splitext(
                os.path.split(vidFileName)[1])[0].lstrip('0123456789. ')
            if '.cd' in vidFile['title']:
                vidFile['title'] = os.path.splitext(vidFile['title'])[0]
        else:
            vidFile['title'] = os.path.split(vidFileName)[1]
        if os.path.splitext(vidFileName)[1].lower() in xbmc.getSupportedMedia(
                'video').split('|') and not '-sample' in vidFileName.lower():
            vidFiles.append(vidFile)
        else:
            log('File ignored: %s' % vidFile['path'])
    return vidFiles
Example #34
0
def getBrowseDialog(
    default="",
    heading="",
    dlg_type=3,
    shares="files",
    mask=xbmc.getSupportedMedia("video"),
    use_thumbs=False,
    treat_as_folder=False,
):
    """ shows a browse dialog and returns a value
        - 0 : ShowAndGetDirectory
        - 1 : ShowAndGetFile
        - 2 : ShowAndGetImage
        - 3 : ShowAndGetWriteableDirectory
    """
    dialog = xbmcgui.Dialog()
    value = dialog.browse(dlg_type, heading, shares, mask, use_thumbs, treat_as_folder, default)
    return value
def getVideoList(rootDir):

    stackCounter = 1
    activeStack = ''
    fileList = []
    for filename in library.getFileList(rootDir):
        stackPart = 'cd' + str(stackCounter)
        if stackPart in filename:
                if stackCounter == 1:
                    if not activeStack == '':
                        if not activeStack in fileList:
                            fileList.append(activeStack)
                    activeStack = 'stack://' + filename
                    stackCounter = 2
                else:
                    activeStack = activeStack + ' , ' + filename
                    stackCounter = stackCounter + 1
        else:
            if not activeStack == '':
                if not activeStack in fileList:
                    fileList.append(activeStack)
                    stackCounter = 1
                    activeStack = ''
            else:
                if not filename in fileList:
                    fileList.append(filename)
    if not activeStack == '':
        if not activeStack in fileList:
            fileList.append(activeStack)
    vidFiles = []
    for vidFileName in sorted(fileList):
        vidFile = {}
        vidFile['path'] = vidFileName
        if __addon__.getSetting("cleanFilenames") == 'true':
            vidFile['title'] = os.path.splitext(os.path.split(vidFileName)[1])[0].lstrip('0123456789. ')
            if '.cd' in vidFile['title']:
                vidFile['title'] = os.path.splitext(vidFile['title'])[0]
        else:
            vidFile['title'] = os.path.split(vidFileName)[1]
        if os.path.splitext(vidFileName)[1].lower() in xbmc.getSupportedMedia('video').split('|') and not '-sample' in vidFileName.lower():
            vidFiles.append(vidFile)
        else:
            log('File ignored: %s' % vidFile['path'])
    return vidFiles
 def _get_music_playlist(self, paths):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi("GetDirectory(%s)" % (path,)).splitlines()
         # enumerate through our entries list and combine question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace("<li>", "")
             # if folder add to our folder list to recursively fetch songs
             if entry.endswith("/") or entry.endswith("\\"):
                 folders += [entry.replace("<li>", "")]
             # add songs to our playlist
             elif entry and os.path.splitext(entry)[1].lower() in xbmc.getSupportedMedia("music"):
                 self.mplaylist.add(entry)
     # if there are folders call again (we want recursive)
     if folders:
         self._get_music_playlist(folders)
 def _get_items( self, paths ):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch videos/pictures recursively
     for path in paths:
         # get the directory listing
         entries = os.listdir( self._convert_smb_path( path ) )
         # enumerate through our entries list and check for valid media type
         for entry in entries:
             # join and validate path
             entry = xbmc.validatePath( os.path.join( path, entry ) )
             # if folder add to our folder list to recursively fetch videos/pictures
             if ( os.path.isdir( entry ) ):
                 folders += [ entry ]
             # is this a valid video/image file
             elif ( os.path.splitext( entry )[ 1 ] in xbmc.getSupportedMedia( "video" ) or os.path.splitext( entry )[ 1 ] in xbmc.getSupportedMedia( "picture" ) ):
                 # add our entry
                 self.tmp_paths += [ entry ]
     # if there are folders call again (we want recursive)
     if ( folders ):
         self._get_items( folders )
 def _fetch_trailers( self, paths ):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi( "GetDirectory(%s)" % ( path, ) ).split( "\n" )
         # enumerate through our entries list and separate question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace( "<li>", "" )
             # if folder add to our folder list to recursively fetch slides
             if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                 folders += [ entry ]
             # does this entry match our pattern "-trailer." and is a video file
             elif ( "-trailer." in entry and os.path.splitext( entry )[ 1 ] in xbmc.getSupportedMedia( "video" ) and ( self.movie != os.path.splitext( os.path.basename( entry ).replace( "-trailer", "" ) )[ 0 ] ) ):
                 # add our entry
                 self.tmp_trailers += [ entry ]
     # if there are folders call again (we want recursive)
     if ( folders ):
         self._fetch_trailers( folders )
Example #39
0
 def _fetch_trailers( self, paths ):
     # reset folders list
     folders = []
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi( "GetDirectory(%s)" % ( path, ) ).split( "\n" )
         # enumerate through our entries list and separate question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace( "<li>", "" )
             # if folder add to our folder list to recursively fetch slides
             if ( entry.endswith( "/" ) or entry.endswith( "\\" ) ):
                 folders += [ entry ]
             # does this entry match our pattern "-trailer." and is a video file
             elif ( "-trailer." in entry and os.path.splitext( entry )[ 1 ] in xbmc.getSupportedMedia( "video" ) and ( self.movie != os.path.splitext( os.path.basename( entry ).replace( "-trailer", "" ) )[ 0 ] ) ):
                 # add our entry
                 self.tmp_trailers += [ entry ]
     # if there are folders call again (we want recursive)
     if ( folders ):
         self._fetch_trailers( folders )
Example #40
0
 def _get_items(self, htmlSource):
     # parse source for items
     items = re.findall(
         '<tr><td class="n"><a href="([^"]*)">[^<]*</a>/?</td><td class="m">([^<]*)</td><td class="s">([^<]*)</td><td class="t">([^<]*)<',
         htmlSource)
     # enumerate thru items and set directories and videos
     for item in items:
         # fix date
         try:
             mm = [
                 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
                 "Sep", "Oct", "Nov", "Dec"
             ].index(item[1][5:8])
             date = "%02d-%02d-%04d" % (
                 int(item[1][9:11]),
                 mm + 1,
                 int(item[1][:4]),
             )
         except:
             date = ""
         # fix size
         try:
             m = (
                 1024,
                 1048576,
             )[item[2].endswith("M")]
             size = int(float(item[2][:-1]) * m)
         except:
             size = 0
         # add our item
         if ((item[3] == "Directory" and item[0] != "../")
                 or (os.path.splitext(item[0])[1] and os.path.splitext(
                     item[0])[1] in xbmc.getSupportedMedia("video"))):
             self.items += [(
                 item[0],
                 date,
                 size,
                 (item[3] == "Directory"),
             )]
Example #41
0
    "title",
    "imdbnumber"
]

music_videos_properties = [
    "title",
    "runtime",
    "artist",
    "album",
    "file"
]

# Taken from XBMC
try:
    import xbmc
    m_pictureExtensions = xbmc.getSupportedMedia('picture')
    m_musicExtensions = xbmc.getSupportedMedia('music')
    m_videoExtensions = xbmc.getSupportedMedia('video')
except:
    # Taken from XBMC
    m_pictureExtensions = ".png|.jpg|.jpeg|.bmp|.gif|.ico|.tif|.tiff|.tga|.pcx|.cbz|.zip|.cbr|.rar|.m3u|.dng|.nef|.cr2|.crw|.orf|" +\
        ".arw|.erf|.3fr|.dcr|.x3f|.mef|.raf|.mrw|.pef|.sr2|.rss"
    m_musicExtensions = ".nsv|.m4a|.flac|.aac|.strm|.pls|.rm|.rma|.mpa|.wav|.wma|.ogg|.mp3|.mp2|.m3u|.mod|.amf|.669|.dmf|.dsm|" +\
        ".far|.gdm|.imf|.it|.m15|.med|.okt|.s3m|.stm|.sfx|.ult|.uni|.xm|.sid|.ac3|.dts|.cue|.aif|.aiff|.wpl|.ape|.mac|.mpc|" +\
        ".mp+|.mpp|.shn|.zip|.rar|.wv|.nsf|.spc|.gym|.adx|.dsp|.adp|.ymf|.ast|.afc|.hps|.xsp|.xwav|.waa|.wvs|.wam|.gcm|.idsp|" +\
        ".mpdsp|.mss|.spt|.rsd|.mid|.kar|.sap|.cmc|.cmr|.dmc|.mpt|.mpd|.rmt|.tmc|.tm8|.tm2|.oga|.url|.pxml|.tta|.rss|.cm3|.cms|" +\
        ".dlt|.brstm|.wtv|.mka"
    m_videoExtensions = ".m4v|.3g2|.3gp|.nsv|.tp|.ts|.ty|.strm|.pls|.rm|.rmvb|.m3u|.ifo|.mov|.qt|.divx|.xvid|.bivx|.vob|.nrg|" +\
        ".img|.iso|.pva|.wmv|.asf|.asx|.ogm|.m2v|.avi|.bin|.dat|.mpg|.mpeg|.mp4|.mkv|.avc|.vp3|.svq3|.nuv|.viv|.dv|.fli|.flv|" +\
        ".rar|.001|.wpl|.zip|.vdr|.dvr-ms|.xsp|.mts|.m2t|.m2ts|.evo|.ogv|.sdp|.avs|.rec|.url|.pxml|.vc1|.h264|.rcv|.rss|" +\
        ".mpls|.webm|.bdmv|.wtv"
def _isValidMediaExtension(ext):
    # use Kodi's supported media to check for valid extension
    if ext in xbmc.getSupportedMedia('video') or ext in xbmc.getSupportedMedia(
            'music') or ext in xbmc.getSupportedMedia('picture'):
        return True
    return False
Example #43
0
# -*- coding: utf-8 -*-

import random
import re
try:
    import xbmc
except:
    pass

from requests import Session

COMMON_VIDEO_EXTENSIONS = xbmc.getSupportedMedia('video').split('|')

COMMON_VIDEO_EXTENSIONS = [
    i for i in COMMON_VIDEO_EXTENSIONS if i != '' and i != '.zip'
]

BROWSER_AGENTS = [
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
]

exclusions = ['soundtrack', 'gesproken']
Example #44
0
FANART = os.path.join(HOME, 'fanart.jpg')
SEARCH = os.path.join(HOME, 'resources', 'media', 'search.png')
GETTEXT = ADDON.getLocalizedString
TITLE = ADDON.getAddonInfo('name')

SF_RUNNING = 'SFRUNNING'

MAX_SIZE = 100

XBMCHOME = os.path.join('special://home', 'addons')

DISPLAYNAME = 'Kodi'

NUMBER_SEP = ' | '

PLAYABLE = xbmc.getSupportedMedia('video') + '|' + xbmc.getSupportedMedia(
    'music')
PLAYABLE = PLAYABLE.replace('|.zip', '')
PLAYABLE = PLAYABLE.split('|')

PLAYMEDIA_MODE = 1
ACTIVATEWINDOW_MODE = 2
RUNPLUGIN_MODE = 3
ACTION_MODE = 4

HOMESPECIAL = 'special://home/'
HOMEFULL = xbmc.translatePath(HOMESPECIAL)

DEBUG = ADDON.getSetting('DEBUG') == 'true'

KEYMAP_HOT = 'super_favourites_hot.xml'
Example #45
0
 def _get_slides(self, paths):
     # reset folders list
     folders = []
     # mpaa ratings
     mpaa_ratings = {
         "G": 0,
         "PG": 1,
         "PG-13": 2,
         "R": 3,
         "NC-17": 4,
         "--": 5,
         "": 6
     }
     # enumerate thru paths and fetch slides recursively
     for path in paths:
         # get the directory listing
         entries = xbmc.executehttpapi("GetDirectory(%s)" %
                                       (path, )).split("\n")
         # sort in case
         entries.sort()
         # get a slides.xml if it exists
         slidesxml_exists, mpaa, question_format, clue_format, answer_format = self._get_slides_xml(
             path)
         # check if rating is ok
         if (slidesxml_exists
                 and mpaa_ratings.get(self.mpaa, -1) < mpaa_ratings.get(
                     mpaa, -1)):
             print "skipping whole folder", path
             continue
         # initialize these to True so we add a new list item to start
         question = clue = answer = True
         # enumerate through our entries list and combine question, clue, answer
         for entry in entries:
             # remove <li> from item
             entry = entry.replace("<li>", "")
             # if folder add to our folder list to recursively fetch slides
             if (entry.endswith("/") or entry.endswith("\\")):
                 folders += [entry.replace("<li>", "")]
             # sliders.xml was included, so check it
             elif (slidesxml_exists):
                 # question
                 if (re.search(question_format, os.path.basename(entry),
                               re.IGNORECASE)):
                     if (question):
                         self.tmp_slides += [["", "", ""]]
                         clue = answer = False
                     self.tmp_slides[-1][0] = entry
                 # clue
                 elif (re.search(clue_format, os.path.basename(entry),
                                 re.IGNORECASE)):
                     if (clue):
                         self.tmp_slides += [["", "", ""]]
                         question = answer = False
                     self.tmp_slides[-1][1] = entry
                 # answer
                 elif (re.search(answer_format, os.path.basename(entry),
                                 re.IGNORECASE)):
                     if (answer):
                         self.tmp_slides += [["", "", ""]]
                         question = clue = False
                     self.tmp_slides[-1][2] = entry
             # add the file as a question TODO: maybe check for valid picture format?
             elif (entry and os.path.splitext(entry)[1]
                   in xbmc.getSupportedMedia("picture")):
                 self.tmp_slides += [["", "", entry]]
     # if there are folders call again (we want recursive)
     if (folders):
         self._get_slides(folders)
def _get_special_items( playlist, items, path, genre, title="", thumbnail="", plot="",
                        runtime="", mpaa="", release_date="0 0 0", studio="", writer="",
                        director="", index=-1, media_type="video"
                      ):
    utils.log( "_get_special_items() Started" )
    video_list = []
    # return if not user preference
    if not items:
        utils.log( "No Items added to playlist" )
        return
    # if path is a file check if file exists
    if os.path.splitext( path )[ 1 ] and not path.startswith( "http://" ) and not xbmcvfs.exists( path ):
        utils.log( "_get_special_items() - File Does not Exist" )
        return
    # parse playlist file
    if ( os.path.splitext( path )[ 1 ] ).lower() in ( "m3u", "pls", "asf", "ram" ):
        utils.log( "Video Playlist: %s" % path )
        if ( os.path.splitext( path )[ 1 ] ).lower() == ".m3u":
            video_list = parser.parse_m3u( path, xbmc.getSupportedMedia( media_type ) )
        elif ( os.path.splitext( path )[ 1 ] ).lower() == ".pls":
            video_list = parser.parse_pls( path, xbmc.getSupportedMedia( media_type ) )
        elif ( os.path.splitext( path )[ 1 ] ).lower() == ".asf":
            video_list = parser.parse_asf( path, xbmc.getSupportedMedia( media_type ) )
        elif ( os.path.splitext( path )[ 1 ] ).lower() == ".ram":
            video_list = parser.parse_ram( path, xbmc.getSupportedMedia( media_type ) )
        if not video_list:
            utils.log( "Playlist empty or has unsupported media files" )
            return
        try:
            for item in video_list[::-1]:
                utils.log( "Checking Path: %s" % item )
                # format a title (we don't want the ugly extension)
                video_title = title or os.path.splitext( os.path.basename( item ) )[ 0 ]
                # create the listitem and fill the infolabels
                listitem = _get_listitem( title=video_title,
                                            url=item,
                                      thumbnail=thumbnail,
                                           plot=plot,
                                        runtime=runtime,
                                           mpaa=mpaa,
                                   release_date=release_date,
                                         studio=studio or "Cinema Experience",
                                          genre=genre or "Movie Trailer",
                                         writer=writer,
                                       director=director
                                        )
                # add our video/picture to the playlist or list
                if isinstance( playlist, list ):
                    playlist += [ ( item, listitem, ) ]
                else:
                    playlist.add( item, listitem, index=index )
        except:
            traceback.print_exc()
    else:
        # set default paths list
        tmp_paths = [ path ]
        # if path is a folder fetch # videos/pictures
        if path.endswith( "/" ) or path.endswith( "\\" ):
            utils.log( "_get_special_items() - Path: %s" % path )
            # initialize our lists
            tmp_paths = absolute_listdir( path, media_type = media_type, recursive = True )
            shuffle( tmp_paths )
        # enumerate thru and add our videos/pictures
        for count in range( items ):
            try:
                # set our path
                path = tmp_paths[ count ]
                utils.log( "Checking Path: %s" % path )
                # format a title (we don't want the ugly extension)
                title = title or os.path.splitext( os.path.basename( path ) )[ 0 ]
                # create the listitem and fill the infolabels
                listitem = _get_listitem( title=title,
                                            url=path,
                                      thumbnail=thumbnail,
                                           plot=plot,
                                        runtime=runtime,
                                           mpaa=mpaa,
                                   release_date=release_date,
                                         studio=studio or "Cinema Experience",
                                          genre=genre or "Movie Trailer",
                                         writer=writer,
                                       director=director
                                        )
                # add our video/picture to the playlist or list
                if isinstance( playlist, list ):
                    playlist += [ ( path, listitem, ) ]
                else:
                    playlist.add( path, listitem, index=index )
            except:
                if items > count:
                    utils.log( "Looking for %d files, but only found %d" % ( items, count), xbmc.LOGNOTICE )
                    break
                else:
                    traceback.print_exc()
def supported_video_extensions():
    import xbmc
    supported_video_extensions = xbmc.getSupportedMedia('video').split('|')
    return [i for i in supported_video_extensions if i != '' and i != '.zip']
Example #48
0
 def common_video_extensions(self):
     return [
         i
         for i in xbmc.getSupportedMedia("video").split("|")
         if i != "" and i != ".zip"
     ]
Example #49
0
import fsutils
import library
import logging
from urllib import quote_plus, unquote_plus
from xbmcgui import ListItem
from xbmcplugin import addDirectoryItem, endOfDirectory

plugin = routing.Plugin()
addon = xbmcaddon.Addon()


def convert_pipe_str(string):
    return set([part.lower() for part in string.split('|') if part])


FILE_EXTENSIONS = convert_pipe_str(xbmc.getSupportedMedia('video')) \
    - convert_pipe_str(addon.getSetting('blacklisted_extensions'))
BLACKLISTED_WORDS = convert_pipe_str(addon.getSetting('blacklisted_words'))
BLACKLISTED_DIRECTORIES = convert_pipe_str(
    addon.getSetting('blacklisted_directories'))
SCAN_RECURSIVELY = addon.getSetting('scan_recursively') == 'true'

tr = addon.getLocalizedString


def filter_video(path):
    if any((word.lower() in path for word in BLACKLISTED_WORDS)):
        logging.debug("skipping '%s'. contains blacklisted word" % path)
        return False

    dirname, filename = os.path.split(path.rstrip('/'))
def _isValidMediaExtension(ext):
    # use Kodi's supported media to check for valid extension
    if ext in xbmc.getSupportedMedia('video') or ext in xbmc.getSupportedMedia('music') or ext in xbmc.getSupportedMedia('picture'):
        return True
    return False
Example #51
0
HOME    =  ADDON.getAddonInfo('path')

ROOT    =  ADDON.getSetting('FOLDER')
if not ROOT:
    ROOT = 'special://profile/addon_data/plugin.program.super.favourites/'

PROFILE =  os.path.join(ROOT, 'Super Favourites')
VERSION =  ADDON.getAddonInfo('version')
ICON    =  os.path.join(HOME, 'icon.png')
FANART  =  os.path.join(HOME, 'fanart.jpg')
SEARCH  =  os.path.join(HOME, 'resources', 'media', 'search.png')
DISPLAY =  ADDON.getSetting('DISPLAYNAME')
TITLE   =  GETTEXT(30000)


PLAYABLE = xbmc.getSupportedMedia('video') + '|' + xbmc.getSupportedMedia('music')
PLAYABLE = PLAYABLE.replace('|.zip', '')
#PLAYABLE = 'mp3|mp4|m4v|avi|flv|mpg|mov|txt|%s' % SRC
PLAYABLE = PLAYABLE.split('|')


PLAYMEDIA_MODE      = 1
ACTIVATEWINDOW_MODE = 2
RUNPLUGIN_MODE      = 3
ACTION_MODE         = 4


HOMESPECIAL = 'special://home/'
HOMEFULL    = xbmc.translatePath(HOMESPECIAL)

Example #52
0
# You should have received a copy of the GNU General Public License
# along with Video ScreenSaver.  If not, see <http://www.gnu.org/licenses/>.

import urllib, json, os, traceback
import xbmc, xbmcaddon, xbmcvfs, xbmcgui

# Plugin Info
ADDON_ID = 'screensaver.videosaver'
REAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID)
ADDON_NAME = REAL_SETTINGS.getAddonInfo('name')
ADDON_VERSION = REAL_SETTINGS.getAddonInfo('version')
ICON = REAL_SETTINGS.getAddonInfo('icon')
ADDON_PATH = (REAL_SETTINGS.getAddonInfo('path').decode('utf-8'))
SETTINGS_LOC = REAL_SETTINGS.getAddonInfo('profile').decode('utf-8')
XSP_CACHE_LOC = os.path.join(SETTINGS_LOC, 'cache', '')
MEDIA_EXTS = (xbmc.getSupportedMedia('video')).split('|')
ACTION_STOP = 13
VOLUME = int(REAL_SETTINGS.getSetting('Set_Volume'))
DEBUG = REAL_SETTINGS.getSetting('Enable_Debugging') == 'true'
LANGUAGE = REAL_SETTINGS.getLocalizedString


def log(msg, level=xbmc.LOGDEBUG):
    if DEBUG == False and level != xbmc.LOGERROR: return
    if level == xbmc.LOGERROR: msg += ' ,' + traceback.format_exc()
    xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + (msg.encode("utf-8")),
             level)


def isMute():
    state = False
Example #53
0
def _get_slides(paths, movie_mpaa):
    # reset folders list
    tmp_slides = []
    folders = []
    # mpaa ratings
    mpaa_ratings = {
        "": 0,
        "G": 1,
        "PG": 2,
        "PG-13": 3,
        "R": 4,
        "NC-17": 5,
        "--": 6,
        "NR": 7
    }
    # enumerate thru paths and fetch slides recursively
    for path in paths:
        # get the directory listing
        folders, file_entries = xbmcvfs.listdir(path.decode("utf-8"))
        # sort in case
        file_entries.sort()
        # get a slides.xml if it exists
        slidesxml_exists, mpaa, question_format, clue_format, answer_format, still_format = _get_slides_xml(
            path)
        # check if rating is ok
        utils.log("Movie MPAA: %s" % movie_mpaa)
        utils.log("Slide MPAA: %s" % mpaa)
        if (slidesxml_exists and
                mpaa_ratings.get(movie_mpaa, -1) < mpaa_ratings.get(mpaa, -1)):
            utils.log(
                "Slide Rating above movie rating - skipping whole folder",
                xbmc.LOGNOTICE)
            continue
        # initialize these to True so we add a new list item to start
        question = clue = answer = still = True
        # enumerate through our file_entries list and combine question, clue, answer
        for entry in file_entries:
            # slides.xml was included, so check it
            file_entry = os.path.join(path.decode("utf-8"),
                                      entry.decode("utf-8"))
            if (slidesxml_exists):
                # question
                if (question_format and re.search(question_format,
                                                  os.path.basename(file_entry),
                                                  re.IGNORECASE)):
                    if (question):
                        tmp_slides += [["", "", ""]]
                        clue = answer = still = False
                    tmp_slides[-1][0] = "__question__" + file_entry
                    # clue
                elif (clue_format
                      and re.search(clue_format, os.path.basename(file_entry),
                                    re.IGNORECASE)):
                    if (clue):
                        tmp_slides += [["", "", ""]]
                        question = answer = still = False
                    tmp_slides[-1][1] = "__clue__" + file_entry
                # answer
                elif (answer_format and re.search(answer_format,
                                                  os.path.basename(file_entry),
                                                  re.IGNORECASE)):
                    if (answer):
                        tmp_slides += [["", "", ""]]
                        question = clue = still = False
                    tmp_slides[-1][2] = "__answer__" + file_entry
                    # still
                elif (still_format
                      and re.search(still_format, os.path.basename(file_entry),
                                    re.IGNORECASE)):
                    if (still):
                        tmp_slides += [["", "", ""]]
                        clue = answer = question = False
                    tmp_slides[-1][0] = "__still__" + file_entry
            # add the file as a question TODO: maybe check for valid picture format?
            elif (file_entry and os.path.splitext(file_entry)[1].lower()
                  in xbmc.getSupportedMedia("picture")):
                tmp_slides += [["", "", "__still__" + file_entry]]
    # if there are folders call again (we want recursive)
    if (folders):
        tmp_slides.extend(
            _get_slides(absolute_folder_paths(folders, path), movie_mpaa))
    return tmp_slides
Example #54
0
    def _get(self, key):
        if key == 'lang':
            return xbmc.getLanguage()

        elif key == 'langname':
            langname = xbmc.getLanguage()
            if langname.find('Oromo') != -1:
                langname = 'Oromo'
            else:
                for tag in (' (', ';', ','):
                    i = langname.find(tag)
                    if i != -1:
                        langname = langname[0:i]
                        break
            try:
                LANGCODE[langname]
            except KeyError:
                return 'English'
            else:
                return langname

        elif key == 'langcode':
            return LANGCODE[self._get('langname')]

        elif key == 'dvd':
            state = {0: 'open', 1: 'notready', 2: 'ready', 3: 'empty', 4: 'present', 5: None}
            return state[xbmc.getDVDState()]

        elif key == 'mem':
            return xbmc.getFreeMem() # MB

        elif key == 'time':
            return xbmc.getGlobalIdleTime()

        elif key == 'skin':
            return xbmc.getSkinDir()

        elif key == 'ip':
            return xbmc.getIPAddress()

        elif key == 'platform':
            if self._platform == -1:
                for platform in ('linux', 'windows', 'android', 'atv2', 'ios', 'osx'):
                    if xbmc.getCondVisibility('system.platform.' + platform):
                        self._platform = platform
                        break
                else:
                    self._platform = None
            return self._platform

        elif key == 'is_64bits':
            return sys.maxsize > 2**32

        elif key == 'support':
            if not self._support['all']:
                for src, dst in (('video', 'video'), ('music', 'audio'), ('picture', 'picture')):
                    self._support[dst] = [x[1:] for x in xbmc.getSupportedMedia(src).split('|')]
                    self._support['all'].extend(self._support[dst])
            return self._support

        elif key == 'region':
            if not self._region:
                for tag in ('dateshort', 'datelong', 'time', 'meridiem', 'tempunit', 'speedunit'):
                    self._region[tag] = xbmc.getRegion(tag)
            return self._region

        else:
            raise AttributeError, key
Example #55
0
def _get_special_items(playlist,
                       items,
                       path,
                       genre,
                       title="",
                       thumbnail="",
                       plot="",
                       runtime="",
                       mpaa="",
                       release_date="0 0 0",
                       studio="",
                       writer="",
                       director="",
                       index=-1,
                       media_type="video"):
    utils.log("_get_special_items() Started")
    video_list = []
    # return if not user preference
    if not items:
        utils.log("No Items added to playlist")
        return
    # if path is a file check if file exists
    if genre == "Movie Rating":
        folders, files = xbmcvfs.listdir(path)
        for f in files:
            if (os.path.splitext(f)[0]).lower() == mpaa.lower():
                path = os.path.join(path, f)
    if os.path.splitext(path)[1] and not path.startswith(
            "http://") and not xbmcvfs.exists(path):
        utils.log("_get_special_items() - File Does not Exist")
        return
    # parse playlist file
    if (os.path.splitext(path)[1]).lower() in (".m3u", ".pls", ".asf", ".ram"):
        utils.log("Video Playlist: %s" % path)
        if (os.path.splitext(path)[1]).lower() == ".m3u":
            video_list = parser.parse_m3u(path,
                                          xbmc.getSupportedMedia(media_type))
        elif (os.path.splitext(path)[1]).lower() == ".pls":
            video_list = parser.parse_pls(path,
                                          xbmc.getSupportedMedia(media_type))
        elif (os.path.splitext(path)[1]).lower() == ".asf":
            video_list = parser.parse_asf(path,
                                          xbmc.getSupportedMedia(media_type))
        elif (os.path.splitext(path)[1]).lower() == ".ram":
            video_list = parser.parse_ram(path,
                                          xbmc.getSupportedMedia(media_type))
        if not video_list:
            utils.log("Playlist empty or has unsupported media files")
            return
        try:
            for item in video_list[::-1]:
                utils.log("Checking Path: %s" % item)
                # format a title (we don't want the ugly extension)
                video_title = title or os.path.splitext(
                    os.path.basename(item))[0]
                # create the listitem and fill the infolabels
                listitem = _get_listitem(title=video_title,
                                         url=item,
                                         thumbnail=thumbnail,
                                         plot=plot,
                                         runtime=runtime,
                                         mpaa=mpaa,
                                         release_date=release_date,
                                         studio=studio or "Cinema Experience",
                                         genre=genre or "Movie Trailer",
                                         writer=writer,
                                         director=director)
                # add our video/picture to the playlist or list
                if isinstance(playlist, list):
                    playlist += [(
                        item,
                        listitem,
                    )]
                else:
                    playlist.add(item, listitem, index=index)
        except:
            traceback.print_exc()
    else:
        # set default paths list
        tmp_paths = [path]
        # if path is a folder fetch # videos/pictures
        if path.endswith("/") or path.endswith("\\"):
            utils.log("_get_special_items() - Path: %s" % path)
            # initialize our lists
            tmp_paths = absolute_listdir(path,
                                         media_type=media_type,
                                         recursive=True)
            shuffle(tmp_paths)
        # enumerate thru and add our videos/pictures
        for count in range(items):
            try:
                # set our path
                path = tmp_paths[count]
                utils.log("Checking Path: %s" % path)
                # format a title (we don't want the ugly extension)
                title = title or os.path.splitext(os.path.basename(path))[0]
                # create the listitem and fill the infolabels
                listitem = _get_listitem(title=title,
                                         url=path,
                                         thumbnail=thumbnail,
                                         plot=plot,
                                         runtime=runtime,
                                         mpaa=mpaa,
                                         release_date=release_date,
                                         studio=studio or "Cinema Experience",
                                         genre=genre or "Movie Trailer",
                                         writer=writer,
                                         director=director)
                # add our video/picture to the playlist or list
                if isinstance(playlist, list):
                    playlist += [(
                        path,
                        listitem,
                    )]
                else:
                    playlist.add(path, listitem, index=index)
            except:
                if items > count:
                    utils.log(
                        "Looking for %d files, but only found %d" %
                        (items, count), xbmc.LOGNOTICE)
                    break
                else:
                    traceback.print_exc()
Example #56
0
 def get_supported_media(media_type):
     import xbmc
     return xbmc.getSupportedMedia(media_type).replace(".","").split("|")
Example #57
0
                                        ('trailers', 'StereoscopyNews', False),
                                        ('trailers', 'Content', False)):
            sett = xbmcaddon.Addon().getSetting('scraper.{0}.{1}'.format(
                stype, scraper))
            if sett in ('true', 'false'):
                sett = sett == 'true'
            else:
                sett = default

            if sett:
                ret.append((stype, scraper))

        return ret

    videoExtensions = tuple(
        xbmc.getSupportedMedia('video').split('|') + ['.cvurl'])
    musicExtensions = tuple(xbmc.getSupportedMedia('music').split('|'))
    imageExtensions = tuple(xbmc.getSupportedMedia('picture').split('|'))

except:
    raise
    import zipfile

    STORAGE_PATH = '/home/ruuk/tmp/content'

    def T(ID, eng=''):
        return eng

    def vfs():
        pass
Example #58
0
    def addFile(self, name, path, meta):
        url = None
        listItem = None
        #print "path: %s" % path
        #print "meta: ", meta
        mediatype = ''
        iconImage = 'DefaultFile.png'

        ext = name.rsplit('.', 1)[-1].lower()
        isImageFile = ext in xbmc.getSupportedMedia('picture')
        isVideoFile = ext in xbmc.getSupportedMedia('video')
        isAudioFile = ext in xbmc.getSupportedMedia('music')
        isExactlyOneMediaType = (
            (isImageFile ^ isVideoFile ^ isAudioFile)
            and not (isImageFile and isVideoFile and isAudioFile))
        showAllFiles = self._contentType == 'executable' or not self._filterFiles
        if (not isExactlyOneMediaType) and showAllFiles:
            mediatype = 'other'
            iconImage = 'DefaultFile.png'
        elif isImageFile and (self._contentType == 'image' or showAllFiles):
            mediatype = 'pictures'
            iconImage = 'DefaultImage.png'
        elif isVideoFile and (self._contentType == 'video' or showAllFiles):
            mediatype = 'video'
            iconImage = 'DefaultVideo.png'
        elif isAudioFile and (self._contentType == 'audio' or showAllFiles):
            mediatype = 'music'
            iconImage = 'DefaultAudio.png'

        if mediatype != '':
            listItem = xbmcgui.ListItem(name, iconImage=iconImage)
            self.metadata2ItemInfo(listItem, meta, mediatype)
            if self._enabledSync and self._remoteSyncPath in path:
                #Use the synchronized location for url
                self._loadedMediaItems += 1
                url = getLocalSyncPath(self._localSyncPath,
                                       self._remoteSyncPath, path)
            elif mediatype in ['pictures', 'video', 'music']:
                self._loadedMediaItems += 1
                tumb = self._loader.getThumbnail(path, meta)
                if tumb:
                    listItem.setThumbnailImage(tumb)
                if self._useStreamingURLs and mediatype in ['video', 'music']:
                    #this doesn't work for pictures...
                    listItem.setProperty("IsPlayable", "true")
                    url = sys.argv[
                        0] + '?action=play' + '&path=' + urllib.quote(
                            path.encode("utf-8"))
                    url += '&account=' + urllib.quote(
                        self._account_settings.account_name.encode("utf-8"))
                else:
                    url = self._loader.getFile(path)
                    #url = self.getMediaUrl(path)
            else:
                listItem.setProperty("IsPlayable", "false")
                url = 'No action'
            if listItem:
                contextMenuItems = []
                searchUrl = self.getUrl(self._current_path,
                                        module='search_dropbox')
                contextMenuItems.append(
                    (LANGUAGE_STRING(30017), 'XBMC.RunPlugin(%s)' % searchUrl))
                contextMenuItems.append((LANGUAGE_STRING(30022),
                                         self.getContextUrl(path, 'delete')))
                contextMenuItems.append(
                    (LANGUAGE_STRING(30024), self.getContextUrl(path, 'copy')))
                contextMenuItems.append(
                    (LANGUAGE_STRING(30027), self.getContextUrl(path, 'move')))
                contextMenuItems.append(
                    (LANGUAGE_STRING(30029),
                     self.getContextUrl(self._current_path, 'create_folder')))
                contextMenuItems.append(
                    (LANGUAGE_STRING(30031),
                     self.getContextUrl(self._current_path, 'upload')))
                contextMenuItems.append(
                    (LANGUAGE_STRING(30037),
                     self.getContextUrl(path, 'download',
                                        extra='isDir=False')))
                if self._enabledSync and self._remoteSyncPath in path:
                    contextMenuItems.append(
                        (LANGUAGE_STRING(30112),
                         self.getContextUrl(self._current_path, 'sync_now')))
                listItem.addContextMenuItems(contextMenuItems,
                                             replaceItems=True)
                xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                            url=url,
                                            listitem=listItem,
                                            isFolder=False,
                                            totalItems=self._totalItems)