示例#1
0
    def _doesThemeExist(self, directory):
        log("doesThemeExist: Checking directory: %s" % directory)
        # Check for custom theme directory
        if Settings.isThemeDirEnabled():
            themeDir = os_path_join(directory, Settings.getThemeDirectory())
            # Check if this directory exists
            if not dir_exists(themeDir):
                workingPath = directory
                # If the path currently ends in the directory separator
                # then we need to clear an extra one
                if (workingPath[-1] == os.sep) or (workingPath[-1]
                                                   == os.altsep):
                    workingPath = workingPath[:-1]
                # If not check to see if we have a DVD VOB
                if (os_path_split(workingPath)[1]
                        == 'VIDEO_TS') or (os_path_split(workingPath)[1]
                                           == 'BDMV'):
                    # Check the parent of the DVD Dir
                    themeDir = os_path_split(workingPath)[0]
                    themeDir = os_path_join(themeDir,
                                            Settings.getThemeDirectory())
            directory = themeDir

        # check if the directory exists before searching
        if dir_exists(directory):
            # Generate the regex
            themeFileRegEx = Settings.getThemeFileRegEx(audioOnly=True)

            dirs, files = list_dir(directory)
            for aFile in files:
                m = re.search(themeFileRegEx, aFile, re.IGNORECASE)
                if m:
                    log("doesThemeExist: Found match: " + aFile)
                    return True
        return False
示例#2
0
    def getPlatformLibFiles(parentDir):
        if parentDir in [None, ""]:
            return None

        log("FFMpegLib: Looking for libraries in %s" % parentDir)
        libLocation = {}

        # Check if the directory exists
        if dir_exists(parentDir):
            # List the contents of the directory
            dirs, files = xbmcvfs.listdir(parentDir)
            for aFile in files:
                if 'avutil' in aFile:
                    libLocation['avutil'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avutil library: %s" % libLocation['avutil'])
                elif 'swresample' in aFile:
                    libLocation['swresample'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found swresample library: %s" % libLocation['swresample'])
                elif 'avcodec' in aFile:
                    libLocation['avcodec'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avcodec library: %s" % libLocation['avcodec'])
                elif 'avformat' in aFile:
                    libLocation['avformat'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avformat library: %s" % libLocation['avformat'])
        else:
            log("FFMpegLib: Directory not found %s" % parentDir)

        # Make sure we found all of the libraries
        if len(libLocation) < 4:
            return None

        return libLocation
示例#3
0
    def _moveToThemeFolder(self, directory):
        log("moveToThemeFolder: path = %s" % directory)

        # Handle the case where we have a disk image
        if (os_path_split(directory)[1] == 'VIDEO_TS') or (os_path_split(directory)[1] == 'BDMV'):
            directory = os_path_split(directory)[0]

        dirs, files = list_dir(directory)
        for aFile in files:
            m = re.search(Settings.getThemeFileRegEx(directory), aFile, re.IGNORECASE)
            if m:
                srcpath = os_path_join(directory, aFile)
                log("fetchAllMissingThemes: Found match: %s" % srcpath)
                targetpath = os_path_join(directory, Settings.getThemeDirectory())
                # Make sure the theme directory exists
                if not dir_exists(targetpath):
                    try:
                        xbmcvfs.mkdir(targetpath)
                    except:
                        log("fetchAllMissingThemes: Failed to create directory: %s" % targetpath, True, xbmc.LOGERROR)
                        break
                else:
                    log("moveToThemeFolder: directory already exists %s" % targetpath)
                # Add the filename to the path
                targetpath = os_path_join(targetpath, aFile)
                if not xbmcvfs.rename(srcpath, targetpath):
                    log("moveToThemeFolder: Failed to move file from %s to %s" % (srcpath, targetpath))
示例#4
0
    def _doesThemeExist(self, directory):
        log("doesThemeExist: Checking directory: %s" % directory)
        # Check for custom theme directory
        if Settings.isThemeDirEnabled():
            themeDir = os_path_join(directory, Settings.getThemeDirectory())
            # Check if this directory exists
            if not dir_exists(themeDir):
                workingPath = directory
                # If the path currently ends in the directory separator
                # then we need to clear an extra one
                if (workingPath[-1] == os.sep) or (workingPath[-1] == os.altsep):
                    workingPath = workingPath[:-1]
                # If not check to see if we have a DVD VOB
                if (os_path_split(workingPath)[1] == 'VIDEO_TS') or (os_path_split(workingPath)[1] == 'BDMV'):
                    # Check the parent of the DVD Dir
                    themeDir = os_path_split(workingPath)[0]
                    themeDir = os_path_join(themeDir, Settings.getThemeDirectory())
            directory = themeDir

        # check if the directory exists before searching
        if dir_exists(directory):
            # Generate the regex
            themeFileRegEx = Settings.getThemeFileRegEx(audioOnly=True)

            dirs, files = list_dir(directory)
            for aFile in files:
                m = re.search(themeFileRegEx, aFile, re.IGNORECASE)
                if m:
                    log("doesThemeExist: Found match: " + aFile)
                    return True
        return False
示例#5
0
    def _getExtrasDirFiles(self,
                           basepath,
                           exitOnFirst=False,
                           noExtrasDirNeeded=False):
        # If a custom path, then don't looks for the Extras directory
        if noExtrasDirNeeded or Settings.isCustomPathEnabled():
            extrasDir = basepath
        else:
            # Add the name of the extras directory to the end of the path
            extrasDir = os_path_join(basepath, Settings.getExtrasDirName())
        log("VideoExtrasFinder: Checking existence for %s" % extrasDir)
        extras = []
        # Check if the extras directory exists
        if dir_exists(extrasDir):
            # list everything in the extras directory
            dirs, files = xbmcvfs.listdir(extrasDir)
            for filename in files:
                log("VideoExtrasFinder: found file: %s" % filename)
                # Check each file in the directory to see if it should be skipped
                if not self._shouldSkipFile(filename):
                    extrasFile = os_path_join(extrasDir, filename)
                    extraItem = ExtrasItem(extrasDir,
                                           extrasFile,
                                           extrasDb=self.extrasDb,
                                           defaultFanArt=self.defaultFanArt)
                    extras.append(extraItem)
                    # Check if we are only looking for the first entry
                    if exitOnFirst is True:
                        break
            # Now check all the directories in the "Extras" directory
            # Need to see if they contain a DVD image
            for dirName in dirs:
                log("VideoExtrasFinder: found directory: %s" % dirName)
                # Check each directory to see if it should be skipped
                if not self._shouldSkipFile(dirName):
                    extrasSubDir = os_path_join(extrasDir, dirName)
                    # Check to see if this sub-directory is a DVD directory by checking
                    # to see if there is VIDEO_TS directory
                    videoTSDir = os_path_join(extrasSubDir, 'VIDEO_TS')
                    # Also check for Bluray
                    videoBluRayDir = os_path_join(extrasSubDir, 'BDMV')
                    if dir_exists(videoTSDir) or dir_exists(videoBluRayDir):
                        extraItem = ExtrasItem(
                            extrasDir,
                            extrasSubDir,
                            extrasDb=self.extrasDb,
                            defaultFanArt=self.defaultFanArt)
                        extras.append(extraItem)

                    # Check if we are only looking for the first entry
                    if exitOnFirst is True:
                        break

        return extras
示例#6
0
    def _addFilesFromPlaylist(self, playlistFile, directory):
        if (playlistFile is None) or (playlistFile == ""):
            return

        fileExt = os.path.splitext(playlistFile)[1]

        # Check if dealing with a Smart Playlist
        if fileExt == ".xsp":
            # Process the Smart Playlist
            self._addFilesFromSmartPlaylist(playlistFile)
            return

        if ("/" not in playlistFile) and ("\\" not in playlistFile):
            # There is just the filename of the playlist without
            # a path, check if the file is local or if we should
            # read it from the user directory
            # Check if there is an extension on the name
            if fileExt is None or fileExt == "":
                playlistFile = playlistFile + ".m3u"
            localFile = os_path_join(directory, playlistFile)
            if xbmcvfs.exists(localFile):
                # Make it a full path if it is not already
                playlistFile = localFile
            else:
                # default to the music playlist directory if not local
                playlistFile = os_path_join(
                    xbmc.translatePath("special://musicplaylists"),
                    playlistFile)

        log("NfoReader: playlist file = %s" % playlistFile,
            self.debug_logging_enabled)

        if xbmcvfs.exists(playlistFile):
            # Load the playlist into the Playlist object
            # An exception if thrown if the file does not exist
            try:
                xbmcPlaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
                xbmcPlaylist.load(playlistFile)
                i = 0
                while i < xbmcPlaylist.size():
                    # get the filename from the playlist
                    file = xbmcPlaylist[i].getfilename()
                    i = i + 1
                    if (file is not None) and (file != ""):
                        log("NfoReader: file from playlist = %s" % file,
                            self.debug_logging_enabled)
                        self.themeFiles.append(file)
            except:
                log(
                    "NfoReader: playlist file processing error = %s" %
                    playlistFile, True, xbmc.LOGERROR)
        else:
            log("NfoReader: playlist file not found = %s" % playlistFile,
                self.debug_logging_enabled)
示例#7
0
    def __init__(self):
        addonRootDir = xbmc.translatePath("special://profile/addon_data/%s" % __addonid__).decode("utf-8")
        self.tempDir = os_path_join(addonRootDir, "temp")
        self.videoDir = os_path_join(addonRootDir, "videos")

        # Set up the addon directories if they do not already exist
        if not dir_exists(addonRootDir):
            xbmcvfs.mkdir(addonRootDir)
        if not dir_exists(self.tempDir):
            xbmcvfs.mkdir(self.tempDir)
        if not dir_exists(self.videoDir):
            xbmcvfs.mkdir(self.videoDir)
    def _loadImages(self, filename):
        imageList = []
        # Find out the name of the image files
        fileNoExt = os.path.splitext(filename)[0]

        # Start by searching for the filename match
        fileNoExtImage = self._loadImageFile(fileNoExt)
        if fileNoExtImage != "":
            imageList.append(fileNoExtImage)

        # Check for -poster added to the end
        fileNoExtImage = self._loadImageFile(fileNoExt + "-poster")
        if fileNoExtImage != "":
            imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for -thumb added to the end
            fileNoExtImage = self._loadImageFile(fileNoExt + "-thumb")
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for poster.jpg
            fileDir = os_path_join(self.directory, "poster")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for folder.jpg
            fileDir = os_path_join(self.directory, "folder")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        # Set the first one to the thumbnail, and the second the the icon
        if len(imageList) > 0:
            self.thumbnailImage = imageList[0]
            if len(imageList) > 1:
                self.iconImage = imageList[1]

        # Now check for the fanart
        # Check for -fanart added to the end
        fileNoExtImage = self._loadImageFile(fileNoExt + "-fanart")
        if fileNoExtImage != "":
            self.fanart = fileNoExtImage
        else:
            # Check for fanart.jpg
            fileDir = os_path_join(self.directory, "fanart")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                self.fanart = fileNoExtImage
示例#9
0
    def _loadImages(self, filename):
        imageList = []
        # Find out the name of the image files
        fileNoExt = os.path.splitext(filename)[0]

        # Start by searching for the filename match
        fileNoExtImage = self._loadImageFile(fileNoExt)
        if fileNoExtImage != "":
            imageList.append(fileNoExtImage)

        # Check for -poster added to the end
        fileNoExtImage = self._loadImageFile(fileNoExt + "-poster")
        if fileNoExtImage != "":
            imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for -thumb added to the end
            fileNoExtImage = self._loadImageFile(fileNoExt + "-thumb")
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for poster.jpg
            fileDir = os_path_join(self.directory, "poster")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        if len(imageList) < 2:
            # Check for folder.jpg
            fileDir = os_path_join(self.directory, "folder")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                imageList.append(fileNoExtImage)

        # Set the first one to the thumbnail, and the second the the icon
        if len(imageList) > 0:
            self.thumbnailImage = imageList[0]
            if len(imageList) > 1:
                self.iconImage = imageList[1]

        # Now check for the fanart
        # Check for -fanart added to the end
        fileNoExtImage = self._loadImageFile(fileNoExt + "-fanart")
        if fileNoExtImage != "":
            self.fanart = fileNoExtImage
        else:
            # Check for fanart.jpg
            fileDir = os_path_join(self.directory, "fanart")
            fileNoExtImage = self._loadImageFile(fileDir)
            if fileNoExtImage != "":
                self.fanart = fileNoExtImage
示例#10
0
    def __init__(self):
        addonRootDir = xbmc.translatePath('special://profile/addon_data/%s' % __addonid__).decode("utf-8")
        self.tempDir = os_path_join(addonRootDir, 'temp')
        self.videoDir = os_path_join(addonRootDir, 'videos')
        self.ziggyServer = "aHR0cDovL2tvZGkuemlnZ3k3MzcwMS5zZWVkci5pby9WaWRlb1NjcmVlbnNhdmVyLw=="

        # Set up the addon directories if they do not already exist
        if not dir_exists(addonRootDir):
            xbmcvfs.mkdir(addonRootDir)
        if not dir_exists(self.tempDir):
            xbmcvfs.mkdir(self.tempDir)
        if not dir_exists(self.videoDir):
            xbmcvfs.mkdir(self.videoDir)
示例#11
0
    def __init__(self):
        addonRootDir = xbmc.translatePath('special://profile/addon_data/%s' %
                                          __addonid__).decode("utf-8")
        self.tempDir = os_path_join(addonRootDir, 'temp')
        self.videoDir = os_path_join(addonRootDir, 'videos')

        # Set up the addon directories if they do not already exist
        if not dir_exists(addonRootDir):
            xbmcvfs.mkdir(addonRootDir)
        if not dir_exists(self.tempDir):
            xbmcvfs.mkdir(self.tempDir)
        if not dir_exists(self.videoDir):
            xbmcvfs.mkdir(self.videoDir)
示例#12
0
    def _findCoverImage(self, dirPath):
        coverImages = []
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.startswith('cover') and (aFile.endswith('jpg') or aFile.endswith('jpeg') or aFile.endswith('png')):
                # Add this image to the list
                coverImages.append(os_path_join(dirPath, aFile))

        # Now check any of the directories
        for aDir in dirs:
            coverImages = coverImages + self._findCoverImage(os_path_join(dirPath, aDir))

        return coverImages
示例#13
0
    def __init__(self):
        addonRootDir = xbmc.translatePath('special://profile/addon_data/%s' %
                                          __addonid__).decode("utf-8")
        self.tempDir = os_path_join(addonRootDir, 'temp')
        self.videoDir = os_path_join(addonRootDir, 'videos')
        self.ziggyServer = "aHR0cDovL2tvZGkuemlnZ3k3MzcwMS5zZWVkci5pby9WaWRlb1NjcmVlbnNhdmVyLw=="

        # Set up the addon directories if they do not already exist
        if not dir_exists(addonRootDir):
            xbmcvfs.mkdir(addonRootDir)
        if not dir_exists(self.tempDir):
            xbmcvfs.mkdir(self.tempDir)
        if not dir_exists(self.videoDir):
            xbmcvfs.mkdir(self.videoDir)
示例#14
0
    def _findCoverImage(self, dirPath):
        coverImages = []
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.startswith('cover') and (aFile.endswith('jpg') or aFile.endswith('jpeg') or aFile.endswith('png')):
                # Add this image to the list
                coverImages.append(os_path_join(dirPath, aFile))

        # Now check any of the directories
        for aDir in dirs:
            coverImages = coverImages + self._findCoverImage(os_path_join(dirPath, aDir))

        return coverImages
示例#15
0
    def _getThemeFiles(self, directory, extensionOnly=False):
        # First read from the NFO file if it exists
        nfoRead = NfoReader(directory, self.debug_logging_enabled)
        themeFiles = nfoRead.getThemeFiles()

        # Get the theme directories that are referenced and process the data in them
        for nfoDir in nfoRead.getThemeDirs():
            # Do not want the theme keyword if looking at an entire directory
            themeFiles = themeFiles + self._getThemeFiles(nfoDir, True)

        del nfoRead

        themeRegex = Settings.getThemeFileRegEx(directory, extensionOnly,
                                                self.audioOnly)
        log("ThemeFiles: Searching %s for %s" % (directory, themeRegex),
            self.debug_logging_enabled)

        # Make sure that the path does not point to a plugin, as we are checking the
        # file-system for themes, not plugins. This can be the case with Emby
        if "plugin://" in directory:
            log(
                "ThemeFiles: Plugin paths do not support theme files: %s" %
                directory, self.debug_logging_enabled)
        else:
            # check if the directory exists before searching
            if dir_exists(directory):
                dirs, files = list_dir(directory)
                for aFile in files:
                    m = re.search(themeRegex, aFile, re.IGNORECASE)
                    if m:
                        path = os_path_join(directory, aFile)
                        log("ThemeFiles: Found match: %s" % path,
                            self.debug_logging_enabled)
                        # Add the theme file to the list
                        themeFiles.append(path)
                # Check to see if any themes were found, and if not see if we should try
                # and use a trailer file instead
                if (len(themeFiles) < 1) and (not self.audioOnly) and (
                        not extensionOnly) and Settings.useTrailers():
                    trailerRegEx = Settings.getTrailerFileRegEx()
                    for aFile in files:
                        m = re.search(trailerRegEx, aFile, re.IGNORECASE)
                        if m:
                            path = os_path_join(directory, aFile)
                            log("ThemeFiles: Found trailer match: %s" % path,
                                self.debug_logging_enabled)
                            # Add the trailer file to the list
                            themeFiles.append(path)

        return themeFiles
示例#16
0
    def _getExtrasDirFiles(self, basepath, exitOnFirst=False, noExtrasDirNeeded=False):
        # If a custom path, then don't looks for the Extras directory
        if noExtrasDirNeeded or Settings.isCustomPathEnabled():
            extrasDir = basepath
        else:
            # Add the name of the extras directory to the end of the path
            extrasDir = os_path_join(basepath, Settings.getExtrasDirName())
        log("VideoExtrasFinder: Checking existence for %s" % extrasDir)
        extras = []
        # Check if the extras directory exists
        if dir_exists(extrasDir):
            # list everything in the extras directory
            dirs, files = xbmcvfs.listdir(extrasDir)
            for filename in files:
                log("VideoExtrasFinder: found file: %s" % filename)
                # Check each file in the directory to see if it should be skipped
                if not self._shouldSkipFile(filename):
                    extrasFile = os_path_join(extrasDir, filename)
                    extraItem = ExtrasItem(extrasDir, extrasFile, extrasDb=self.extrasDb, defaultFanArt=self.defaultFanArt)
                    extras.append(extraItem)
                    # Check if we are only looking for the first entry
                    if exitOnFirst is True:
                        break
            # Now check all the directories in the "Extras" directory
            # Need to see if they contain a DVD image
            for dirName in dirs:
                log("VideoExtrasFinder: found directory: %s" % dirName)
                # Check each directory to see if it should be skipped
                if not self._shouldSkipFile(dirName):
                    extrasSubDir = os_path_join(extrasDir, dirName)
                    # Check to see if this sub-directory is a DVD directory by checking
                    # to see if there is VIDEO_TS directory
                    videoTSDir = os_path_join(extrasSubDir, 'VIDEO_TS')
                    # Also check for Bluray
                    videoBluRayDir = os_path_join(extrasSubDir, 'BDMV')
                    if dir_exists(videoTSDir) or dir_exists(videoBluRayDir):
                        extraItem = ExtrasItem(extrasDir, extrasSubDir, extrasDb=self.extrasDb, defaultFanArt=self.defaultFanArt)
                        extras.append(extraItem)
                    else:
                        # This is a sub directory inside the extras directory that is
                        # not a DVD image directory, so scan the contents of this as well
                        extras = extras + self._getExtrasDirFiles(extrasSubDir, exitOnFirst, True)

                    # Check if we are only looking for the first entry
                    if exitOnFirst is True:
                        break

        return extras
示例#17
0
    def _findBookFile(self, dirPath, bookFileName):
        bookFile = None
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.lower() == bookFileName:
                # Found a match, set the value
                bookFile = os_path_join(dirPath, aFile)
                break

        # Now check any of the directories
        for aDir in dirs:
            if bookFile is None:
                bookFile = self._findBookFile(os_path_join(dirPath, aDir), bookFileName)

        return bookFile
示例#18
0
    def _getMainCoverLocation(self):
        coverFileName, oldExt = os.path.splitext(self.fileName)
        targetCoverName = "%s.jpg" % coverFileName
        coverTargetName = os_path_join(Settings.getCoverCacheLocation(), targetCoverName)

        log("AudioBookHandler: Cached cover target location is %s" % coverTargetName)
        return coverTargetName
示例#19
0
    def getCoverImage(filePath, eBookFileName):
        # Check if there is a cached version
        coverTargetName = None
        fullpathLocalImage, bookExt = os.path.splitext(filePath)
        fullpathLocalImage = "%s.jpg" % fullpathLocalImage

        if xbmcvfs.exists(fullpathLocalImage):
            log("EBookBase: Found local cached image %s" % fullpathLocalImage)
            return fullpathLocalImage

        # Check for a cached cover
        coverTargetName = EBookBase.getCachedCover(eBookFileName)

        # If we reach here, then there was no cached cover image, so we need to extract one
        if coverTargetName in [None, ""]:
            ebook = EBookBase.createEBookObject(filePath)
            coverTargetName = ebook.extractCoverImage()
            ebook.tidyUp()
            del ebook

        # If there is still no cover image, check for folder.jpg in the same directory
        if coverTargetName in [None, ""]:
            baseDirectory = (os_path_split(filePath))[0]
            subdirs, filesInDir = xbmcvfs.listdir(baseDirectory)
            for fileInDir in filesInDir:
                if fileInDir.lower() in ['folder.jpg', 'cover.jpg', 'folder.png', 'cover.png']:
                    coverTargetName = os_path_join(baseDirectory, fileInDir)

        return coverTargetName
示例#20
0
    def _getNestedExtrasFiles(self, basepath, filename, exitOnFirst=False, noExtrasDirNeeded=False):
        extras = []
        if dir_exists(basepath):
            dirs, files = xbmcvfs.listdir(basepath)
            for dirname in dirs:
                # Do not search inside Bluray or DVD images
                if (dirname == 'VIDEO_TS') or (dirname == 'BDMV'):
                    continue

                dirpath = os_path_join(basepath, dirname)
                log("VideoExtrasFinder: Nested check in directory: %s" % dirpath)
                if dirname != Settings.getExtrasDirName():
                    log("VideoExtrasFinder: Check directory: %s" % dirpath)
                    extras.extend(self._getExtrasDirFiles(dirpath, exitOnFirst, noExtrasDirNeeded))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
                    extras.extend(self._getExtrasFiles(dirpath, filename, exitOnFirst))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
                    extras.extend(self._getNestedExtrasFiles(dirpath, filename, exitOnFirst, noExtrasDirNeeded))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
        return extras
示例#21
0
    def _loadHashRecord(self, recordLocation):
        log("AddonData: Loading hash record %s" % recordLocation)

        hashFile = os_path_join(recordLocation, 'hashdata.xml')

        addonList = {}
        if not xbmcvfs.exists(hashFile):
            log("AddonData: Unable to load as file does not exist %s" % hashFile)
            return addonList

        try:
            recordFile = xbmcvfs.File(hashFile, 'r')
            recordFileStr = recordFile.read()
            recordFile.close()

            hashRecord = ET.ElementTree(ET.fromstring(recordFileStr))

            for elemItem in hashRecord.findall('addon'):
                hashDetails = {}
                addonName = elemItem.attrib['name']
                hashDetails['name'] = addonName
                hashDetails['version'] = elemItem.attrib['version']
                hashDetails['hash'] = elemItem.text
                log("AddonData: Processing entry %s (%s) with hash %s" % (hashDetails['name'], hashDetails['version'], hashDetails['hash']))
                addonList[addonName] = hashDetails
        except:
            log("AddonData: Failed to read in file %s" % hashFile, xbmc.LOGERROR)
            log("AddonData: %s" % traceback.format_exc(), xbmc.LOGERROR)

        return addonList
示例#22
0
    def _findTocNcx(self, dirPath):
        tocNcx = None
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.lower() == 'toc.ncx':
                # Found the table of contents file
                tocNcx = os_path_join(dirPath, aFile)
                break

        # Now check any of the directories
        for aDir in dirs:
            if tocNcx is None:
                tocNcx = self._findTocNcx(os_path_join(dirPath, aDir))

        return tocNcx
示例#23
0
 def __init__(self):
     # Start by getting the database location
     self.configPath = xbmc.translatePath(__addon__.getAddonInfo('profile'))
     self.databasefile = os_path_join(self.configPath, "pinsentry_database.db")
     log("PinSentryDB: Database file location = %s" % self.databasefile)
     # Make sure that the database exists if this is the first time
     self.createDatabase()
示例#24
0
    def __init__(self, rawPath, pathList=None, videotitle=None, debug_logging_enabled=True, audioOnly=False):
        self.debug_logging_enabled = debug_logging_enabled
        self.forceShuffle = False
        self.doNotShuffle = False
        self.audioOnly = audioOnly
        self.rawPath = rawPath
        if rawPath in [None, ""]:
            self.clear()
        else:
            # Check for the case where there is a custom path set so we need to use
            # the custom location rather than the rawPath
            if Settings.isCustomPathEnabled() and (videotitle not in [None, ""]):
                customRoot = Settings.getCustomPath()
                # Make sure that the path passed in has not already been converted
                if customRoot not in self.rawPath:
                    self.rawPath = os_path_join(customRoot, normalize_string(videotitle))
                    log("ThemeFiles: Setting custom path to %s" % self.rawPath, self.debug_logging_enabled)

            if (pathList is not None) and (len(pathList) > 0):
                self.themeFiles = []
                for aPath in pathList:
                    subThemeList = self._generateThemeFilelistWithDirs(aPath)
                    # add these files to the existing list
                    self.themeFiles = self._mergeThemeLists(self.themeFiles, subThemeList)
                # If we were given a list, then we should shuffle the themes
                # as we don't always want the first path playing first
                self.forceShuffle = True
            else:
                self.themeFiles = self._generateThemeFilelistWithDirs(self.rawPath)

        # Check if we need to handle the ordering for video themes
        if not audioOnly:
            self.doNotShuffle = self._filterForVideoThemesRule()
            self.forceShuffle = False
示例#25
0
    def _findBookFile(self, dirPath, bookFileName):
        bookFile = None
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.lower() == bookFileName:
                # Found a match, set the value
                bookFile = os_path_join(dirPath, aFile)
                break

        # Now check any of the directories
        for aDir in dirs:
            if bookFile is None:
                bookFile = self._findBookFile(os_path_join(dirPath, aDir), bookFileName)

        return bookFile
示例#26
0
    def _getExtrasFiles(self, filepath, filename, exitOnFirst=False):
        extras = []
        extrasTag = Settings.getExtrasFileTag()

        # If there was no filename given, nothing to do
        if (filename is None) or (filename == "") or (extrasTag == ""):
            return extras
        directory = filepath
        dirs, files = xbmcvfs.listdir(directory)

        for aFile in files:
            if not self._shouldSkipFile(aFile) and (
                    extrasTag in aFile
            ) and aFile.startswith(os.path.splitext(filename)[0] + extrasTag):
                extrasFile = os_path_join(directory, aFile)
                extraItem = ExtrasItem(directory,
                                       extrasFile,
                                       True,
                                       extrasDb=self.extrasDb,
                                       defaultFanArt=self.defaultFanArt)
                extras.append(extraItem)
                # Check if we are only looking for the first entry
                if exitOnFirst is True:
                    break
        return extras
示例#27
0
    def _getThemeFiles(self, directory, extensionOnly=False):
        # First read from the NFO file if it exists
        nfoRead = NfoReader(directory, self.debug_logging_enabled)
        themeFiles = nfoRead.getThemeFiles()

        # Get the theme directories that are referenced and process the data in them
        for nfoDir in nfoRead.getThemeDirs():
            # Do not want the theme keyword if looking at an entire directory
            themeFiles = themeFiles + self._getThemeFiles(nfoDir, True)

        del nfoRead
        log("ThemeFiles: Searching %s for %s" % (directory, Settings.getThemeFileRegEx(directory, extensionOnly, self.audioOnly)), self.debug_logging_enabled)

        # check if the directory exists before searching
        if dir_exists(directory):
            dirs, files = list_dir(directory)
            for aFile in files:
                m = re.search(Settings.getThemeFileRegEx(directory, extensionOnly, self.audioOnly), aFile, re.IGNORECASE)
                if m:
                    path = os_path_join(directory, aFile)
                    log("ThemeFiles: Found match: %s" % path, self.debug_logging_enabled)
                    # Add the theme file to the list
                    themeFiles.append(path)

        return themeFiles
示例#28
0
    def _findTocNcx(self, dirPath):
        tocNcx = None
        dirs, files = xbmcvfs.listdir(dirPath)

        for aFile in files:
            if aFile.lower() == 'toc.ncx':
                # Found the table of contents file
                tocNcx = os_path_join(dirPath, aFile)
                break

        # Now check any of the directories
        for aDir in dirs:
            if tocNcx is None:
                tocNcx = self._findTocNcx(os_path_join(dirPath, aDir))

        return tocNcx
示例#29
0
    def _generateThemeFilelist(self, rawPath):
        # Get the full path with any network alterations
        workingPath = self._getUsablePath(rawPath)

        themeList = self._getThemeFiles(workingPath)

        # If no themes have been found
        if len(themeList) < 1:
            # TV shows stored as ripped disc folders
            if ('VIDEO_TS' in workingPath) or ('BDMV' in workingPath):
                log("ThemeFiles: Found VIDEO_TS or BDMV in path: Correcting the path for DVDR tv shows", self.debug_logging_enabled)
                workingPath = os_path_split(workingPath)[0]
                themeList = self._getThemeFiles(workingPath)
                if len(themeList) < 1:
                    workingPath = os_path_split(workingPath)[0]
                    themeList = self._getThemeFiles(workingPath)
            else:
                # If no theme files were found in this path, look at the parent directory
                workingPath = os_path_split(workingPath)[0]

                # Check for the case where there is the theme forlder settings, we want to
                # check the parent folders themes directory
                if Settings.isThemeDirEnabled():
                    themeDir = os_path_join(workingPath, Settings.getThemeDirectory())
                    themeList = self._getThemeFiles(themeDir)

                # If there are still no themes, just check the parent directory
                if len(themeList) < 1:
                    themeList = self._getThemeFiles(workingPath)

        log("ThemeFiles: Playlist size = %d" % len(themeList), self.debug_logging_enabled)
        log("ThemeFiles: Working Path = %s" % workingPath, self.debug_logging_enabled)

        return themeList
示例#30
0
 def getVOBFile(self):
     # Check to see if the filename actually holds a directory
     # If that is the case, we will only support it being a DVD Directory Image
     # So check to see if the expected file is set
     videoTSDir = os_path_join(self.filename, 'VIDEO_TS')
     if dir_exists(videoTSDir):
         ifoFile = os_path_join(videoTSDir, 'VIDEO_TS.IFO')
         if xbmcvfs.exists(ifoFile):
             return ifoFile
     # Also check for BluRay
     videoBluRayDir = os_path_join(self.filename, 'BDMV')
     if dir_exists(videoBluRayDir):
         dbmvFile = os_path_join(videoBluRayDir, 'index.bdmv')
         if xbmcvfs.exists(dbmvFile):
             return dbmvFile
     return None
示例#31
0
    def _getExistingCoverImage(self):
        # Check if there is a cached version, or a local one on the drive
        fullpathLocalImage, bookExt = os.path.splitext(self.filePath)

        # Store the directory that the file is in, default the the current path
        parentPath = self.filePath

        # Check to see if this is actually a file with an extension
        if (bookExt not in [None, ""]) and (len(bookExt) < 5):
            fullpathLocalImage1 = "%s.jpg" % fullpathLocalImage
            fullpathLocalImage2 = "%s.JPG" % fullpathLocalImage

            if xbmcvfs.exists(fullpathLocalImage1):
                log("AudioBookHandler: Found local cached image %s" % fullpathLocalImage1)
                return fullpathLocalImage1
            if xbmcvfs.exists(fullpathLocalImage2):
                log("AudioBookHandler: Found local cached image %s" % fullpathLocalImage2)
                return fullpathLocalImage2

            # If we reach here, then we were a file, so get the directory part
            parentPath = (os_path_split(self.filePath))[0]

        # Check for a file in the same directory but with the name
        # "cover.jpg" or "folder.jpg
        dirs, files = xbmcvfs.listdir(parentPath)
        for file in files:
            if file.lower() in ['folder.jpg', 'cover.jpg']:
                fullpathLocalImage = os_path_join(parentPath, file)
                log("AudioBookHandler: Found local directory cover %s" % fullpathLocalImage)
                return fullpathLocalImage

        # Check for a cached cover
        return self._getCachedCover(self.fileName)
示例#32
0
    def _getMainCoverLocation(self):
        coverFileName, oldExt = os.path.splitext(self.fileName)
        targetCoverName = "%s.jpg" % coverFileName
        coverTargetName = os_path_join(Settings.getCoverCacheLocation(), targetCoverName)

        log("AudioBookHandler: Cached cover target location is %s" % coverTargetName)
        return coverTargetName
示例#33
0
    def _generateThemeFilelist(self, rawPath):
        # Get the full path with any network alterations
        workingPath = self._getUsablePath(rawPath)

        themeList = self._getThemeFiles(workingPath)

        # If no themes have been found
        if len(themeList) < 1:
            # TV shows stored as ripped disc folders
            if ('VIDEO_TS' in workingPath) or ('BDMV' in workingPath):
                log("ThemeFiles: Found VIDEO_TS or BDMV in path: Correcting the path for DVDR tv shows", self.debug_logging_enabled)
                workingPath = os_path_split(workingPath)[0]
                themeList = self._getThemeFiles(workingPath)
                if len(themeList) < 1:
                    workingPath = os_path_split(workingPath)[0]
                    themeList = self._getThemeFiles(workingPath)
            else:
                # If no theme files were found in this path, look at the parent directory
                workingPath = os_path_split(workingPath)[0]

                # Check for the case where there is the theme forlder settings, we want to
                # check the parent folders themes directory
                if Settings.isThemeDirEnabled():
                    themeDir = os_path_join(workingPath, Settings.getThemeDirectory())
                    themeList = self._getThemeFiles(themeDir)

                # If there are still no themes, just check the parent directory
                if len(themeList) < 1:
                    themeList = self._getThemeFiles(workingPath)

        log("ThemeFiles: Playlist size = %d" % len(themeList), self.debug_logging_enabled)
        log("ThemeFiles: Working Path = %s" % workingPath, self.debug_logging_enabled)

        return themeList
示例#34
0
 def getVOBFile(self):
     # Check to see if the filename actually holds a directory
     # If that is the case, we will only support it being a DVD Directory Image
     # So check to see if the expected file is set
     videoTSDir = os_path_join(self.filename, 'VIDEO_TS')
     if dir_exists(videoTSDir):
         ifoFile = os_path_join(videoTSDir, 'VIDEO_TS.IFO')
         if xbmcvfs.exists(ifoFile):
             return ifoFile
     # Also check for BluRay
     videoBluRayDir = os_path_join(self.filename, 'BDMV')
     if dir_exists(videoBluRayDir):
         dbmvFile = os_path_join(videoBluRayDir, 'index.bdmv')
         if xbmcvfs.exists(dbmvFile):
             return dbmvFile
     return None
示例#35
0
 def __init__(self):
     # Start by getting the database location
     self.configPath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
     self.databasefile = os_path_join(self.configPath, "pinsentry_database.db")
     log("PinSentryDB: Database file location = %s" % self.databasefile)
     # Check to make sure the DB has been created
     self._createDatabase()
示例#36
0
    def loadSavedPhrases(self):
        # Get the location of the speech list file
        configPath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
        speechfile = os_path_join(configPath, "speech.txt")
        log("Speech: Phrases file location = %s" % speechfile)

        phrases = []
        # Check to see if the speech list file exists
        if not xbmcvfs.exists(speechfile):
            # Create a list of pre-defined phrases
            phrases.append(ADDON.getLocalizedString(32221))
            phrases.append(ADDON.getLocalizedString(32222))
            phrases.append(ADDON.getLocalizedString(32226))
            phrases.append('%greet')
            phrases.sort()
        else:
            # Read the phases from the file
            try:
                with open(speechfile, 'r') as file_in:
                    phrases = file_in.readlines()
            except:
                log("Speech: Failed to read lines from file %s" % speechfile,
                    xbmc.LOGERROR)
                log("Speech: %s" % traceback.format_exc(), xbmc.LOGERROR)

        return phrases
示例#37
0
 def __init__(self):
     # Start by getting the database location
     self.configPath = xbmc.translatePath(__addon__.getAddonInfo('profile'))
     self.databasefile = os_path_join(self.configPath, "audiobooks_database.db")
     log("AudioBooksDB: Database file location = %s" % self.databasefile)
     # Check to make sure the DB has been created
     self._createDatabase()
示例#38
0
    def __init__(self, rawPath, pathList=None, videotitle=None, debug_logging_enabled=True, audioOnly=False):
        self.debug_logging_enabled = debug_logging_enabled
        self.forceShuffle = False
        self.doNotShuffle = False
        self.audioOnly = audioOnly
        self.rawPath = rawPath
        if rawPath in [None, ""]:
            self.clear()
        else:
            # Check for the case where there is a custom path set so we need to use
            # the custom location rather than the rawPath
            if Settings.isCustomPathEnabled() and (videotitle not in [None, ""]):
                customRoot = Settings.getCustomPath()
                # Make sure that the path passed in has not already been converted
                if customRoot not in self.rawPath:
                    self.rawPath = os_path_join(customRoot, normalize_string(videotitle))
                    log("ThemeFiles: Setting custom path to %s" % self.rawPath, self.debug_logging_enabled)

            if (pathList is not None) and (len(pathList) > 0):
                self.themeFiles = []
                for aPath in pathList:
                    subThemeList = self._generateThemeFilelistWithDirs(aPath)
                    # add these files to the existing list
                    self.themeFiles = self._mergeThemeLists(self.themeFiles, subThemeList)
                # If we were given a list, then we should shuffle the themes
                # as we don't always want the first path playing first
                self.forceShuffle = True
            else:
                self.themeFiles = self._generateThemeFilelistWithDirs(self.rawPath)

        # Check if we need to handle the ordering for video themes
        if not audioOnly:
            self.doNotShuffle = self._filterForVideoThemesRule()
            self.forceShuffle = False
示例#39
0
文件: speech.py 项目: noba3/KoTos
    def loadSavedPhrases(self):
        # Get the location of the speech list file
        configPath = xbmc.translatePath(__addon__.getAddonInfo('profile'))
        speechfile = os_path_join(configPath, "speech.txt")
        log("Speech: Phrases file location = %s" % speechfile)

        phrases = []
        # Check to see if the speech list file exists
        if not xbmcvfs.exists(speechfile):
            # Create a list of pre-defined phrases
            phrases.append(__addon__.getLocalizedString(32221))
            phrases.append(__addon__.getLocalizedString(32222))
            phrases.append(__addon__.getLocalizedString(32226))
            phrases.append('%greet')
            phrases.sort()
        else:
            # Read the phases from the file
            try:
                file_in = open(speechfile, 'r')
                phrases = file_in.readlines()
                file_in.close()
            except:
                log("Speech: Failed to read lines from file %s" % speechfile, xbmc.LOGERROR)
                log("Speech: %s" % traceback.format_exc(), xbmc.LOGERROR)

        return phrases
示例#40
0
    def _getCachedCover(self, fileName):
        cachedCover = None
        # check if the directory exists before searching
        dirs, files = xbmcvfs.listdir(Settings.getCoverCacheLocation())
        for aFile in files:
            # Get the filename without extension
            coverSrc, ext = os.path.splitext(aFile)

            # Get the name that the cached cover will have been stored as
            targetSrc, bookExt = os.path.splitext(fileName)

            # Make sure both are utf-8 when comparing
            try:
                coverSrc = coverSrc.encode("utf-8")
            except:
                pass
            try:
                targetSrc = targetSrc.encode("utf-8")
            except:
                pass

            if targetSrc == coverSrc:
                cachedCover = os_path_join(Settings.getCoverCacheLocation(), aFile)
                log("AudioBookHandler: Cached cover found: %s" % cachedCover)

        return cachedCover
示例#41
0
    def _getNestedExtrasFiles(self, basepath, filename, exitOnFirst=False, noExtrasDirNeeded=False):
        extras = []
        if dir_exists(basepath):
            dirs, files = xbmcvfs.listdir(basepath)
            for dirname in dirs:
                # Do not search inside Bluray or DVD images
                if (dirname == 'VIDEO_TS') or (dirname == 'BDMV'):
                    continue

                dirpath = os_path_join(basepath, dirname)
                log("VideoExtrasFinder: Nested check in directory: %s" % dirpath)
                if dirname != Settings.getExtrasDirName():
                    log("VideoExtrasFinder: Check directory: %s" % dirpath)
                    extras.extend(self._getExtrasDirFiles(dirpath, exitOnFirst, noExtrasDirNeeded))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
                    extras.extend(self._getExtrasFiles(dirpath, filename, exitOnFirst))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
                    extras.extend(self._getNestedExtrasFiles(dirpath, filename, exitOnFirst, noExtrasDirNeeded))
                    # Check if we are only looking for the first entry
                    if files and (exitOnFirst is True):
                        break
        return extras
示例#42
0
    def _getCachedCover(self, fileName):
        cachedCover = None
        # check if the directory exists before searching
        dirs, files = xbmcvfs.listdir(Settings.getCoverCacheLocation())
        for aFile in files:
            # Get the filename without extension
            coverSrc, ext = os.path.splitext(aFile)

            # Get the name that the cached cover will have been stored as
            targetSrc, bookExt = os.path.splitext(fileName)

            # Make sure both are utf-8 when comparing
            try:
                coverSrc = coverSrc.encode("utf-8")
            except:
                pass
            try:
                targetSrc = targetSrc.encode("utf-8")
            except:
                pass

            if targetSrc == coverSrc:
                cachedCover = os_path_join(Settings.getCoverCacheLocation(), aFile)
                log("AudioBookHandler: Cached cover found: %s" % cachedCover)

        return cachedCover
示例#43
0
 def __init__(self):
     # Start by getting the database location
     self.configPath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
     self.databasefile = os_path_join(self.configPath, "extras_database.db")
     log("ExtrasDB: Database file location = %s" % self.databasefile)
     # Make sure that the database exists if this is the first time
     self.createDatabase()
示例#44
0
 def __init__(self):
     # Start by getting the database location
     self.configPath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
     self.databasefile = os_path_join(self.configPath, "ebooks_database.db")
     log("EbooksDB: Database file location = %s" % self.databasefile)
     # Check to make sure the DB has been created
     self._createDatabase()
示例#45
0
    def _addFilesFromPlaylist(self, playlistFile, directory):
        if (playlistFile is None) or (playlistFile == ""):
            return

        fileExt = os.path.splitext(playlistFile)[1]

        # Check if dealing with a Smart Playlist
        if fileExt == ".xsp":
            # Process the Smart Playlist
            self._addFilesFromSmartPlaylist(playlistFile)
            return

        if ("/" not in playlistFile) and ("\\" not in playlistFile):
            # There is just the filename of the playlist without
            # a path, check if the file is local or if we should
            # read it from the user directory
            # Check if there is an extension on the name
            if fileExt is None or fileExt == "":
                playlistFile = playlistFile + ".m3u"
            localFile = os_path_join(directory, playlistFile)
            if xbmcvfs.exists(localFile):
                # Make it a full path if it is not already
                playlistFile = localFile
            else:
                # default to the music playlist directory if not local
                playlistFile = os_path_join(xbmc.translatePath("special://musicplaylists"), playlistFile)

        log("NfoReader: playlist file = %s" % playlistFile, self.debug_logging_enabled)

        if xbmcvfs.exists(playlistFile):
            # Load the playlist into the Playlist object
            # An exception if thrown if the file does not exist
            try:
                xbmcPlaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
                xbmcPlaylist.load(playlistFile)
                i = 0
                while i < xbmcPlaylist.size():
                    # get the filename from the playlist
                    file = xbmcPlaylist[i].getfilename()
                    i = i + 1
                    if (file is not None) and (file != ""):
                        log("NfoReader: file from playlist = %s" % file, self.debug_logging_enabled)
                        self.themeFiles.append(file)
            except:
                log("NfoReader: playlist file processing error = %s" % playlistFile)
        else:
            log("NfoReader: playlist file not found = %s" % playlistFile, self.debug_logging_enabled)
示例#46
0
    def _getCustomPathDir(self, path):
        # Get the last element of the path
        pathLastDir = os_path_split(path)[1]

        # Create the path with this added
        custPath = Settings.getCustomPath(self.videoType)
        custPath = os_path_join(custPath, pathLastDir)
        log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)

        # Check if this path exists
        if not dir_exists(custPath):
            # If it doesn't exist, check the path before that, this covers the
            # case where there is a TV Show with each season in it's own directory

            # Make sure we have enough elements to actually navigate back up the path
            if len(os_path_split((os_path_split(path)[0]))) < 2:
                log("VideoExtrasFinder: No parent directories to check %s" % path)
            else:
                path2ndLastDir = os_path_split((os_path_split(path)[0]))[1]
                custPath = Settings.getCustomPath(self.videoType)
                custPath = os_path_join(custPath, path2ndLastDir)
                custPath = os_path_join(custPath, pathLastDir)
                log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)
                if not dir_exists(custPath):
                    # If it still does not exist then check just the 2nd to last path
                    custPath = Settings.getCustomPath(self.videoType)
                    custPath = os_path_join(custPath, path2ndLastDir)
                    log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)

            if not dir_exists(custPath):
                # Some systems will store extras in the custom pass using the name
                # of the TV Show of Movie, so try that
                videoName = self.title
                if self.title in [None, ""]:
                    if self.videoType == Settings.TVSHOWS:
                        videoName = xbmc.getInfoLabel("ListItem.TVShowTitle")
                    else:
                        videoName = xbmc.getInfoLabel("ListItem.Title")
                videoName = normalize_string(videoName)
                # Now construct the path using the movie or TV show title
                custPath = Settings.getCustomPath(self.videoType)
                custPath = os_path_join(custPath, videoName)
                log("VideoExtrasFinder: Checking existence of custom path using title %s" % custPath)
                if not dir_exists(custPath):
                    custPath = None

        return custPath
示例#47
0
    def _getCustomPathDir(self, path):
        # Get the last element of the path
        pathLastDir = os_path_split(path)[1]

        # Create the path with this added
        custPath = Settings.getCustomPath(self.videoType)
        custPath = os_path_join(custPath, pathLastDir)
        log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)

        # Check if this path exists
        if not dir_exists(custPath):
            # If it doesn't exist, check the path before that, this covers the
            # case where there is a TV Show with each season in it's own directory

            # Make sure we have enough elements to actually navigate back up the path
            if len(os_path_split((os_path_split(path)[0]))) < 2:
                log("VideoExtrasFinder: No parent directories to check %s" % path)
            else:
                path2ndLastDir = os_path_split((os_path_split(path)[0]))[1]
                custPath = Settings.getCustomPath(self.videoType)
                custPath = os_path_join(custPath, path2ndLastDir)
                custPath = os_path_join(custPath, pathLastDir)
                log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)
                if not dir_exists(custPath):
                    # If it still does not exist then check just the 2nd to last path
                    custPath = Settings.getCustomPath(self.videoType)
                    custPath = os_path_join(custPath, path2ndLastDir)
                    log("VideoExtrasFinder: Checking existence of custom path %s" % custPath)

            if not dir_exists(custPath):
                # Some systems will store extras in the custom pass using the name
                # of the TV Show of Movie, so try that
                videoName = self.title
                if self.title in [None, ""]:
                    if self.videoType == Settings.TVSHOWS:
                        videoName = xbmc.getInfoLabel("ListItem.TVShowTitle")
                    else:
                        videoName = xbmc.getInfoLabel("ListItem.Title")
                videoName = normalize_string(videoName)
                # Now construct the path using the movie or TV show title
                custPath = Settings.getCustomPath(self.videoType)
                custPath = os_path_join(custPath, videoName)
                log("VideoExtrasFinder: Checking existence of custom path using title %s" % custPath)
                if not dir_exists(custPath):
                    custPath = None

        return custPath
示例#48
0
    def extractCoverImage(self):
        log("MobiEBook: Extracting cover for %s" % self.filePath)
        # Get the location that the book is to be extracted to
        extractDir = os_path_join(Settings.getTempLocation(), 'mobi_extracted')

        # Check if the mobi extract directory already exists
        if dir_exists(extractDir):
            try:
                shutil.rmtree(extractDir, True)
            except:
                log("MobiEBook: Failed to delete directory %s" % extractDir)

        # Extract the contents of the book so we can get the cover image
        try:
            kindleunpack.unpackBook(self.filePath, extractDir, None, '2', True)
        except:
            log("MobiEBook: Failed to extract cover for %s with error: %s" % (self.filePath, traceback.format_exc()), xbmc.LOGERROR)

        coverTargetName = None
        if dir_exists(extractDir):
            coverImages = self._findCoverImage(extractDir)

            if len(coverImages) > 0:
                coverImageSrc = coverImages[0]
                log("MobiEBook: Found cover file %s" % coverImageSrc)
                coverFileName, oldExt = os.path.splitext(self.fileName)
                cacheCoverName = "%s.jpg" % coverFileName
                coverTargetName = os_path_join(Settings.getCoverCacheLocation(), cacheCoverName)

                # Now move the file to the covers cache directory
                copy = xbmcvfs.copy(coverImageSrc, coverTargetName)
                if copy:
                    log("MobiEBook: copy successful for %s" % coverTargetName)
                else:
                    log("MobiEBook: copy failed from %s to %s" % (coverImageSrc, coverTargetName))
            else:
                log("MobiEBook: No cover image found for %s" % self.filePath)

            # Now tidy up the extracted data
            try:
                shutil.rmtree(extractDir, True)
            except:
                log("MobiEBook: Failed to tidy up directory %s" % extractDir)
        else:
            log("MobiEBook: Failed to extract Mobi file %s" % self.filePath)

        return coverTargetName
