/// <summary>
        /// Sets a new path for the list view
        /// </summary>
        /// <param name="newPath">Path to be set</param>
        public void setPath(ref string newPath)
        {
            if (newPath == null || newPath == "" || !Directory.Exists(newPath))
            {
                return;
            }

            if (newPath.Length == 2)
            {
                if (char.IsLetter(newPath[0]) && newPath[1] == ':')
                {
                    newPath = newPath + Path.DirectorySeparatorChar;
                }
            }

            //Skip this for now on networks

            if (!isNetworkPath(newPath))
            {
                //fix casing of the path if user entered it
                newPath = fixPathCase(newPath);
            }
            //Same path, ignore
            if (Helper.ReadProperty(ConfigKeyConstants.LAST_DIRECTORY_KEY).ToLower() == newPath.ToLower())
            {
                return;
            }
            else
            {
                Helper.WriteProperty(ConfigKeyConstants.LAST_DIRECTORY_KEY, newPath);
                Environment.CurrentDirectory = newPath;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// internal recursive function for getting subdirectories
        /// </summary>
        /// <param name="dir">current recursive root folder</param>
        /// <param name="pattern">Pattern for file matching, "*" for all</param>
        /// <param name="depth">Current recursive depth for cancelling recursion</param>
        /// <param name="count">Total count of all listed files</param>
        /// <returns>List of FileSystemInfo classes from all matched files</returns>
        private static List <FileSystemInfo> GetAllFilesRecursively(DirectoryInfo dir, string pattern, int depth, ref int count, BackgroundWorker worker)
        {
            if (worker != null && worker.CancellationPending)
            {
                return(new List <FileSystemInfo>());
            }
            List <FileSystemInfo> files;

            try {
                files = new List <FileSystemInfo>(dir.GetFileSystemInfos(pattern));
            }
            catch (Exception) {
                return(null);
            }
            //remove directories? Why are they even there :(
            for (int i = 0; i < files.Count; i++)
            {
                if (Directory.Exists(files[i].FullName))
                {
                    files.RemoveAt(i);
                }
                else
                {
                    count++;
                }
            }
            List <FileSystemInfo> all = new List <FileSystemInfo>(dir.GetFileSystemInfos());

            if (depth >= Convert.ToInt32(Helper.ReadProperty(Config.MaxDepth)))
            {
                return(files);
            }
            foreach (FileSystemInfo f in all)
            {
                if (f is DirectoryInfo)
                {
                    List <FileSystemInfo> deeperfiles = GetAllFilesRecursively((DirectoryInfo)f, pattern, depth + 1, ref count, worker);
                    if (deeperfiles != null)
                    {
                        files.AddRange(deeperfiles);
                    }
                }
            }
            //weird threading issues force me to create a new var here which is no reference
            int count2 = count;

            if (Form1.Instance.lblFileListingProgress.InvokeRequired)
            {
                Form1.Instance.lblFileListingProgress.Invoke(new EventHandler(delegate
                {
                    Form1.Instance.lblFileListingProgress.Text = "Found " + count2 + " files so far...";
                }));
            }
            else
            {
                Form1.Instance.lblFileListingProgress.Text = "Found " + count2 + " files so far...";
            }
            return(files);
        }
        /// <summary>
        /// Main Rename function
        /// </summary>
        public void Rename(BackgroundWorker someWorker, DoWorkEventArgs someRenameEventArgs)
        {
            this.currentWorker          = someWorker;
            this.currentRenameEventArgs = someRenameEventArgs;

            double copiedFileBytesSum = countCopiedFileBytes();

            double copiedBytes = 0;
            //Go through all files and do stuff
//            for (int i = 0; i < this.mediaFiles.Count; i++) {
            List <MediaFile> filesToCheck = new List <MediaFile>(mediaFiles);

            foreach (MediaFile mediaFile in filesToCheck)
            {
                if (renamingCancelled(someWorker, someRenameEventArgs))
                {
                    return;
                }

                if (fileWillBeDeleted(mediaFile))
                {
                    deleteMediaFile(mediaFile);
                }

                //need to set before ie.Rename because it resets some conditions
                bool willBeCopied = mediaFileChangesPartition(mediaFile);

                //if there are files which actually need to be copied since they're on a different drive, only count those for the progress bar status since they take much longer
                setProgress(copiedBytes, copiedFileBytesSum, mediaFile, willBeCopied);

                someWorker.ReportProgress((int)ProgressAtCopyStart);

                bool removeFromSet = notVisibleAfterRenaming(mediaFile);
                //this call will also report progress more detailed by calling ReportSingleFileProgress()
                mediaFile.Rename(someWorker, someRenameEventArgs);
                if (removeFromSet)
                {
                    mediaFiles.Remove(mediaFile);
                }
                //after file is (really) copied, add its size
                if (willBeCopied)
                {
                    copiedBytes += getFilesize(mediaFile);
                }
            }

            if (Helper.ReadBool(ConfigKeyConstants.DELETE_EMPTIED_FOLDERS_KEY))
            {
                //Delete all empty folders code
                Helper.DeleteAllEmptyFolders(Helper.ReadProperty(ConfigKeyConstants.LAST_DIRECTORY_KEY), new List <string>(Helper.ReadProperties(ConfigKeyConstants.EMPTY_FOLDER_CHECK_IGNORED_FILETYPES_KEY)), someWorker, someRenameEventArgs);
            }
            logEndOfRenaming(someRenameEventArgs.Cancel);
        }
        private bool notVisibleAfterRenaming(MediaFile mediaFile)
        {
            int destinationDirDepth = Filepath.GetSubdirectoryLevel(Helper.ReadProperty(ConfigKeyConstants.LAST_DIRECTORY_KEY), mediaFile.DestinationPath);

            if (destinationDirDepth == -1)
            {
                return(true);
            }
            else
            {
                int maxDirDepth = Helper.ReadInt(ConfigKeyConstants.MAX_SEARCH_DEPTH_KEY);
                return(destinationDirDepth > maxDirDepth);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Sets a new path for the list view
        /// </summary>
        /// <param name="path">Path to be set</param>
        public void SetPath(ref string path)
        {
            if (path == null || path == "" || !Directory.Exists(path))
            {
                return;
            }

            if (path.Length == 2)
            {
                if (char.IsLetter(path[0]) && path[1] == ':')
                {
                    path = path + Path.DirectorySeparatorChar;
                }
            }
            DirectoryInfo currentpath = new DirectoryInfo(path);

            //Skip this for now on networks

            if (!path.StartsWith("\\\\"))
            {
                //fix casing of the path if user entered it
                string fixedpath = "";
                while (currentpath.Parent != null)
                {
                    fixedpath   = currentpath.Parent.GetDirectories(currentpath.Name)[0].Name + Path.DirectorySeparatorChar + fixedpath;
                    currentpath = currentpath.Parent;
                }
                fixedpath = currentpath.Name.ToUpper() + fixedpath;
                fixedpath = fixedpath.TrimEnd(new char[] { Path.DirectorySeparatorChar });
                if (fixedpath.Length == 2)
                {
                    if (char.IsLetter(fixedpath[0]) && fixedpath[1] == ':')
                    {
                        fixedpath = fixedpath + Path.DirectorySeparatorChar;
                    }
                }
                path = fixedpath;
            }
            //Same path, ignore
            if (Helper.ReadProperty(Config.LastDirectory).ToLower() == path.ToLower())
            {
                return;
            }
            else
            {
                Helper.WriteProperty(Config.LastDirectory, path);
                Environment.CurrentDirectory = path;
            }
        }
        /// <summary>
        /// Finds similar files by looking at the file path and comparing it to a showname
        /// </summary>
        /// <param name="Basepath">basepath of the show</param>
        /// <param name="showname">name of the show to filter</param>
        /// <param name="source">source files</param>
        /// <returns>a list of matches</returns>
        public List <MediaFile> FindSimilarByName(string showname)
        {
            List <MediaFile> matches = new List <MediaFile>();

            showname = showname.ToLower();
            //whatever, just check path and file path if it contains the showname
            foreach (MediaFile mediaFile in this.mediaFiles)
            {
                string lowerCaseFilename = mediaFile.Filename.ToLower();

                //try to extract the name from a shortcut, i.e. sga for Stargate Atlantis
                string noWordCharPattern = "[^\\w]";
                Match  findWhitespaces   = Regex.Match(lowerCaseFilename, noWordCharPattern, RegexOptions.IgnoreCase);
                if (findWhitespaces != null && findWhitespaces.Success)
                {
                    string firstWord = lowerCaseFilename.Substring(0, findWhitespaces.Index);
                    if (firstWord.Length > 0 && Helper.ContainsLetters(firstWord, showname))
                    {
                        //FIXME: this should probably be removed, because I can think of a thousand times where this will break
                        matches.Add(mediaFile);
                        continue;
                    }
                }

                //now check if whole showname is in the file path
                string CleanupRegex = Helper.ReadProperty(ConfigKeyConstants.REGEX_SHOWNAME_CLEANUP_KEY);
                lowerCaseFilename = Regex.Replace(lowerCaseFilename, CleanupRegex, " ");
                if (lowerCaseFilename.Contains(showname))
                {
                    matches.Add(mediaFile);
                    continue;
                }

                string[] parentFolders = Helper.getParentFolderNames(mediaFile.FilePath.Path);
                //or in some top folder
                foreach (string str in parentFolders)
                {
                    lowerCaseFilename = str.ToLower();
                    lowerCaseFilename = Regex.Replace(lowerCaseFilename, CleanupRegex, " ");
                    if (lowerCaseFilename.Contains(showname))
                    {
                        matches.Add(mediaFile);
                        break;
                    }
                }
            }
            return(matches);
        }
Esempio n. 7
0
        /// <summary>
        /// Finds similar files by looking at the filename and comparing it to a showname
        /// </summary>
        /// <param name="Basepath">basepath of the show</param>
        /// <param name="Showname">name of the show to filter</param>
        /// <param name="source">source files</param>
        /// <returns>a list of matches</returns>
        public List <InfoEntry> FindSimilarByName(string Showname)
        {
            List <InfoEntry> matches = new List <InfoEntry>();

            Showname = Showname.ToLower();
            //whatever, just check path and filename if it contains the showname
            foreach (InfoEntry ie in this.episodes)
            {
                string[] folders   = Helper.splitFilePath(ie.FilePath.Path);
                string   processed = ie.Filename.ToLower();

                //try to extract the name from a shortcut, i.e. sga for Stargate Atlantis
                string pattern = "[^\\w]";
                Match  m       = Regex.Match(processed, pattern, RegexOptions.IgnoreCase);
                if (m != null && m.Success)
                {
                    string abbreviation = processed.Substring(0, m.Index);
                    if (abbreviation.Length > 0 && Helper.ContainsLetters(abbreviation, Showname))
                    {
                        matches.Add(ie);
                        continue;
                    }
                }

                //now check if whole showname is in the filename
                string CleanupRegex = Helper.ReadProperty(Config.CleanupRegex);
                processed = Regex.Replace(processed, CleanupRegex, " ");
                if (processed.Contains(Showname))
                {
                    matches.Add(ie);
                    continue;
                }

                //or in some top folder
                foreach (string str in folders)
                {
                    processed = str.ToLower();
                    processed = Regex.Replace(processed, CleanupRegex, " ");
                    if (processed.Contains(Showname))
                    {
                        matches.Add(ie);
                        break;
                    }
                }
            }
            return(matches);
        }
Esempio n. 8
0
 /// <summary>
 /// writes a property with more than one Value to config file
 /// </summary>
 /// <param name="Identifier">Name of the property</param>
 /// <param name="Value">delimiter separated string of values</param>
 /// /// <param name="FilePath">Path of the config file</param>
 public static void WriteProperties(string Identifier, string Value, string FilePath)
 {
     WriteProperties(Identifier, Value.Split(new string[] { Helper.ReadProperty(Config.Delimiter) }, StringSplitOptions.RemoveEmptyEntries), FilePath);
 }
Esempio n. 9
0
        /// <summary>
        /// Main Rename function
        /// </summary>
        public void Rename(BackgroundWorker worker, DoWorkEventArgs e)
        {
            this.worker = worker;
            this.dwea   = e;

            long TotalBytes = 0;
            long Bytes      = 0;

            foreach (InfoEntry ie in episodes)
            {
                if (ie.ProcessingRequested && ie.Destination != "" && ie.FilePath.Fullfilename.ToLower()[0] != ie.Destination.ToLower()[0])
                {
                    FileInfo info = new FileInfo(ie.FilePath.Fullfilename);
                    TotalBytes += info.Length;
                }
            }
            //Go through all files and do stuff
            for (int i = 0; i < this.episodes.Count; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    Logger.Instance.LogMessage("Renaming Cancelled.", LogLevel.INFO);
                    return;
                }

                InfoEntry ie = InfoEntryManager.Instance[i];
                if (ie.MarkedForDeletion && ie.ProcessingRequested)
                {
                    try
                    {
                        File.Delete(ie.FilePath.Fullfilename);
                        episodes.Remove(ie);
                        //Go back so no entry is skipped after removal of current entry
                        i--;
                        continue;
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.LogMessage("Couldn't delete " + ie.FilePath.Fullfilename + ": " + ex.Message, LogLevel.ERROR);
                    }
                }

                //need to set before ie.Rename because it resets some conditions
                bool copyfile = ie.ProcessingRequested && ie.Destination != "" && ie.FilePath.Fullfilename.ToLower()[0] != ie.Destination.ToLower()[0];

                //if there are files which actually need to be copied since they're on a different drive, only count those for the progress bar status since they take much longer
                if (TotalBytes > 0)
                {
                    ProgressAtCopyStart = ((double)Bytes / (double)TotalBytes * 100);
                    if (copyfile)
                    {
                        ProgressAtCopyEnd = Math.Min(ProgressAtCopyStart + (long)(((double)new FileInfo(ie.FilePath.Fullfilename).Length) / (double)TotalBytes * 100), 100);
                    }
                    else
                    {
                        ProgressAtCopyEnd = ProgressAtCopyStart;
                    }
                }
                else
                {
                    ProgressAtCopyStart = i;
                    ProgressAtCopyEnd   = i;
                }

                worker.ReportProgress((int)ProgressAtCopyStart);

                //if a InfoEntry is moved to a different destination directory that isn't visible in the current basedir, remove it
                int  subdirlevel = Filepath.GetSubdirectoryLevel(Helper.ReadProperty(Config.LastDirectory), ie.Destination);
                bool remove      = subdirlevel > Helper.ReadInt(Config.MaxDepth) || subdirlevel == -1;
                //this call will also report progress more detailed by calling ReportSingleFileProgress()
                ie.Rename(worker, e);
                if (remove)
                {
                    episodes.Remove(ie);
                    //Go back so no entry is skipped after removal of current entry
                    i--;
                }
                //after file is (really) copied, add its size
                if (copyfile)
                {
                    Bytes += new FileInfo(ie.FilePath.Fullfilename).Length;
                }
            }
            if (Helper.ReadBool(Config.DeleteEmptyFolders))
            {
                //Delete all empty folders code
                Helper.DeleteAllEmptyFolders(Helper.ReadProperty(Config.LastDirectory), new List <string>(Helper.ReadProperties(Config.IgnoreFiles)), worker, e);
            }
            if (!e.Cancel)
            {
                Logger.Instance.LogMessage("Renaming (and possibly moving and deleting) finished!", LogLevel.INFO);
            }
            else
            {
                Logger.Instance.LogMessage("Renaming Cancelled.", LogLevel.INFO);
            }
        }