// One time upgrades tasks for file information
        public static void PerformFileInformationUpgradeCheck()
        {
            Version ver = Assembly.GetExecutingAssembly().GetName().Version;

            logger.Info("Performing File Information Upgrade Check...");

            float count = 0;
            List <DBLocalMedia> files = DBLocalMedia.GetAll();
            float total = files.Count;

            foreach (DBLocalMedia currFile in files)
            {
                if (MaintenanceProgress != null)
                {
                    MaintenanceProgress("", (int)(count * 100 / total));
                }
                count++;

                // Skip uncommited files
                if (currFile.ID == null)
                {
                    continue;
                }


                // commit file
                currFile.Commit();
            }

            if (MaintenanceProgress != null)
            {
                MaintenanceProgress("", 100);
            }
        }
        // Loops through all local files in the system and removes anything that's invalid.
        public static void RemoveInvalidFiles()
        {
            logger.Info("Checking for invalid file entries in the database.");

            float count = 0;
            List <DBLocalMedia> files = DBLocalMedia.GetAll();
            float total = files.Count;

            int cleaned = 0;

            foreach (DBLocalMedia currFile in files)
            {
                if (MaintenanceProgress != null)
                {
                    MaintenanceProgress("", (int)(count * 100 / total));
                }
                count++;

                // Skip previously deleted files
                if (currFile.ID == null)
                {
                    continue;
                }

                // Remove Orphan Files
                if (currFile.AttachedmvCentral.Count == 0 && !currFile.Ignored)
                {
                    logger.Info("Removing: {0} (orphan)", currFile.FullPath);
                    currFile.Delete();
                    cleaned++;
                    continue;
                }

                // remove files without an import path
                if (currFile.ImportPath == null || currFile.ImportPath.ID == null)
                {
                    logger.Info("Removing: {0} (no import path)", currFile.FullPath);
                    currFile.Delete();
                    cleaned++;
                    continue;
                }

                // Remove entries from the database that have their file removed
                if (currFile.IsRemoved)
                {
                    logger.Info("Removing: {0} (file is removed)", currFile.FullPath);
                    currFile.Delete();
                    cleaned++;
                }
            }

            logger.Info("Removed {0} file entries.", cleaned.ToString());
            if (MaintenanceProgress != null)
            {
                MaintenanceProgress("", 100);
            }

            // Remove Orphan albums
            cleaned = 0;
            List <DBAlbumInfo> albumObjectList = DBAlbumInfo.GetAll();

            foreach (DBAlbumInfo albumObject in albumObjectList)
            {
                if (albumObject.Album.Trim() == string.Empty)
                {
                    albumObject.Album = "Unknow Album";
                    albumObject.Commit();
                }
                List <DBTrackInfo> mvs = DBTrackInfo.GetEntriesByAlbum(albumObject);
                if (mvs.Count == 0)
                {
                    logger.Info("Removing: {0} (albuminfo orphan)", albumObject.Album);
                    albumObject.Delete();
                    cleaned++;
                }
            }
            logger.Info("Removed {0} Album orphan entries.", cleaned.ToString());
            if (MaintenanceProgress != null)
            {
                MaintenanceProgress("", 100);
            }

            // Remove Orphan artist
            cleaned = 0;
            List <DBArtistInfo> allArtistList = DBArtistInfo.GetAll();

            foreach (DBArtistInfo artist in allArtistList)
            {
                List <DBTrackInfo> mvs = DBTrackInfo.GetEntriesByArtist(artist);
                if (mvs.Count == 0)
                {
                    logger.Info("Removing: {0} (artistinfo orphan)", artist.Artist);
                    artist.Delete();
                    cleaned++;
                }
            }
            logger.Info("Removed {0} Artist orphan entries.", cleaned.ToString());
            if (MaintenanceProgress != null)
            {
                MaintenanceProgress("", 100);
            }
        }
        // Update System Managed Import Paths
        public static void UpdateImportPaths()
        {
            // remove obsolete or invalid import paths
            foreach (DBImportPath currPath in DBImportPath.GetAll())
            {
                if (currPath.Directory == null)
                {
                    currPath.Delete();
                }

                if (currPath.InternallyManaged && currPath.GetDriveType() == DriveType.NoRootDirectory)
                {
                    currPath.Delete();
                    logger.Info("Removed system managed import path: {0} (drive does not exist)", currPath.FullPath);
                }

                // Automatically remove import paths that were marked as replaced and don't have any related media (left)
                if (currPath.Replaced)
                {
                    // get related local media (we append % so we get all paths starting with the import path)
                    List <DBLocalMedia> attachedLocalMedia = DBLocalMedia.GetAll(currPath.FullPath + "%");
                    if (attachedLocalMedia.Count == 0)
                    {
                        currPath.Delete();
                        logger.Info("Removed import path: {0} (was marked as replaced and doesn't have any related files)", currPath.FullPath);
                    }
                }
            }

            float count = 0;
            float total = DriveInfo.GetDrives().Length;

            bool   daemonEnabled = mvCentralCore.MediaPortalSettings.GetValueAsBool("daemon", "enabled", false);
            string virtualDrive  = mvCentralCore.MediaPortalSettings.GetValueAsString("daemon", "drive", "?:");

            // Get all drives
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (MaintenanceProgress != null)
                {
                    MaintenanceProgress("", (int)(count * 100 / total));
                }
                count++;

                // Add the import path if it does not exist and
                // is not marked virtual by MediaPortal.
                DBImportPath importPath = DBImportPath.Get(drive.Name);
                bool         isVirtual  = drive.Name.StartsWith(virtualDrive, StringComparison.OrdinalIgnoreCase) && daemonEnabled;
                bool         isCDRom    = (drive.DriveType == DriveType.CDRom);

                if (importPath.ID != null)
                {
                    // Remove an system managed path if for any reason it's not of type CDRom
                    if (!isCDRom && importPath.InternallyManaged)
                    {
                        importPath.Delete();
                        logger.Info("Removed system managed import path: {0} (drive type has changed)", importPath.FullPath);
                        continue;
                    }

                    // Remove an existing path if it's defined as the virtual drive
                    if (isVirtual)
                    {
                        importPath.Delete();
                        logger.Info("Removed import path: {0} (drive is marked as virtual)", importPath.FullPath);
                        continue;
                    }

                    // Update an existing import path to a system managed import path
                    // if the drive type is CDRom but the system flag isn't set
                    if (isCDRom && !importPath.InternallyManaged)
                    {
                        importPath.InternallyManaged = true;
                        importPath.Commit();
                        logger.Info("{0} was updated to a system managed import path.", importPath.FullPath);
                    }
                }
                else
                {
                    if (isCDRom && !isVirtual)
                    {
                        importPath.InternallyManaged = true;
                        importPath.Commit();
                        logger.Info("Added system managed import path: {0}", importPath.FullPath);
                    }
                }
            }

            if (MaintenanceProgress != null)
            {
                MaintenanceProgress("", 100);
            }
        }