示例#49
0
    def extractCoverImage(self):
        log("MobiEBook: Extracting cover for %s" % self.filePath)
        # Get the location that the book is to be extracted to
        extractDir = os_path_join(Settings.getTempLocation(), 'mobi_extracted')

        # Check if the mobi extract directory already exists
        if dir_exists(extractDir):
            try:
                shutil.rmtree(extractDir, True)
            except:
                log("MobiEBook: Failed to delete directory %s" % extractDir)

        # Extract the contents of the book so we can get the cover image
        try:
            kindleunpack.unpackBook(self.filePath, extractDir, None, '2', True)
        except:
            log("MobiEBook: Failed to extract cover for %s with error: %s" % (self.filePath, traceback.format_exc()), xbmc.LOGERROR)

        coverTargetName = None
        if dir_exists(extractDir):
            coverImages = self._findCoverImage(extractDir)

            if len(coverImages) > 0:
                coverImageSrc = coverImages[0]
                log("MobiEBook: Found cover file %s" % coverImageSrc)
                coverFileName, oldExt = os.path.splitext(self.fileName)
                cacheCoverName = "%s.jpg" % coverFileName
                coverTargetName = os_path_join(Settings.getCoverCacheLocation(), cacheCoverName)

                # Now move the file to the covers cache directory
                copy = xbmcvfs.copy(coverImageSrc, coverTargetName)
                if copy:
                    log("MobiEBook: copy successful for %s" % coverTargetName)
                else:
                    log("MobiEBook: copy failed from %s to %s" % (coverImageSrc, coverTargetName))
            else:
                log("MobiEBook: No cover image found for %s" % self.filePath)

            # Now tidy up the extracted data
            try:
                shutil.rmtree(extractDir, True)
            except:
                log("MobiEBook: Failed to tidy up directory %s" % extractDir)
        else:
            log("MobiEBook: Failed to extract Mobi file %s" % self.filePath)

        return coverTargetName
