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
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
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 __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 __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)
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
def __init__(self): ThemeLibrary.__init__(self) # Set up the addon directories if they do not already exist if not dir_exists( xbmc.translatePath('special://profile/addon_data/%s' % ADDON_ID).decode("utf-8")): xbmcvfs.mkdir( xbmc.translatePath('special://profile/addon_data/%s' % ADDON_ID).decode("utf-8")) self.tvtunesUploadRecord = xbmc.translatePath( 'special://profile/addon_data/%s/tvtunesUpload.xml' % ADDON_ID).decode("utf-8") # Records if the entire upload system is disabled self.uploadsDisabled = False self.isVideoEnabled = True self.isAudioEnabled = True self.isTvShowsEnabled = True self.isMoviesEnabled = True self.skipMultipleThemes = False self.ftpArg = None self.userArg = None self.passArg = None self.uploadRecord = None
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
def __init__(self): ThemeLibrary.__init__(self) # Set up the addon directories if they do not already exist if not dir_exists(xbmc.translatePath('special://profile/addon_data/%s' % ADDON_ID).decode("utf-8")): xbmcvfs.mkdir(xbmc.translatePath('special://profile/addon_data/%s' % ADDON_ID).decode("utf-8")) self.tvtunesUploadRecord = xbmc.translatePath('special://profile/addon_data/%s/tvtunesUpload.xml' % ADDON_ID).decode("utf-8") # Records if the entire upload system is disabled self.uploadsDisabled = False self.isVideoEnabled = True self.isAudioEnabled = True self.isTvShowsEnabled = True self.isMoviesEnabled = True self.ftpArg = None self.userArg = None self.passArg = None self.tvShowAudioExcludes = [] self.movieAudioExcludes = [] self.tvShowVideoExcludes = [] self.movieVideoExcludes = [] self.uploadRecord = None
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) # 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(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
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))
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
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
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
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
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
def __init__(self): # Set up the addon directories if they do not already exist if not dir_exists(xbmc.translatePath('special://profile/addon_data/%s' % __addonid__).decode("utf-8")): xbmcvfs.mkdir(xbmc.translatePath('special://profile/addon_data/%s' % __addonid__).decode("utf-8")) self.tvtunesUploadRecord = xbmc.translatePath('special://profile/addon_data/%s/tvtunesUpload.xml' % __addonid__).decode("utf-8") # Records if the entire upload system is disabled self.uploadsDisabled = False self.isEmbyEnabled = True self.isVideoEnabled = True self.isAudioEnabled = True self.isTvShowsEnabled = True self.isMoviesEnabled = True self.ftpArg = None self.userArg = None self.passArg = None self.tvShowAudioExcludes = [] self.movieAudioExcludes = [] self.tvShowVideoExcludes = [] self.movieVideoExcludes = [] # Load all of the config settings self.loadUploadConfig() self.uploadRecord = None # Check if the file exists, if it does read it in if xbmcvfs.exists(self.tvtunesUploadRecord): try: recordFile = xbmcvfs.File(self.tvtunesUploadRecord, 'r') recordFileStr = recordFile.read() recordFile.close() self.uploadRecord = ET.ElementTree(ET.fromstring(recordFileStr)) except: log("UploadThemes: Failed to read in file %s" % self.tvtunesUploadRecord, xbmc.LOGERROR) log("UploadThemes: %s" % traceback.format_exc(), xbmc.LOGERROR) else: # <tvtunesUpload machineid="XXXXXXXXX"> # <tvshows></tvshows> # <movies></movies> # </tvtunesUpload> try: root = ET.Element('tvtunesUpload') root.attrib['machineid'] = Settings.getTvTunesId() tvshows = ET.Element('tvshows') movies = ET.Element('movies') root.extend((tvshows, movies)) self.uploadRecord = ET.ElementTree(root) except: log("UploadThemes: Failed to create XML Content %s" % traceback.format_exc(), xbmc.LOGERROR)
def _getPlaylist(self): playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() # Check if we are showing all the videos in a given folder if Settings.isFolderSelection(): videosFolder = Settings.getScreensaverFolder() if (videosFolder is None): videosFolder == "" # Check if we are dealing with a Folder of videos if videosFolder != "" and dir_exists(videosFolder): dirs, files = list_dir(videosFolder) # Now shuffle the playlist to ensure that if there are more # than one video a different one starts each time random.shuffle(files) for vidFile in files: fullPath = os_path_join(videosFolder, vidFile) log("Screensaver video in directory is: %s" % fullPath) playlist.add(fullPath) else: # Must be dealing with a single file videoFile = Settings.getScreensaverVideo() if (videoFile is None): videoFile == "" # Check to make sure the screensaver video file exists if (videoFile != "") and xbmcvfs.exists(videoFile): log("Screensaver video is: %s" % videoFile) playlist.add(videoFile) # If there are no videos in the playlist yet, then display an error if playlist.size() < 1: errorLocation = Settings.getScreensaverVideo() if Settings.isFolderSelection(): errorLocation = Settings.getScreensaverFolder() log("No Screensaver file set or not valid %s" % errorLocation) cmd = 'XBMC.Notification("{0}", "{1}", 5, "{2}")'.format( __addon__.getLocalizedString(32300).encode('utf-8'), errorLocation, __icon__) xbmc.executebuiltin(cmd) return None return playlist
def _getPlaylist(self): playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() # Check if we are showing all the videos in a given folder if Settings.isFolderSelection(): videosFolder = Settings.getScreensaverFolder() if (videosFolder is None): videosFolder == "" # Check if we are dealing with a Folder of videos if videosFolder != "" and dir_exists(videosFolder): dirs, files = list_dir(videosFolder) # Now shuffle the playlist to ensure that if there are more # than one video a different one starts each time random.shuffle(files) for vidFile in files: fullPath = os_path_join(videosFolder, vidFile) log("Screensaver video in directory is: %s" % fullPath) playlist.add(fullPath) else: # Must be dealing with a single file videoFile = Settings.getScreensaverVideo() if (videoFile is None): videoFile == "" # Check to make sure the screensaver video file exists if (videoFile != "") and xbmcvfs.exists(videoFile): log("Screensaver video is: %s" % videoFile) playlist.add(videoFile) # If there are no videos in the playlist yet, then display an error if playlist.size() < 1: errorLocation = Settings.getScreensaverVideo() if Settings.isFolderSelection(): errorLocation = Settings.getScreensaverFolder() log("No Screensaver file set or not valid %s" % errorLocation) cmd = 'XBMC.Notification("{0}", "{1}", 5, "{2}")'.format(__addon__.getLocalizedString(32300).encode('utf-8'), errorLocation, __icon__) xbmc.executebuiltin(cmd) return None return playlist
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
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
def getChapterDetails(self): log("MobiEBook: Extracting chapter list 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 unpack book for %s with error: %s" % (self.filePath, traceback.format_exc()), xbmc.LOGERROR) chapterDetails = [] if dir_exists(extractDir): tocNcx = self._findTocNcx(extractDir) if tocNcx not in [None, ""]: log("MobiEBook: TOC file found: %s" % tocNcx) # Now we have the TOC file, we need to parse it, we already have # a tool for that, as it is the ePub format try: # Read the contents of the TOC file into a string tocFile = xbmcvfs.File(tocNcx, 'r') tocStr = tocFile.read() tocFile.close() # Now load it into the parser toc = epub.ncx.parse_toc(tocStr) # Get all the chapters for navPoint in toc.nav_map.nav_point: # Get each of the chapter labels for aLabelGroup in navPoint.labels: if aLabelGroup not in [None, ""]: for aLabel in aLabelGroup: if aLabel not in [None, ""]: log("MobiEBook: Adding chapter %s with src %s" % (aLabel, navPoint.src)) detail = {'title': aLabel.encode("utf-8"), 'link': navPoint.src} chapterDetails.append(detail) # Only need the first string for this label group break del toc except: log("MobiEBook: Failed to process TOC %s with error: %s" % (tocNcx, traceback.format_exc()), xbmc.LOGERROR) else: log("MobiEBook: Failed to find TOC file") # Check if we have any chapters, if there are none, then we should show the whole book if (len(chapterDetails) < 1) or (not Settings.onlyShowWholeBookIfChapters()): htmlFiles = self._findHtmlFiles(extractDir) # Check if there are any html files if len(htmlFiles) > 0: keyHtmlFile = None for htmlFile in htmlFiles: if htmlFile.endswith('book.html'): keyHtmlFile break if keyHtmlFile is None: keyHtmlFile = htmlFiles[0] detail = {'title': ADDON.getLocalizedString(32016), 'link': keyHtmlFile} chapterDetails.insert(0, detail) # 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 chapterDetails
def getChapterContents(self, chapterLink): log("MobiEBook: Getting chapter contents for %s" % chapterLink) # Find out the name of the page that this chapter is stored in sections = chapterLink.split('#') bookFileName = None chapterStartFlag = None if len(sections) > 0: bookFileName = sections[0] if len(sections) > 1: chapterStartFlag = sections[1] # Get the content of the chapter, this will be in HTML chapterContent = "" # 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 chapter contents try: kindleunpack.unpackBook(self.filePath, extractDir, None, '2', True) except: log("MobiEBook: Failed to unpack book for %s with error: %s" % (self.filePath, traceback.format_exc()), xbmc.LOGERROR) # Find the file containing the book contents bookFileLocation = self._findBookFile(extractDir, bookFileName) bookContents = "" if bookFileLocation not in [None, ""]: # Read the contents of the file try: # Read the contents of the book file into a string bookFile = xbmcvfs.File(bookFileLocation, 'r') bookContents = bookFile.read() bookFile.close() except: log("MobiEBook: Failed to read contents of book %s with error: %s" % (bookFileName, traceback.format_exc()), xbmc.LOGERROR) else: log("MobiEBook: Failed to find book content file %s" % bookFileName) # Cleanup the extract directory if dir_exists(extractDir): try: shutil.rmtree(extractDir, True) except: log("MobiEBook: Failed to delete directory %s" % extractDir) chapterContent = "" if bookContents not in [None, ""]: if chapterStartFlag is not None: # Split out the chapter (For now just add the whole book) # Split based on page markers pageBreaks = bookContents.split('<mbp:pagebreak/>') anchorHtml = "<a id=\"%s\"" % chapterStartFlag # Find which section contains this anchor for page in pageBreaks: if anchorHtml in page.decode("utf-8"): log("MobiEBook: Found page for chapter marker %s" % chapterStartFlag) chapterContent = self._mobiHtmlParsing(page) break else: log("MobiEBook: Chapter start flag, showing whole book") chapterContent = self._mobiHtmlParsing(bookContents) if chapterContent not in [None, ""]: chapterContent = self.convertHtmlIntoKodiText(chapterContent) return chapterContent
# Import the common settings from settings import Settings from settings import log from settings import dir_exists from settings import os_path_join ######################### # Main ######################### if __name__ == '__main__': log("AudioBookCoverCleanup: Cover cache cleanup called (version %s)" % __version__) coverCache = Settings.getCoverCacheLocation() if dir_exists(coverCache): try: log("AudioBookCoverCleanup: Checking cache files %s" % coverCache) # Remove the jpg and png files in the directory first dirs, files = xbmcvfs.listdir(coverCache) for aFile in files: log("AudioBookCoverCleanup: Removing file %s" % aFile) if aFile.endswith('.jpg') or aFile.endswith('.jpeg') or aFile.endswith('.png'): coverFile = os_path_join(coverCache, aFile) xbmcvfs.delete(coverFile) # Now remove the actual directory xbmcvfs.rmdir(coverCache) except: log("AudioBookCoverCleanup: %s" % traceback.format_exc(), xbmc.LOGERROR)
################################## # Main of the TvTunes Service ################################## if __name__ == "__main__": log("StoreReg: Starting TvTunes Store Registration %s" % __addon__.getAddonInfo("version")) # Prompt the user for the location of the registration file fileLocation = xbmcgui.Dialog().browseSingle(1, __addon__.getLocalizedString(32116), "files") if fileLocation not in ["", None]: log("StoreReg: Registration file selected: %s" % fileLocation) # Make sure the target directory exists if not dir_exists(xbmc.translatePath("special://profile/addon_data/%s" % __addonid__).decode("utf-8")): xbmcvfs.mkdir(xbmc.translatePath("special://profile/addon_data/%s" % __addonid__).decode("utf-8")) # Get the location the file is to be copied to tvtunesStoreFileName = xbmc.translatePath( "special://profile/addon_data/%s/tvtunes-store-reg.xml" % __addonid__ ).decode("utf-8") log("StoreReg: Target location of registration file: %s" % tvtunesStoreFileName) # Copy the file into the target location copy = xbmcvfs.copy(fileLocation, tvtunesStoreFileName) if copy: log("StoreReg: Registration file copy successful") else: log("StoreReg: Registration file copy failed")
def _loadNfoInfo(self, directory): # Find out the name of the NFO file nfoFileName = os_path_join(directory, "tvtunes.nfo") # If this is a plugin path, then don't try and get the NFO file if "plugin://" in nfoFileName: log("NfoReader: Plugin paths do not support NFO files: %s" % nfoFileName, self.debug_logging_enabled) return log("NfoReader: Searching for NFO file: %s" % nfoFileName, self.debug_logging_enabled) # Return False if file does not exist if not xbmcvfs.exists(nfoFileName): log("NfoReader: No NFO file found: %s" % nfoFileName, self.debug_logging_enabled) return False returnValue = False checkThemeExists = False try: # Need to first load the contents of the NFO file into # a string, this is because the XML File Parse option will # not handle formats like smb:// nfoFile = xbmcvfs.File(nfoFileName, 'r') nfoFileStr = nfoFile.read() nfoFile.close() # Create an XML parser nfoXml = ET.ElementTree(ET.fromstring(nfoFileStr)) rootElement = nfoXml.getroot() log("NfoReader: Root element is = %s" % rootElement.tag, self.debug_logging_enabled) # Check which format if being used if rootElement.tag == "tvtunes": log("NfoReader: TvTunes format NFO detected", self.debug_logging_enabled) # <tvtunes> # <file>theme.mp3</file> # <directory>c:\my\themes</directory> # <playlistfile>playlist.m3u</playlistfile> # <excludeFromScreensaver/> # </tvtunes> # There could be multiple file entries, so loop through all of them for fileElem in nfoXml.findall('file'): file = None if fileElem is not None: file = fileElem.text if (file is not None) and (file != ""): if file.startswith('..') or (("/" not in file) and ("\\" not in file)): # Make it a full path if it is not already file = os_path_join(directory, file) log("NfoReader: file = %s" % file, self.debug_logging_enabled) self.themeFiles.append(file) # There could be multiple directory entries, so loop through all of them for dirElem in nfoXml.findall('directory'): dir = None if dirElem is not None: dir = dirElem.text if (dir is not None) and (dir != ""): if dir.startswith('..') or (("/" not in dir) and ("\\" not in dir)): # Make it a full path if it is not already dir = os_path_join(directory, dir) log("NfoReader: directory = %s" % dir, self.debug_logging_enabled) self.themeDirs.append(dir) # Check for the playlist files for playlistFileElem in nfoXml.findall('playlistfile'): playlistFile = None if playlistFileElem is not None: playlistFile = playlistFileElem.text self._addFilesFromPlaylist(playlistFile, directory) # Check if this directory should be excluded from the screensaver for playlistFileElem in nfoXml.findall('excludeFromScreensaver'): self.excludeFromScreensaver = True # Check if there may be theme paths that do not exist and we should # check each theme to see if they they can be accessed for playlistFileElem in nfoXml.findall('checkThemeExists'): checkThemeExists = True returnValue = True else: self.displayName = None self.orderKey = None log("NfoReader: Unknown NFO format", self.debug_logging_enabled) del nfoXml except: log("NfoReader: Failed to process NFO: %s" % nfoFileName, True, xbmc.LOGERROR) log("NfoReader: %s" % traceback.format_exc(), True, xbmc.LOGERROR) returnValue = False # Not that the entire NFO file has been read, see if we need to verify # that each of the themes exists if checkThemeExists: # Check the theme files to make sure they all exist existingThemeFiles = [] for nfoThemeFile in self.themeFiles: if xbmcvfs.exists(nfoThemeFile): existingThemeFiles.append(nfoThemeFile) else: log("NfoReader: File does not exists, removing %s" % nfoThemeFile, self.debug_logging_enabled) self.themeFiles = existingThemeFiles # Check the theme directories to make sure they all exist existingThemeDir = [] for nfoThemeDir in self.themeDirs: if dir_exists(nfoThemeDir): existingThemeDir.append(nfoThemeDir) else: log("NfoReader: Directory does not exists, removing %s" % nfoThemeDir, self.debug_logging_enabled) self.themeDirs = existingThemeDir return returnValue
def _getPlaylist(self): playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) # Note: The playlist clear option seems to creat all playlist settings, # so will remove the repeat settings on a playlist that is currently playing, # not just this instance - a bit nasty, but not much we can do about it playlist.clear() # Check to see if we should be using a video from the schedule scheduleEntry = self.scheduler.getScheduleEntry() if scheduleEntry != -1: # There is an item scheduled, so check to see if the item has actually changed if scheduleEntry == self.currentScheduleItem: return None # Set the entry we are about to play self.currentScheduleItem = scheduleEntry # Get the actual video file that should be played scheduledVideo = self.scheduler.getScheduleVideo(scheduleEntry) # Do a quick check to see if the video exists if xbmcvfs.exists(scheduledVideo): log("Screensaver video for scheduled item %d is: %s" % (scheduleEntry, scheduledVideo)) playlist.add(scheduledVideo) # Check if we are showing all the videos in a given folder elif Settings.isFolderSelection(): videosFolder = Settings.getScreensaverFolder() # Check if we are dealing with a Folder of videos if videosFolder not in [None, ""]: if dir_exists(videosFolder): self.currentScheduleItem = -1 files = self._getAllFilesInDirectory(videosFolder) # Now shuffle the playlist to ensure that if there are more # than one video a different one starts each time random.shuffle(files) for vidFile in files: log("Screensaver video in directory is: %s" % vidFile) playlist.add(vidFile) else: # Must be dealing with a single file videoFile = Settings.getScreensaverVideo() # Check to make sure the screensaver video file exists if videoFile not in [None, ""]: if xbmcvfs.exists(videoFile): self.currentScheduleItem = -1 log("Screensaver video is: %s" % videoFile) playlist.add(videoFile) # If there are no videos in the playlist yet, then display an error if playlist.size() < 1: errorLocation = Settings.getScreensaverVideo() if Settings.isFolderSelection(): errorLocation = Settings.getScreensaverFolder() log("No Screensaver file set or not valid %s" % errorLocation) cmd = 'Notification("{0}", "{1}", 3000, "{2}")'.format(__addon__.getLocalizedString(32300).encode('utf-8'), errorLocation, __icon__) xbmc.executebuiltin(cmd) return None return playlist
def _getPlaylist(self): playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) # Note: The playlist clear option seems to creat all playlist settings, # so will remove the repeat settings on a playlist that is currently playing, # not just this instance - a bit nasty, but not much we can do about it playlist.clear() # Check to see if we should be using a video from the schedule scheduleEntry = self.scheduler.getScheduleEntry() if scheduleEntry != -1: # There is an item scheduled, so check to see if the item has actually changed if scheduleEntry == self.currentScheduleItem: return None # Set the entry we are about to play self.currentScheduleItem = scheduleEntry # Get the actual video file that should be played scheduledVideo = self.scheduler.getScheduleVideo(scheduleEntry) # Do a quick check to see if the video exists if xbmcvfs.exists(scheduledVideo): log("Screensaver video for scheduled item %d is: %s" % (scheduleEntry, scheduledVideo)) playlist.add(scheduledVideo) # Check if we are showing all the videos in a given folder elif Settings.isFolderSelection(): videosFolder = Settings.getScreensaverFolder() # Check if we are dealing with a Folder of videos if videosFolder not in [None, ""]: if dir_exists(videosFolder): self.currentScheduleItem = -1 files = self._getAllFilesInDirectory(videosFolder) # Now shuffle the playlist to ensure that if there are more # than one video a different one starts each time random.shuffle(files) for vidFile in files: log("Screensaver video in directory is: %s" % vidFile) playlist.add(vidFile) else: # Must be dealing with a single file videoFile = Settings.getScreensaverVideo() # Check to make sure the screensaver video file exists if videoFile not in [None, ""]: if xbmcvfs.exists(videoFile): self.currentScheduleItem = -1 log("Screensaver video is: %s" % videoFile) playlist.add(videoFile) # If there are no videos in the playlist yet, then display an error if playlist.size() < 1: errorLocation = Settings.getScreensaverVideo() if Settings.isFolderSelection(): errorLocation = Settings.getScreensaverFolder() log("No Screensaver file set or not valid %s" % errorLocation) cmd = 'Notification("{0}", "{1}", 3000, "{2}")'.format( __addon__.getLocalizedString(32300).encode('utf-8'), errorLocation, __icon__) xbmc.executebuiltin(cmd) return None return playlist
# Import the common settings from settings import Settings from settings import log from settings import dir_exists from settings import os_path_join ######################### # Main ######################### if __name__ == '__main__': log("AudioBookCoverCleanup: Cover cache cleanup called (version %s)" % __version__) coverCache = Settings.getCoverCacheLocation() if dir_exists(coverCache): try: log("AudioBookCoverCleanup: Checking cache files %s" % coverCache) # Remove the jpg and png files in the directory first dirs, files = xbmcvfs.listdir(coverCache) for aFile in files: log("AudioBookCoverCleanup: Removing file %s" % aFile) if aFile.endswith('.jpg') or aFile.endswith( '.jpeg') or aFile.endswith('.png'): coverFile = os_path_join(coverCache, aFile) xbmcvfs.delete(coverFile) # Now remove the actual directory xbmcvfs.rmdir(coverCache) except: