private void OnRenamed(object source, RenamedEventArgs e)
        {
            this.PathChanged(e.FullPath, fileExists: true);
            // Irritatingly, e.OldFullPath will throw an exception if the path is longer than the windows max
            // (but e.FullPath is fine).
            // So, construct it from e.FullPath and e.OldName
            // Note that we're using Pri.LongPath to get a Path.GetDirectoryName implementation that can handle
            // long paths

            // Apparently Path.GetDirectoryName(e.FullPath) or Path.GetFileName(e.OldName) can return null, see #112
            // Not sure why this might be, but let's work around it...
            var oldFullPathDirectory = Path.GetDirectoryName(e.FullPath);
            var oldFileName          = Path.GetFileName(e.OldName);

            if (oldFullPathDirectory == null)
            {
                logger.Warn("OldFullPathDirectory is null. Not sure why... e.FullPath: {0}", e.FullPath);
                return;
            }

            if (oldFileName == null)
            {
                logger.Warn("OldFileName is null. Not sure why... e.OldName: {0}", e.OldName);
                return;
            }

            var oldFullPath = Path.Combine(oldFullPathDirectory, oldFileName);

            this.PathChanged(oldFullPath, fileExists: false);
        }
Beispiel #2
0
        public List <Stream> Process(SVR_VideoLocal_Place vplace)
        {
            string dirname = Path.GetDirectoryName(vplace.FullServerPath);
            string fname   = Path.GetFileNameWithoutExtension(vplace.FilePath);

            if (string.IsNullOrEmpty(dirname) || string.IsNullOrEmpty(fname))
            {
                return(null);
            }
            string        basename = Path.Combine(dirname, fname);
            List <Stream> streams  = new List <Stream>();

            if (File.Exists(basename + ".idx") && File.Exists(basename + ".sub"))
            {
                FileSystemResult <IObject> r = vplace.ImportFolder.FileSystem.Resolve(basename + ".sub");
                if (r != null && r.IsOk && r.Result is IFile)
                {
                    List <Stream> ss = GetStreams((IFile)r.Result);
                    if ((ss != null) && (ss.Count > 0))
                    {
                        streams.AddRange(ss);
                    }
                }
            }
            return(streams);
        }
Beispiel #3
0
        public List <Stream> Process(string filename)
        {
            string dirname = Path.GetDirectoryName(filename);
            string fname   = Path.GetFileNameWithoutExtension(filename);

            if (string.IsNullOrEmpty(dirname) || string.IsNullOrEmpty(fname))
            {
                return(null);
            }
            string           basename   = Path.Combine(dirname, fname);
            HashSet <string> extensions = new HashSet <string>(SubtitleHelper.Extensions.Keys);

            extensions.Remove("idx");
            List <Stream> streams = new List <Stream>();

            foreach (string n in extensions)
            {
                string newname = basename + "." + n;
                if (File.Exists(newname))
                {
                    List <Stream> ss = GetStreams(newname);
                    if ((ss != null) && (ss.Count > 0))
                    {
                        streams.AddRange(ss);
                    }
                }
            }
            return(streams);
        }
Beispiel #4
0
        public List <Stream> GetStreams(string filename)
        {
            string dirname = Path.GetDirectoryName(filename);
            string fname   = Path.GetFileNameWithoutExtension(filename);

            if (string.IsNullOrEmpty(dirname) || string.IsNullOrEmpty(fname))
            {
                return(null);
            }
            string basename = Path.Combine(dirname, fname);

            if (!File.Exists(basename + ".idx"))
            {
                return(null);
            }
            string bing = File.ReadAllText(basename + ".idx");

            if (!bing.Contains("VobSub index file"))
            {
                return(null);
            }
            Regex           ex = new Regex("\\nid: ([A-Za-z]{2})");
            MatchCollection ma = ex.Matches(bing);
            int             x  = 0;
            List <Stream>   ss = new List <Stream>();

            foreach (Match m in ma)
            {
                if (m.Success)
                {
                    string language = null;
                    string val      = m.Groups[1].Value.ToLower();
                    if (SubtitleHelper.Iso639_3_TO_Iso639_1.ContainsKey(val))
                    {
                        language = SubtitleHelper.Iso639_3_TO_Iso639_1[val];
                    }
                    else if (SubtitleHelper.Iso639_1_TO_Languages.ContainsKey(val))
                    {
                        language = val;
                    }
                    else if (SubtitleHelper.Languages_TO_ISO639_1_Lower.ContainsKey(val))
                    {
                        language = SubtitleHelper.Languages_TO_ISO639_1_Lower[val];
                    }
                    if (language != null)
                    {
                        Stream s = new Stream();
                        s.Format       = "vobsub";
                        s.StreamType   = "3";
                        s.SubIndex     = x.ToString();
                        s.File         = basename + ".idx";
                        s.LanguageCode = SubtitleHelper.Iso639_1_TO_Iso639_3[language];
                        s.Language     = SubtitleHelper.Iso639_1_TO_Languages[language];
                        ss.Add(s);
                    }
                }
                x++;
            }
            return(ss);
        }
Beispiel #5
0
        public List <Stream> Process(SVR_VideoLocal_Place vplace)
        {
            string dirname = Path.GetDirectoryName(vplace.FullServerPath);
            string fname   = Path.GetFileNameWithoutExtension(vplace.FilePath);

            if (string.IsNullOrEmpty(dirname) || string.IsNullOrEmpty(fname))
            {
                return(null);
            }
            string           basename   = Path.Combine(dirname, fname);
            HashSet <string> extensions = new HashSet <string>(SubtitleHelper.Extensions.Keys);

            extensions.Remove("idx");
            List <Stream> streams = new List <Stream>();

            foreach (string n in extensions)
            {
                string newname = basename + "." + n;
                FileSystemResult <IObject> r = vplace.ImportFolder.FileSystem.Resolve(newname);
                if (r != null && r.IsOk && r.Result is IFile)
                {
                    List <Stream> ss = GetStreams((IFile)r.Result);
                    if ((ss != null) && (ss.Count > 0))
                    {
                        streams.AddRange(ss);
                    }
                }
            }
            return(streams);
        }
        public static void RenameFileExtension(string iPath, string src, string dest)
        {
            if (!Directory.Exists(iPath))
            {
                return;
            }

            // rename subDir
            string[] dirPaths = Directory.GetDirectories(iPath);
            for (int i = 0; i < dirPaths.Length; i++)
            {
                RenameFileExtension(dirPaths[i], src, dest);
            }

            // rename files
            string[] filePaths = Directory.GetFiles(iPath);
            for (int i = 0; i < filePaths.Length; ++i)
            {
                string extension = Path.GetExtension(filePaths[i]);
                if (extension == src)
                {
                    string dir      = Path.GetDirectoryName(filePaths[i]);
                    string name     = Path.GetFileNameWithoutExtension(filePaths[i]);
                    string destFile = dir + name + dest;

                    MoveWithReplace(filePaths[i], destFile);
                }
            }
        }
        /// <summary>
        /// Write transcript for the clip if it available.
        /// </summary>
        /// <param name="clipId">Clip Id</param>
        /// <param name="clipPath">Path of current clip</param>
        public void WriteTranscriptFile(Clip clipId, string clipPath)
        {
            // Get all transcript to list
            List <ClipTranscript> clipTranscripts = clipId.Subtitle;

            if (clipTranscripts.Count > 0)
            {
                // Create transcript path with the same name of the clip
                string transcriptPath = Path.Combine(Path.GetDirectoryName(clipPath),
                                                     Path.GetFileNameWithoutExtension(clipPath) + ".srt");
                if (!File.Exists(transcriptPath))
                {
                    using (FileStream transcriptStream = File.OpenWrite(transcriptPath))
                    {
                        using (StreamWriter writer = new StreamWriter(transcriptStream))
                        {
                            // Write it to file with stream writer
                            int i = 1;
                            foreach (var clipTranscript in clipTranscripts)
                            {
                                var start = TimeSpan.FromMilliseconds(clipTranscript.StartTime).ToString(@"hh\:mm\:ss\,fff");
                                var end   = TimeSpan.FromMilliseconds(clipTranscript.EndTime).ToString(@"hh\:mm\:ss\,fff");
                                writer.WriteLine(i++);
                                writer.WriteLine(start + " --> " + end);
                                writer.WriteLine(clipTranscript.Text);
                                writer.WriteLine();
                            }
                        }
                    }
                    bgwDecrypt.ReportProgress(1, new { Text = $"Transcript of {Path.GetFileName(clipPath)} generated.", Color = Color.Purple, newLine = false });
                }
            }
        }
Beispiel #8
0
        public void GetDirectoryNameOnRelativePathWithNoParent()
        {
            const string input    = @"foo";
            const string expected = @"";
            string       actual   = Path.GetDirectoryName(input);

            Assert.AreEqual(expected, actual);
        }
Beispiel #9
0
        public void GetDirectoryNameOnRelativePath()
        {
            const string input    = @"foo\bar\baz";
            const string expected = @"foo\bar";
            string       actual   = Path.GetDirectoryName(input);

            Assert.AreEqual(expected, actual);
        }
Beispiel #10
0
        public static string GetAppPath()
        {
            if (string.IsNullOrEmpty(appPath))
            {
                appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            }

            return(appPath);
        }
Beispiel #11
0
        public void RenameFile(string renameScript)
        {
            string renamed = RenameFileHelper.GetNewFileName(this, renameScript);

            if (string.IsNullOrEmpty(renamed))
            {
                return;
            }

            ImportFolderRepository repFolders = new ImportFolderRepository();
            VideoLocalRepository   repVids    = new VideoLocalRepository();

            // actually rename the file
            string fullFileName = this.FullServerPath;

            // check if the file exists
            if (!File.Exists(fullFileName))
            {
                logger.Error("Error could not find the original file for renaming: " + fullFileName);
                return;
            }

            // actually rename the file
            string path        = Path.GetDirectoryName(fullFileName);
            string newFullName = Path.Combine(path, renamed);

            try
            {
                logger.Info(string.Format("Renaming file From ({0}) to ({1})....", fullFileName, newFullName));

                if (fullFileName.Equals(newFullName, StringComparison.InvariantCultureIgnoreCase))
                {
                    logger.Info(string.Format("Renaming file SKIPPED, no change From ({0}) to ({1})", fullFileName,
                                              newFullName));
                }
                else
                {
                    File.Move(fullFileName, newFullName);
                    logger.Info(string.Format("Renaming file SUCCESS From ({0}) to ({1})", fullFileName, newFullName));

                    string newPartialPath = "";
                    int    folderID       = this.ImportFolderID;

                    DataAccessHelper.GetShareAndPath(newFullName, repFolders.GetAll(), ref folderID, ref newPartialPath);

                    this.FilePath = newPartialPath;
                    repVids.Save(this, true);
                }
            }
            catch (Exception ex)
            {
                logger.Info(string.Format("Renaming file FAIL From ({0}) to ({1}) - {2}", fullFileName, newFullName,
                                          ex.Message));
                logger.ErrorException(ex.ToString(), ex);
            }
        }
        /// <summary>
        ///   Folder of the executing assembly, mainly used in Unit testing
        /// </summary>
        /// <returns></returns>
        public static string ExecutableDirectoryName()
        {
            var diretory = Assembly.GetExecutingAssembly().Location;

            if (string.IsNullOrEmpty(diretory))
            {
                diretory = Assembly.GetEntryAssembly().Location;
            }
            if (string.IsNullOrEmpty(diretory))
            {
                diretory = ".";
            }
            return(Path.GetDirectoryName(diretory));
        }
Beispiel #13
0
        public static void ProcessIsos()
        {
            var files = Directory.EnumerateFiles(Paths.OutputPath, "*.iso", SearchOption.AllDirectories).Concat(Directory.EnumerateFiles(Paths.OutputPath, "*.bin", SearchOption.AllDirectories));

            //var files = Directory.EnumerateFiles(Paths.OutputPath, "*.bin", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                Console.WriteLine("Mounting {0} => D:", file);
                if (StartProcess(@"C:\Program Files\PowerISO\piso.exe", $"mount \"{file}\" D:") >= 0)
                {
                    var destPath = Path.GetDirectoryName(file) + @"\" + Path.GetFileNameWithoutExtension(file) + @"\";
                    CopyFiles("D:", destPath, false);
                }
            }
        }
Beispiel #14
0
        public override async Task <FileSystemResult> RenameAsync(string newname)
        {
            if (string.Equals(Name, newname))
            {
                return(new FileSystemResult("Unable to rename, names are the same"));
            }
            string parentPath  = Path.GetDirectoryName(FullName);
            string newfullname = Path.Combine(parentPath, newname);

            Directory.Move(FullName, newfullname);
            DirectoryInfo dinfo = new DirectoryInfo(newfullname);

            _directory = dinfo;
            return(await Task.FromResult(new FileSystemResult()));
        }
        public static void CopyFile(string from, string to)
        {
            string directoryName = Path.GetDirectoryName(to);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            // FileUtil.CopyFileOrDirectory(from, to);
            try {
                File.Copy(from, to, true);
            } catch (Exception ex) {
                //Debug.LogError (string.Format ("{0}: {1}", ex.Message, ex.StackTrace));
            }
        }
Beispiel #16
0
        public static void FixLibraryFolders()
        {
            var folders = Directory.EnumerateDirectories(Paths.OutputPath, "*", SearchOption.TopDirectoryOnly);

            foreach (var folder in folders)
            {
                var name    = Path.GetFileName(folder);
                var oldName = name;
                name = Regex.Replace(name, @"\b(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY|AU|MATRiX|DVDR|WAV|AiR|ArCADE|VR|CDDA|PAD|MiDi|CoBaLT|DiSCOVER)\b", "");
                name = Regex.Replace(name, @"\b(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK|MAGNETRiXX|TZ7iSO|KLI|DVDriSO|DVD9|KRock|ACiD|REX|RMX|SynthX|AiFF|Apple Loops|AiRISO|MULTiFORMAT|AudioP2P|GHOSTiSO|REX2|DXi|HYBRiD|AKAI|ALFiSO)\b", "", RegexOptions.IgnoreCase);
                name = Regex.Replace(name, @"  +", " ");
                if (name != oldName && !Directory.Exists(Path.GetDirectoryName(folder) + @"\" + name))
                {
                    File.Move(folder, Path.GetDirectoryName(folder) + @"\" + name);
                }
            }
        }
Beispiel #17
0
        public static List <string> GetPossibleSubtitleFiles(string fileName)
        {
            List <string> subtileFiles = new List <string>();

            subtileFiles.Add(Path.Combine(Path.GetDirectoryName(fileName),
                                          Path.GetFileNameWithoutExtension(fileName) + ".srt"));
            subtileFiles.Add(Path.Combine(Path.GetDirectoryName(fileName),
                                          Path.GetFileNameWithoutExtension(fileName) + ".ass"));
            subtileFiles.Add(Path.Combine(Path.GetDirectoryName(fileName),
                                          Path.GetFileNameWithoutExtension(fileName) + ".ssa"));
            subtileFiles.Add(Path.Combine(Path.GetDirectoryName(fileName),
                                          Path.GetFileNameWithoutExtension(fileName) + ".idx"));
            subtileFiles.Add(Path.Combine(Path.GetDirectoryName(fileName),
                                          Path.GetFileNameWithoutExtension(fileName) + ".sub"));

            return(subtileFiles);
        }
Beispiel #18
0
        static void ProcessFolder(string rootPath, string baseFolder, string destFolder, bool canMove, bool preservePaths, string extraPath = "")
        {
            var folder = baseFolder;
            var files  = Directory.EnumerateFiles(folder, "*").Where(f => Path.GetExtension(f) != ".txt" && Path.GetExtension(f) != ".nfo" && Path.GetExtension(f) != ".sfv").ToArray();

            while (!preservePaths)              // Not a true while, preserve paths does not change.
            {
                var subFolders = Directory.EnumerateDirectories(folder).ToArray();
                if (files.Length == 0 && subFolders.Length == 1)
                {
                    folder = subFolders[0];
                }
                else
                {
                    break;
                }
                files = Directory.EnumerateFiles(folder, "*").Where(f => Path.GetExtension(f) != ".txt" && Path.GetExtension(f) != ".nfo" && Path.GetExtension(f) != ".sfv").ToArray();
            }

            //files = Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).ToArray();
            var archiveFiles = GetArchiveFiles(files);

            archiveFiles.ForEach(archive => ProcessArchive(rootPath, Path.GetDirectoryName(archive), archive, files, destFolder));

            var names = folder.Substring(rootPath.Length).Split(Path.DirectorySeparatorChar);
            var name  = names.FirstOrDefault(n => Regex.IsMatch(n, "KONTAKT", RegexOptions.IgnoreCase)) ?? names[0];

            //if ((folder + "\\").StartsWith(string.Format("{0}\\{1}\\", baseFolder, name)))
            //	name = "";
            //name = Regex.Replace(name, @"\.(rar|r00|zip|iso)$", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.(rar|r00|zip)$", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.part1", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.part01", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, "-", " ");
            name = Regex.Replace(name, @"([a-z ])\.+([\w ])", "$1 $2", RegexOptions.IgnoreCase);                // Remove dots but leave those that are between digits.
            name = Regex.Replace(name, @"([\w ])\.+([a-z ])", "$1 $2", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\b(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY|AU|MATRiX|DVDR|WAV|AiR|ArCADE|VR|CDDA|PAD|MiDi|CoBaLT|DiSCOVER)\b", "");
            name = Regex.Replace(name, @"\b(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK|MAGNETRiXX|TZ7iSO|KLI|DVDriSO|DVD9|KRock|ACiD|REX|RMX|SynthX|AiFF|Apple Loops|AiRISO|MULTiFORMAT|AudioP2P|GHOSTiSO|REX2|DXi|HYBRiD|AKAI|ALFiSO)\b", "", RegexOptions.IgnoreCase);
            //name = Regex.Replace(name, "(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY| AU |MATRiX)", "");
            //name = Regex.Replace(name, "(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK||MAGNETRiXX)", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"  +", " ");
            name = name.Trim(' ', '-');
            var destPath = $"{destFolder}\\{name}{extraPath}";

            CopyFiles(folder, destPath, canMove, false);
        }
Beispiel #19
0
 public override async Task <FileSystemResult> RenameAsync(string newname)
 {
     try
     {
         if (string.Equals(Name, newname))
         {
             return(new FileSystemResult("Unable to rename, names are the same"));
         }
         string parentPath  = Path.GetDirectoryName(FullName);
         string newfullname = Path.Combine(parentPath, newname);
         File.Move(FullName, newfullname);
         FileInfo finfo = new FileInfo(newfullname);
         file = finfo;
         return(await Task.FromResult(new FileSystemResult()));
     }
     catch (Exception e)
     {
         return(new FileSystemResult(e.Message));
     }
 }
Beispiel #20
0
 static void CopyFiles(string source, string dest, bool move, bool includeArchives = true)
 {
     if (move)
     {
         MarkFolderWritable(source);
     }
     MarkFolderWritable(dest);
     Console.WriteLine("{0} {1} => {2}", move ? "Moving" : "Copying", source, dest);
     source = source.TrimEnd('\\');
     dest   = dest.TrimEnd('\\');
     if (!Directory.Exists(dest))
     {
         Directory.CreateDirectory(dest);
     }
     Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories).Select(d => d.Replace(source, dest)).ForEach(path => Directory.CreateDirectory(path));
     foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories).Where(f => Path.GetExtension(f) != ".nfo" && !Regex.IsMatch(Path.GetFileName(f), "All.Collection.Upload|WareZ-Audio", RegexOptions.IgnoreCase)).ToArray())
     {
         if (Path.GetExtension(file) == ".sfv")
         {
             continue;
         }
         //if (!includeArchives && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip|iso)"))
         if (!includeArchives && Path.GetDirectoryName(file) == source && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip)"))
         {
             continue;
         }
         var newFile = file.Replace(source, dest);
         if (move)
         {
             if (File.Exists(newFile))
             {
                 File.Delete(newFile);
             }
             File.Move(file, newFile);
         }
         else
         {
             File.Copy(file, newFile, true);
         }
     }
 }
        public static FileStream saveFile(string fileName, JSONObject node = null)
        {
            string directoryName = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);

            if (node == null)
            {
                return(fileStream);
            }
            StreamWriter streamWriter = new StreamWriter(fileStream);
            string       value        = node.Print(true);

            streamWriter.Write(value);
            streamWriter.Close();
            return(fileStream);
        }
Beispiel #22
0
        private void OnRenamed(object source, RenamedEventArgs e)
        {
            // Apparently e.FullPath or e.OldName can be null, see #112
            // Not sure why this might be, but let's work around it...
            if (e.FullPath == null)
            {
                logger.Warn("OnRenamed: e.FullPath is null. Ignoring...");
                return;
            }

            this.RecordPathChange(e.FullPath, pathExists: true);
            // Irritatingly, e.OldFullPath will throw an exception if the path is longer than the windows max
            // (but e.FullPath is fine).
            // So, construct it from e.FullPath and e.OldName.
            // Note that we're using Pri.LongPath to get a Path.GetDirectoryName implementation that can handle
            // long paths

            if (e.OldName == null)
            {
                logger.Warn("OnRenamed: e.OldName is null. Not sure why");
                return;
            }

            // Note that e.FullPath could be a file or a directory. If it's a directory, it could be a drive
            // root. If it's a drive root, Path.GetDirectoryName will return null. I'm not sure *how* it could
            // be a drive root though... Record a change to the drive root if so.
            var oldFullPathDirectory = Path.GetDirectoryName(e.FullPath);

            if (oldFullPathDirectory == null)
            {
                this.RecordPathChange(e.FullPath, pathExists: true);
            }
            else
            {
                var oldFileName = Path.GetFileName(e.OldName);
                var oldFullPath = Path.Combine(oldFullPathDirectory, oldFileName);

                this.RecordPathChange(oldFullPath, pathExists: false);
            }
        }
Beispiel #23
0
        public List <Stream> Process(string filename)
        {
            string dirname = Path.GetDirectoryName(filename);
            string fname   = Path.GetFileNameWithoutExtension(filename);

            if (string.IsNullOrEmpty(dirname) || string.IsNullOrEmpty(fname))
            {
                return(null);
            }
            string        basename = Path.Combine(dirname, fname);
            List <Stream> streams  = new List <Stream>();

            if (File.Exists(basename + ".idx") && File.Exists(basename + ".sub"))
            {
                List <Stream> ss = GetStreams(basename + ".sub");
                if ((ss != null) && (ss.Count > 0))
                {
                    streams.AddRange(ss);
                }
            }
            return(streams);
        }
        /*
         * public static async Task<IObject> ObjectFromPath(this IDirectory dir, string fullname)
         * {
         *  while (!dir.IsRoot)
         *  {
         *      dir = dir.Parent;
         *  }
         *  string[] parts = fullname.Split('\\');
         *  int start = 0;
         *  bool repeat;
         *  do
         *  {
         *      repeat = false;
         *      if (!dir.IsPopulated)
         *          await dir.PopulateAsync();
         *      foreach (IDirectory d in dir.Directories)
         *      {
         *          if (d.Name.Equals(parts[start], StringComparison.InvariantCultureIgnoreCase))
         *          {
         *              if (start == parts.Length - 1)
         *                  return d;
         *              repeat = true;
         *              start++;
         *              dir = d;
         *              break;
         *          }
         *      }
         *      if ((!repeat) && (start == parts.Length-1))
         *      {
         *          foreach (IFile d in dir.Files)
         *          {
         *              if (d.Name.Equals(parts[start], StringComparison.InvariantCultureIgnoreCase))
         *              {
         *                  return d;
         *              }
         *          }
         *      }
         *  } while (repeat);
         *  return null;
         * }
         */
        public static string HashFromExtendedFile(string file, string type = "md5")
        {
            if (File.Exists(file + "." + type))
            {
                string[] lines = File.ReadAllLines(file + "." + type);
                foreach (string s in lines)
                {
                    if ((s.Length >= 32) && (s[0] != '#'))
                    {
                        return(s.Substring(0, 32));
                    }
                }
            }
            FileInfo f   = new FileInfo(file);
            string   dir = string.Empty;

            if (f.Directory != null)
            {
                dir = f.Directory.Name;
            }
            string bas = Path.Combine(Path.GetDirectoryName(file) ?? string.Empty, dir);

            if (File.Exists(bas + ".md5"))
            {
                string[] lines = File.ReadAllLines(bas + "." + type);
                foreach (string s in lines)
                {
                    if ((s.Length >= 35) && (s[0] != '#'))
                    {
                        string hash  = s.Substring(0, 32);
                        string fname = s.Substring(32).Replace("*", string.Empty).Trim();
                        if (string.Equals(f.Name, fname, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(hash);
                        }
                    }
                }
            }
            if (File.Exists(bas + ""))
            {
                string[] lines = File.ReadAllLines(bas + "");
                bool     hash  = false;
                for (int x = 0; x < lines.Length; x++)
                {
                    string s = lines[x];
                    if ((s.Length > 5) && (s.StartsWith("#" + type + "#")))
                    {
                        hash = true;
                    }
                    else if ((s.Length >= 35) && (s[0] != '#') && hash)
                    {
                        string md    = s.Substring(0, 32);
                        string fname = s.Substring(32).Replace("*", string.Empty).Trim();
                        if (string.Equals(f.Name, fname, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(md);
                        }
                        hash = false;
                    }
                    else
                    {
                        hash = false;
                    }
                }
            }
            return(string.Empty);
        }
Beispiel #25
0
 public void TestLongPathDirectoryName()
 {
     var x = Path.GetDirectoryName(@"C:\Vault Data\w\M\Access Midstream\9305 Hopeton Stabilizer Upgrades\08  COMMUNICATION\8.1  Transmittals\9305-005 Access Midstream Hopeton - Electrical Panel Wiring dwgs\TM-9305-005-Access Midstream-Hopeton Stabilizer Upgrades-Electrical Panel Wiring-IFC Revised.msg");
 }
Beispiel #26
0
 public void TestGetDirectoryNameWithNullPath()
 {
     Assert.Throws <ArgumentNullException>(() => Path.GetDirectoryName(null));
 }
Beispiel #27
0
        public void TestGetDirectoryNameAtRoot()
        {
            string path = @"c:\";

            Assert.IsNull(Path.GetDirectoryName(path));
        }
Beispiel #28
0
 public void TestLongPathDirectoryNameWithInvalidChars()
 {
     Assert.Throws <ArgumentException>(() => Path.GetDirectoryName(longPathDirectory + '<'));
 }
Beispiel #29
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_DownloadAniDBImages: {0}", AnimeID);

            AniDbRateLimiter.Instance.EnsureRate();
            try
            {
                List <ImageEntityType> types = new List <ImageEntityType>
                {
                    ImageEntityType.AniDB_Cover,
                    ImageEntityType.AniDB_Character,
                    ImageEntityType.AniDB_Creator
                };
                foreach (var EntityTypeEnum in types)
                {
                    List <string> downloadURLs = new List <string>();
                    List <string> fileNames    = new List <string>();
                    switch (EntityTypeEnum)
                    {
                    case ImageEntityType.AniDB_Cover:
                        SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(AnimeID);
                        if (anime == null)
                        {
                            logger.Warn(
                                $"AniDB poster image failed to download: Can't find AniDB_Anime with ID: {AnimeID}");
                            return;
                        }

                        downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, anime.Picname));
                        fileNames.Add(anime.PosterPath);
                        break;

                    case ImageEntityType.AniDB_Character:
                        if (!ServerSettings.AniDB_DownloadCharacters)
                        {
                            continue;
                        }
                        var chrs = (from xref1 in RepoFactory.AniDB_Anime_Character.GetByAnimeID(AnimeID)
                                    select RepoFactory.AniDB_Character.GetByCharID(xref1.CharID))
                                   .Where(a => !string.IsNullOrEmpty(a?.PicName))
                                   .DistinctBy(a => a.CharID)
                                   .ToList();
                        if (chrs == null || chrs.Count == 0)
                        {
                            logger.Warn(
                                $"AniDB Character image failed to download: Can't find Character for anime: {AnimeID}");
                            return;
                        }

                        foreach (var chr in chrs)
                        {
                            downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, chr.PicName));
                            fileNames.Add(chr.GetPosterPath());
                        }

                        ShokoService.CmdProcessorGeneral.QueueState = PrettyDescriptionCharacters;
                        break;

                    case ImageEntityType.AniDB_Creator:
                        if (!ServerSettings.AniDB_DownloadCreators)
                        {
                            continue;
                        }

                        var creators = (from xref1 in RepoFactory.AniDB_Anime_Character.GetByAnimeID(AnimeID)
                                        from xref2 in RepoFactory.AniDB_Character_Seiyuu.GetByCharID(xref1.CharID)
                                        select RepoFactory.AniDB_Seiyuu.GetBySeiyuuID(xref2.SeiyuuID))
                                       .Where(a => !string.IsNullOrEmpty(a?.PicName))
                                       .DistinctBy(a => a.SeiyuuID)
                                       .ToList();
                        if (creators == null || creators.Count == 0)
                        {
                            logger.Warn(
                                $"AniDB Seiyuu image failed to download: Can't find Seiyuus for anime: {AnimeID}");
                            return;
                        }

                        foreach (var creator in creators)
                        {
                            downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, creator.PicName));
                            fileNames.Add(creator.GetPosterPath());
                        }

                        ShokoService.CmdProcessorGeneral.QueueState = PrettyDescriptionCreators;
                        break;
                    }

                    if (downloadURLs.Count == 0 || fileNames.All(a => string.IsNullOrEmpty(a)))
                    {
                        logger.Warn("Image failed to download: No URLs were generated. This should never happen");
                        return;
                    }


                    for (int i = 0; i < downloadURLs.Count; i++)
                    {
                        try
                        {
                            if (string.IsNullOrEmpty(fileNames[i]))
                            {
                                continue;
                            }
                            bool downloadImage = true;
                            bool fileExists    = File.Exists(fileNames[i]);
                            bool imageValid    = fileExists && Misc.IsImageValid(fileNames[i]);

                            if (imageValid && !ForceDownload)
                            {
                                downloadImage = false;
                            }

                            if (!downloadImage)
                            {
                                continue;
                            }

                            string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(),
                                                           Path.GetFileName(fileNames[i]));

                            try
                            {
                                if (fileExists)
                                {
                                    File.Delete(fileNames[i]);
                                }
                            }
                            catch (Exception ex)
                            {
                                Thread.CurrentThread.CurrentUICulture =
                                    CultureInfo.GetCultureInfo(ServerSettings.Culture);

                                logger.Warn(Resources.Command_DeleteError, fileNames, ex.Message);
                                return;
                            }

                            // If this has any issues, it will throw an exception, so the catch below will handle it
                            RecursivelyRetryDownload(downloadURLs[i], ref tempName, 0, 5);

                            // move the file to it's final location
                            // check that the final folder exists
                            string fullPath = Path.GetDirectoryName(fileNames[i]);
                            if (!Directory.Exists(fullPath))
                            {
                                Directory.CreateDirectory(fullPath);
                            }

                            File.Move(tempName, fileNames[i]);
                            logger.Info($"Image downloaded: {fileNames[i]} from {downloadURLs[i]}");
                        }
                        catch (WebException e)
                        {
                            logger.Warn("Error processing CommandRequest_DownloadAniDBImages: {0} ({1}) - {2}",
                                        downloadURLs[i],
                                        AnimeID,
                                        e.Message);
                        }catch (Exception e)
                        {
                            logger.Error("Error processing CommandRequest_DownloadAniDBImages: {0} ({1}) - {2}",
                                         downloadURLs[i],
                                         AnimeID,
                                         e);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_DownloadAniDBImages: {0} - {1}", AnimeID, ex);
            }
            AniDbRateLimiter.Instance.ResetRate();
        }