示例#50
0
    def _loadSpecificDetails(self, includeCover=True):
        # List all the files in the directory, as that will be the chapters
        dirs, files = xbmcvfs.listdir(self.filePath)
        files.sort()

        # Check if the cover image is required
        coverTargetName = None
        if includeCover and (self.coverImage in [None, ""]):
            coverTargetName = self._getMainCoverLocation()

        runningStartTime = 0
        for audioFile in files:
            if not Settings.isPlainAudioFile(audioFile):
                continue

            # Store this audio file in the chapter file list
            fullpath = os_path_join(self.filePath, audioFile)
            self.chapterFiles.append(fullpath)

            # Make the call to ffmpeg to get the details of the chapter
            info = self._runFFmpegCommand(fullpath, coverTargetName)

            # If we needed the cover, then save the details
            if coverTargetName not in [None, ""]:
                if xbmcvfs.exists(coverTargetName):
                    self.coverImage = coverTargetName
                    # Clear the cover image flag so we do not get it again
                    coverTargetName = None

            duration = 0
            chapterTitle = None
            endTime = 0
            if info not in [None, ""]:
                if self.title in [None, ""]:
                    self.title = info['album']
                duration = info['duration']
                chapterTitle = info['title']
                if duration not in [None, 0]:
                    endTime = runningStartTime + info['duration']

            if chapterTitle in [None, ""]:
                # Now generate the name of the chapter from the audio file
                sections = audioFile.split('.')
                sections.pop()
                # Replace the dots with spaces
                chapterTitle = ' '.join(sections)

            detail = {
                'title': chapterTitle,
                'startTime': runningStartTime,
                'endTime': endTime,
                'duration': duration
            }
            self.chapters.append(detail)
            # Set the next start time to be after this chapter
            runningStartTime = endTime

        if runningStartTime > 0:
            self.totalDuration = runningStartTime