Ejemplo n.º 4
0
        public List <DBLocalMedia> GetLocalMedia(bool returnOnlyNew)
        {
            logger.Debug("Scanning: {0}", Directory.FullName);

            // default values
            string volume = string.Empty;
            string label  = string.Empty;
            string serial = string.Empty;

            // validate the import path
            if (!_replaced && this.IsAvailable)
            {
                if (!this.IsUnc)
                {
                    // Logical volume (can be a mapped network share)
                    int retry = 0;
                    while (serial == string.Empty)
                    {
                        // Grab information for this logical volume
                        DriveInfo driveInfo = Directory.GetDriveInfo();
                        if (driveInfo != null && driveInfo.IsReady)
                        {
                            // get the volume properties
                            volume = driveInfo.GetDriveLetter();
                            label  = driveInfo.VolumeLabel;
                            serial = driveInfo.GetVolumeSerial();
                            logger.Debug("Drive='{0}', Label='{1}', Serial='{2}'", volume, label, serial);
                        }

                        // check if the serial is empty
                        // logical volumes SHOULD have a serial number or something went wrong
                        if (serial == string.Empty)
                        {
                            // If we tried 3 times already then we should report a failure
                            if (retry == 3)
                            {
                                logger.Error("Canceled scan for '{0}': Could not get required volume information.", Directory.FullName);
                                return(null);
                            }

                            // up the retry count and wait for 1 second
                            retry++;
                            Thread.Sleep(1000);
                            logger.Debug("Retrying: {1} ({0})", Directory.FullName, retry);
                        }
                    }
                } // todo: for UNC paths we could consider using the host part of the UNC path as the MediaLabel (ex. '//SomeHost/../..' => 'SomeHost')
            }
            else
            {
                if (this.IsRemovable)
                {
                    if (this.IsUnc)
                    {
                        // network share
                        logger.Info("Skipping scan for '{0}': the share is offline.", Directory.FullName);
                    }
                    else if (this.IsOpticalDrive)
                    {
                        // optical drive
                        logger.Info("Skipping scan for '{0}': the drive is empty.", Directory.FullName);
                    }
                    else
                    {
                        // all other removable paths
                        logger.Info("Skipping scan for '{0}': the volume is disconnected.", Directory.FullName);
                    }
                }
                else
                {
                    logger.Error("Scan for '{0}' was cancelled because the import path is not available.", Directory.FullName);
                }

                // returning nothing
                return(null);
            }

            // Grab the list of files and validate them
            List <DBLocalMedia> rtn = new List <DBLocalMedia>();

            try {
                List <FileInfo> fileList = null;

                // When the option to ignore interactive content is enabled (applies to optical drives that are internally managed)
                // we first check for known video formats (DVD, Bluray etc..) before we are going to scan for all files on the disc.
                if (mvCentralCore.Settings.IgnoreInteractiveContentOnVideoDisc && IsOpticalDrive && InternallyManaged)
                {
                    string videoPath = VideoUtility.GetVideoPath(Directory.FullName);
                    if (VideoUtility.IsVideoDisc(videoPath))
                    {
                        // if we found one we can safely asume by standards that this will be the
                        // only valid video file on the disc so we create the filelist and add only this file
                        fileList = new List <FileInfo>();
                        fileList.Add(new FileInfo(videoPath));
                    }
                }

                // if the fileList is null it means that we didn't find an 'exclusive' video file above
                // and we are going to scan the whole tree
                if (fileList == null)
                {
                    fileList = VideoUtility.GetVideoFilesRecursive(Directory);
                }

                // go through the video file list
                DriveType type = GetDriveType();
                foreach (FileInfo videoFile in fileList)
                {
                    // Create or get a localmedia object from the video file path
                    DBLocalMedia newFile = DBLocalMedia.Get(videoFile.FullName, serial);

                    // The file is in the database
                    if (newFile.ID != null)
                    {
                        // for optical paths + DVD we have to check the actual DiscId
                        // todo: add bluray disc id support
                        if (IsOpticalDrive)
                        {
                            if ((newFile.IsDVD) && !newFile.IsAvailable)
                            {
                                string discId = newFile.VideoFormat.GetIdentifier(newFile.FullPath);
                                // Create/get a DBLocalMedia object using the the DiscID
                                newFile = DBLocalMedia.GetDisc(videoFile.FullName, discId);
                            }
                        }

                        // If the file is still in the database continue if we only want new files
                        if (newFile.ID != null && returnOnlyNew)
                        {
                            continue;
                        }
                    }
                    else if (!IsOpticalDrive && !IsUnc)
                    {
                        // Verify the new file, if we find a similar file it could be that the serial has changed
                        List <DBLocalMedia> otherFiles = DBLocalMedia.GetAll(newFile.FullPath);
                        if (otherFiles.Count == 1)
                        {
                            DBLocalMedia otherFile = otherFiles[0];
                            if (type != DriveType.Unknown && type != DriveType.CDRom && type != DriveType.NoRootDirectory)
                            {
                                bool fileAvailable = otherFile.IsAvailable;
                                if ((String.IsNullOrEmpty(otherFile.VolumeSerial) && fileAvailable) || (!fileAvailable && File.Exists(otherFile.FullPath)))
                                {
                                    // the disk serial was updated for this file
                                    otherFile.VolumeSerial = serial;
                                    otherFile.MediaLabel   = label;
                                    otherFile.Commit();
                                    logger.Info("Disk information updated for '{0}'", otherFile.FullPath);
                                    continue;
                                }
                            }
                        }
                    }

                    // NEW FILE

                    // Add additional file information
                    newFile.ImportPath   = this;
                    newFile.VolumeSerial = serial;
                    newFile.MediaLabel   = label;

                    // add the localmedia object to our return list
                    logger.Debug("New File: {0}", videoFile.Name);
                    rtn.Add(newFile);
                }
            }
            catch (Exception e) {
                if (e.GetType() == typeof(ThreadAbortException))
                {
                    throw e;
                }


                if (logger.IsDebugEnabled)
                {
                    // In debug mode we log the geeky version
                    logger.DebugException("Error scanning '" + Directory.FullName + "'", e);
                }
                else
                {
                    // In all other modes we do it more friendlier
                    logger.Error("Error scanning '{0}': {1}", Directory.FullName, e.Message);
                }
            }

            return(rtn);
        }