Beispiel #30
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_DownloadImage: {0}", EntityID);
            string downloadURL = string.Empty;

            try
            {
                ImageDownloadRequest req = null;
                switch (EntityTypeEnum)
                {
                case ImageEntityType.TvDB_Episode:
                    TvDB_Episode ep = RepoFactory.TvDB_Episode.GetByID(EntityID);
                    if (string.IsNullOrEmpty(ep?.Filename))
                    {
                        logger.Warn($"TvDB Episode image failed to download: Can't get episode with ID: {EntityID}");
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, ep, ForceDownload);
                    break;

                case ImageEntityType.TvDB_FanArt:
                    TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(EntityID);
                    if (string.IsNullOrEmpty(fanart?.BannerPath))
                    {
                        logger.Warn($"TvDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, fanart, ForceDownload);
                    break;

                case ImageEntityType.TvDB_Cover:
                    TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(EntityID);
                    if (string.IsNullOrEmpty(poster?.BannerPath))
                    {
                        logger.Warn($"TvDB Poster image failed to download: Can't find valid poster with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, poster, ForceDownload);
                    break;

                case ImageEntityType.TvDB_Banner:
                    TvDB_ImageWideBanner wideBanner = RepoFactory.TvDB_ImageWideBanner.GetByID(EntityID);
                    if (string.IsNullOrEmpty(wideBanner?.BannerPath))
                    {
                        logger.Warn($"TvDB Banner image failed to download: Can't find valid banner with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, wideBanner, ForceDownload);
                    break;

                case ImageEntityType.MovieDB_Poster:
                    MovieDB_Poster moviePoster = RepoFactory.MovieDB_Poster.GetByID(EntityID);
                    if (string.IsNullOrEmpty(moviePoster?.URL))
                    {
                        logger.Warn($"MovieDB Poster image failed to download: Can't find valid poster with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, moviePoster, ForceDownload);
                    break;

                case ImageEntityType.MovieDB_FanArt:
                    MovieDB_Fanart movieFanart = RepoFactory.MovieDB_Fanart.GetByID(EntityID);
                    if (string.IsNullOrEmpty(movieFanart?.URL))
                    {
                        logger.Warn($"MovieDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}");
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, movieFanart, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Cover:
                    SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(EntityID);
                    if (anime == null)
                    {
                        logger.Warn($"AniDB poster image failed to download: Can't find AniDB_Anime with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, anime, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Character:
                    AniDB_Character chr = RepoFactory.AniDB_Character.GetByCharID(EntityID);
                    if (chr == null)
                    {
                        logger.Warn($"AniDB Character image failed to download: Can't find AniDB Character with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, chr, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Creator:
                    AniDB_Seiyuu creator = RepoFactory.AniDB_Seiyuu.GetBySeiyuuID(EntityID);
                    if (creator == null)
                    {
                        logger.Warn($"AniDB Seiyuu image failed to download: Can't find Seiyuu with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, creator, ForceDownload);
                    break;
                }

                if (req == null)
                {
                    logger.Warn($"Image failed to download: No implementation found for {EntityTypeEnum}");
                    return;
                }

                List <string> fileNames    = new List <string>();
                List <string> downloadURLs = new List <string>();

                string fileNameTemp    = GetFileName(req, false);
                string downloadURLTemp = GetFileURL(req, false);

                fileNames.Add(fileNameTemp);
                downloadURLs.Add(downloadURLTemp);

                if (req.ImageType == ImageEntityType.TvDB_FanArt)
                {
                    fileNameTemp    = GetFileName(req, true);
                    downloadURLTemp = GetFileURL(req, true);

                    fileNames.Add(fileNameTemp);
                    downloadURLs.Add(downloadURLTemp);
                }

                for (int i = 0; i < fileNames.Count; i++)
                {
                    try
                    {
                        string fileName = fileNames[i];
                        downloadURL = downloadURLs[i];

                        bool downloadImage = true;
                        bool fileExists    = File.Exists(fileName);
                        bool imageValid    = fileExists && Misc.IsImageValid(fileName);

                        if (imageValid && !req.ForceDownload)
                        {
                            downloadImage = false;
                        }

                        if (!downloadImage)
                        {
                            continue;
                        }

                        string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(), Path.GetFileName(fileName));

                        try
                        {
                            if (fileExists)
                            {
                                File.Delete(fileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture);

                            logger.Warn(Resources.Command_DeleteError, fileName, ex.Message);
                            return;
                        }

                        // If this has any issues, it will throw an exception, so the catch below will handle it
                        RecursivelyRetryDownload(downloadURL, ref tempName, 0, 5);

                        // move the file to it's final location
                        // check that the final folder exists
                        string fullPath = Path.GetDirectoryName(fileName);
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }

                        File.Move(tempName, fileName);
                        logger.Info($"Image downloaded: {fileName} from {downloadURL}");
                    }
                    catch (WebException e)
                    {
                        logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL,
                                    EntityID,
                                    e.Message);
                        // Remove the record if the image doesn't exist or can't download
                        RemoveImageRecord();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL, EntityID,
                            ex.Message);
            }
        }