示例#51
0
    def createEBookObject(filePath):
        localFilePath = filePath
        removeWhenComplete = False
        if filePath.startswith('smb://') or filePath.startswith('nfs://'):
            try:
                # Copy the file to the local disk
                justFileName = os_path_split(filePath)[-1]
                copiedFile = os_path_join(Settings.getTempLocation(), justFileName)
                copy = xbmcvfs.copy(filePath, copiedFile)
                if copy:
                    log("EBookBase: copy successful for %s" % copiedFile)
                    localFilePath = copiedFile
                    removeWhenComplete = True
                else:
                    log("EBookBase: copy failed from %s to %s" % (filePath, copiedFile))
            except:
                log("EBookBase: Failed to copy file %s to local directory" % filePath)

        elif filePath.startswith('http://') or filePath.startswith('https://'):
            log("EBookBase: Book source is %s" % filePath)
            try:
                justFileName = 'opds.epub'
                if '/mobi/' in filePath:
                    justFileName = 'opds.mobi'
                elif '/pdf/' in filePath:
                    justFileName = 'opds.pdf'
                copiedFile = os_path_join(Settings.getTempLocation(), justFileName)
                fp, h = urllib.urlretrieve(filePath, copiedFile)
                log(h)
                localFilePath = copiedFile
                removeWhenComplete = True
            except:
                log("EBookBase: Failed to download file %s to local directory" % filePath)

        bookType = None
        # Check which type of EBook it is
        if localFilePath.lower().endswith('.epub'):
            bookType = EPubEBook(localFilePath, removeWhenComplete)
        elif localFilePath.lower().endswith('.mobi'):
            bookType = MobiEBook(localFilePath, removeWhenComplete)
        elif localFilePath.lower().endswith('.pdf'):
            bookType = PdfEBook(localFilePath, removeWhenComplete)
        else:
            log("EBookBase: Unknown book type for %s (%s)" % (filePath, localFilePath))

        return bookType
示例#52
0
    def _getAllFilesInDirectory(self, baseDir):
        videoFiles = []
        dirs, files = list_dir(baseDir)

        # Get all the files in the current directory
        for vidFile in files:
            fullPath = os_path_join(baseDir, vidFile)
            videoFiles.append(fullPath)

        # Now check each directory
        if Settings.isFolderNested():
            for aDir in dirs:
                fullPath = os_path_join(baseDir, aDir)
                dirContents = self._getAllFilesInDirectory(fullPath)
                videoFiles = videoFiles + dirContents

        return videoFiles
示例#53
0
    def _getAllFilesInDirectory(self, baseDir):
        videoFiles = []
        dirs, files = list_dir(baseDir)

        # Get all the files in the current directory
        for vidFile in files:
            fullPath = os_path_join(baseDir, vidFile)
            videoFiles.append(fullPath)

        # Now check each directory
        if Settings.isFolderNested():
            for aDir in dirs:
                fullPath = os_path_join(baseDir, aDir)
                dirContents = self._getAllFilesInDirectory(fullPath)
                videoFiles = videoFiles + dirContents

        return videoFiles
示例#54
0
    def createEBookObject(filePath):
        localFilePath = filePath
        removeWhenComplete = False
        if filePath.startswith('smb://') or filePath.startswith('nfs://'):
            try:
                # Copy the file to the local disk
                justFileName = os_path_split(filePath)[-1]
                copiedFile = os_path_join(Settings.getTempLocation(), justFileName)
                copy = xbmcvfs.copy(filePath, copiedFile)
                if copy:
                    log("EBookBase: copy successful for %s" % copiedFile)
                    localFilePath = copiedFile
                    removeWhenComplete = True
                else:
                    log("EBookBase: copy failed from %s to %s" % (filePath, copiedFile))
            except:
                log("EBookBase: Failed to copy file %s to local directory" % filePath)

        elif filePath.startswith('http://') or filePath.startswith('https://'):
            log("EBookBase: Book source is %s" % filePath)
            try:
                justFileName = 'opds.epub'
                if '/mobi/' in filePath:
                    justFileName = 'opds.mobi'
                elif '/pdf/' in filePath:
                    justFileName = 'opds.pdf'
                copiedFile = os_path_join(Settings.getTempLocation(), justFileName)
                fp, h = urllib.urlretrieve(filePath, copiedFile)
                log(h)
                localFilePath = copiedFile
                removeWhenComplete = True
            except:
                log("EBookBase: Failed to download file %s to local directory" % filePath)

        bookType = None
        # Check which type of EBook it is
        if localFilePath.lower().endswith('.epub'):
            bookType = EPubEBook(localFilePath, removeWhenComplete)
        elif localFilePath.lower().endswith('.mobi'):
            bookType = MobiEBook(localFilePath, removeWhenComplete)
        elif localFilePath.lower().endswith('.pdf'):
            bookType = PdfEBook(localFilePath, removeWhenComplete)
        else:
            log("EBookBase: Unknown book type for %s (%s)" % (filePath, localFilePath))

        return bookType
示例#55
0
    def _getThemeFiles(self, directory, extensionOnly=False):
        # First read from the NFO file if it exists
        nfoRead = NfoReader(directory, self.debug_logging_enabled)
        themeFiles = nfoRead.getThemeFiles()

        # Get the theme directories that are referenced and process the data in them
        for nfoDir in nfoRead.getThemeDirs():
            # Do not want the theme keyword if looking at an entire directory
            themeFiles = themeFiles + self._getThemeFiles(nfoDir, True)

        del nfoRead

        themeRegex = Settings.getThemeFileRegEx(directory, extensionOnly, self.audioOnly)
        log("ThemeFiles: Searching %s for %s" % (directory, themeRegex), self.debug_logging_enabled)

        # Make sure that the path does not point to a plugin, as we are checking the
        # file-system for themes, not plugins. This can be the case with Emby
        if "plugin://" in directory:
            log("ThemeFiles: Plugin paths do not support theme files: %s" % directory, self.debug_logging_enabled)
        else:
            # check if the directory exists before searching
            if dir_exists(directory):
                dirs, files = list_dir(directory)
                for aFile in files:
                    m = re.search(themeRegex, aFile, re.IGNORECASE)
                    if m:
                        path = os_path_join(directory, aFile)
                        log("ThemeFiles: Found match: %s" % path, self.debug_logging_enabled)
                        # Add the theme file to the list
                        themeFiles.append(path)
                # Check to see if any themes were found, and if not see if we should try
                # and use a trailer file instead
                if (len(themeFiles) < 1) and (not self.audioOnly) and (not extensionOnly) and Settings.useTrailers():
                    trailerRegEx = Settings.getTrailerFileRegEx()
                    for aFile in files:
                        m = re.search(trailerRegEx, aFile, re.IGNORECASE)
                        if m:
                            path = os_path_join(directory, aFile)
                            log("ThemeFiles: Found trailer match: %s" % path, self.debug_logging_enabled)
                            # Add the trailer file to the list
                            themeFiles.append(path)

        return themeFiles
示例#56
0
    def _saveAlbumArtFromMetadata(self, fullPath):
        dirs, files = xbmcvfs.listdir(self.filePath)

        coverImg = None
        for audioFile in files:
            fullPath = os_path_join(self.filePath, audioFile)
            coverImg = AudioBookHandler._saveAlbumArtFromMetadata(self, fullPath)
            if coverImg not in [None, ""]:
                break
        return coverImg
示例#57
0
    def _saveAlbumArtFromMetadata(self, fullPath):
        dirs, files = xbmcvfs.listdir(self.filePath)

        coverImg = None
        for audioFile in files:
            fullPath = os_path_join(self.filePath, audioFile)
            coverImg = AudioBookHandler._saveAlbumArtFromMetadata(self, fullPath)
            if coverImg not in [None, ""]:
                break
        return coverImg
示例#58
0
    def getPlatformLibFiles(parentDir):
        if parentDir in [None, ""]:
            return None

        log("FFMpegLib: Looking for libraries in %s" % parentDir)
        libLocation = {}

        # Check if the directory exists
        if dir_exists(parentDir):
            # List the contents of the directory
            dirs, files = xbmcvfs.listdir(parentDir)
            for aFile in files:
                if 'avutil' in aFile:
                    libLocation['avutil'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avutil library: %s" %
                        libLocation['avutil'])
                elif 'swresample' in aFile:
                    libLocation['swresample'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found swresample library: %s" %
                        libLocation['swresample'])
                elif 'avcodec' in aFile:
                    libLocation['avcodec'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avcodec library: %s" %
                        libLocation['avcodec'])
                elif 'avformat' in aFile:
                    libLocation['avformat'] = os_path_join(parentDir, aFile)
                    log("FFMpegLib: Found avformat library: %s" %
                        libLocation['avformat'])
        else:
            log("FFMpegLib: Directory not found %s" % parentDir)

        # Make sure we found all of the libraries
        if len(libLocation) < 4:
            return None

        # Check if this is version 3 of ffmpeg as things are slightly different
        if '-55' in libLocation['avutil']:
            global FFMPEG_VERSION
            FFMPEG_VERSION = 3

        return libLocation
示例#59
0
 def _getNfoThumb(self, nfoXml):
     # Get the thumbnail
     thumbnail = nfoXml.findtext('thumb')
     if (thumbnail is not None) and (thumbnail != ""):
         # Found the thumb entry, check if this is a local path
         # which just has a filename, this is the case if there are
         # no forward slashes and no back slashes
         if thumbnail.startswith('..') or (("/" not in thumbnail) and ("\\" not in thumbnail)):
             thumbnail = os_path_join(self.directory, thumbnail)
     else:
         thumbnail = None
     return thumbnail
示例#60
0
 def _getNfoFanart(self, nfoXml):
     # Get the fanart
     fanart = nfoXml.findtext('fanart')
     if (fanart is not None) and (fanart != ""):
         # Found the fanart entry, check if this is a local path
         # which just has a filename, this is the case if there are
         # no forward slashes and no back slashes
         if fanart.startswith('..') or (("/" not in fanart) and ("\\" not in fanart)):
             fanart = os_path_join(self.directory, fanart)
     else:
         fanart = None
     return fanart