Beispiel #1
0
 public void TestCombineThreePaths()
 {
     Assert.AreEqual(Path.Combine(Path.Combine(longPathDirectory, "subdir1"), "filename.ext"),
                     Path.Combine(longPathDirectory, "subdir1", "filename.ext"));
 }
Beispiel #2
0
 public void TestCombineTwoPathsOneNull()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(uncDirectory, null));
 }
Beispiel #3
0
 public void TestCombineFourPathsTwoNull()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(uncDirectory, "subdir1", null, null));
 }
Beispiel #4
0
        public void TestCombineArrayOnePath()
        {
            var strings = new[] { uncDirectory };

            Assert.AreEqual(uncDirectory, Path.Combine(strings));
        }
Beispiel #5
0
 public void TestCombineArrayNullPath()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine((string[])null));
 }
Beispiel #6
0
 public void TestCombineWithEmpthPath2()
 {
     Assert.AreEqual(@"C:\test", Path.Combine(string.Empty, @"C:\test"));
 }
Beispiel #7
0
        public void TestGetFileNameWithoutExtension()
        {
            var filename = Path.Combine(uncDirectory, "filename.ext");

            Assert.AreEqual("filename", Path.GetFileNameWithoutExtension(filename));
        }
Beispiel #8
0
 public void TestCombineFourPathsThreeNulls()
 {
     Path.Combine(longPathDirectory, null, null, null);
 }
Beispiel #9
0
 public void TestCombineFourPathsFourNulls()
 {
     Path.Combine(null, null, null, null);
 }
Beispiel #10
0
 public void TestCombineThreePathsThreeNulls()
 {
     Path.Combine(null, null, null);
 }
Beispiel #11
0
 public void TestCombineFourPathsTwoNull()
 {
     Path.Combine(longPathDirectory, "subdir1", null, null);
 }
Beispiel #12
0
 public void TestCombineThreePathsTwoNulls()
 {
     Path.Combine(longPathDirectory, null, null);
 }
Beispiel #13
0
 public void TestCombineThreePathsOneNull()
 {
     Path.Combine(longPathDirectory, "subdir1", null);
 }
Beispiel #14
0
 public void TestCombineTwoPathsOneNull()
 {
     Path.Combine(longPathDirectory, null);
 }
Beispiel #15
0
 public void TestCombineWithNull()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(null, null));
 }
Beispiel #16
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 #17
0
 public void TestCombineWithEmpthPath1()
 {
     Assert.AreEqual("test", Path.Combine("test", string.Empty));
 }
Beispiel #18
0
        /// <summary>
        /// Setup system with needed network settings for JMMServer operation. Will invoke an escalation prompt to user. If changing port numbers please give new and old port.
        /// Do NOT add nancy hosted URLs to this. Nancy has an issue with ServiceHost stealing the reservations, and will handle its URLs itself.
        /// </summary>
        /// <param name="OldPort">The port JMMServer was set to run on.</param>
        /// <param name="Port">The port JMMServer will be running on.</param>
        /// <param name="FilePort">The port JMMServer will use for files.</param>
        /// <param name="OldFilePort">The port JMMServer was set to use for files.</param>
        public static bool SetNetworkRequirements(string Port, string FilePort, string OldPort, string OldFilePort)
        {
            string  BatchFile = Path.Combine(System.IO.Path.GetTempPath(), "NetworkConfig.bat");
            Process proc      = new Process
            {
                StartInfo =
                {
                    FileName        = "cmd.exe",
                    Arguments       = $@"/c {BatchFile}",
                    Verb            = "runas",
                    CreateNoWindow  = true,
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true
                }
            };

            try
            {
                StreamWriter BatchFileStream = new StreamWriter(BatchFile);

                //Cleanup previous
                try
                {
                    BatchFileStream.CleanUpDefaultPortsInNetSh(new[] { int.Parse(OldPort), int.Parse(OldFilePort) });
                    BatchFileStream.WriteLine(
                        "netsh advfirewall firewall delete rule name=\"JMM Server - Client Port\"");
                    BatchFileStream.WriteLine("netsh advfirewall firewall delete rule name=\"JMM Server - File Port\"");
                    BatchFileStream.WriteLine(
                        $@"netsh advfirewall firewall add rule name=""JMM Server - Client Port"" dir=in action=allow protocol=TCP localport={
                                Port
                            }");
                    Paths.ForEach(a => BatchFileStream.NetSh(a, "add", Port));
                    BatchFileStream.WriteLine(
                        $@"netsh advfirewall firewall add rule name=""JMM Server - File Port"" dir=in action=allow protocol=TCP localport={
                                FilePort
                            }");
                    BatchFileStream.NetSh("", "add", FilePort);
                }
                finally
                {
                    BatchFileStream.Close();
                }

                proc.Start();
                proc.WaitForExit();
                int exitCode = proc.ExitCode;
                proc.Close();
                File.Delete(BatchFile);
                if (exitCode != 0)
                {
                    logger.Error("Temporary batch process for netsh and firewall settings returned error code: " +
                                 exitCode);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                return(false);
            }

            logger.Info("Network requirements set.");

            return(true);
        }
Beispiel #19
0
 public void TestCombineWithEmpthPath1EndingInSeparator()
 {
     Assert.AreEqual(@"C:\test\test2", Path.Combine(@"C:\test\", "test2"));
 }
Beispiel #20
0
        /*
         * 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 #21
0
        public void TestCombineArray()
        {
            var strings = new[] { uncDirectory, "subdir1", "subdir2", "filename.ext" };

            Assert.AreEqual(Path.Combine(Path.Combine(Path.Combine(uncDirectory, "subdir1"), "subdir2"), "filename.ext"), Path.Combine(strings));
        }
Beispiel #22
0
        // Return true to cancel
        private bool OnPreviewDirectoryChanged(string subPath, bool pathExists)
        {
            var handler = this.PreviewDirectoryChanged;

            if (handler != null)
            {
                var ea = new PreviewDirectoryChangedEventArgs(this.Directory, subPath, pathExists);
                handler(this, ea);
                logger.Trace("PreviewDirectoryChanged with path {0}. Cancelled: {1}", Path.Combine(this.Directory, subPath), ea.Cancel);
                return(ea.Cancel);
            }
            return(false);
        }
Beispiel #23
0
        public void TestCombineArrayTwoPaths()
        {
            var strings = new[] { uncDirectory, "filename.ext" };

            Assert.AreEqual(Path.Combine(uncDirectory, "filename.ext"), Path.Combine(strings));
        }
Beispiel #24
0
 private void OnDirectoryChanged(string subPath)
 {
     logger.Info("Path Changed: {0}", Path.Combine(this.Directory, subPath));
     this.DirectoryChanged?.Invoke(this, new DirectoryChangedEventArgs(this.Directory, subPath));
 }
Beispiel #25
0
 public void TestCombineFourPaths()
 {
     Assert.AreEqual(Path.Combine(Path.Combine(Path.Combine(uncDirectory, "subdir1"), "subdir2"), "filename.ext"),
                     Path.Combine(uncDirectory, "subdir1", "subdir2", "filename.ext"));
 }
        public void DecryptCourse(List <ListViewItem> list)
        {
            if (string.IsNullOrWhiteSpace(txtCoursePath.Text))
            {
                MessageBox.Show("Please select course path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtDBPath.Text))
            {
                MessageBox.Show("Please select database path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtOutputPath.Text))
            {
                MessageBox.Show("Please select output path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            foreach (ListViewItem item in list)
            {
                CourseItem courseItem = listCourse.Where(r => r.Course.Name == item.Name).Select(r => r).FirstOrDefault();

                if (chkDecrypt.Checked)
                {
                    bgwDecrypt.ReportProgress(1, new { Text = $"Start to decrypt course \"{courseItem.Course.Title}\"", Color = Color.Magenta, newLine = true });

                    //Create new course path with the output path
                    var newCoursePath = Path.Combine(txtOutputPath.Text, this.CleanName(courseItem.Course.Title));

                    DirectoryInfo courseInfo = Directory.Exists(newCoursePath)
                        ? new DirectoryInfo(newCoursePath)
                        : Directory.CreateDirectory(newCoursePath);


                    //Get list all modules in current course
                    List <Module> listModules = courseItem.Course.Modules;

                    if (listModules.Count > 0)
                    {
                        // integer to add 1 if index should start at 1
                        int startAt1 = Convert.ToInt16(chkStartModuleIndexAt1.Checked);
                        //Get each module
                        foreach (Module module in listModules)
                        {
                            //Generate module hash name
                            string moduleHash = this.ModuleHash(module.Name, module.AuthorHandle);
                            //Generate module path
                            string moduleHashPath = Path.Combine(courseItem.CoursePath, moduleHash);
                            //Create new module path with decryption name
                            string newModulePath = Path.Combine(courseInfo.FullName, $"{(startAt1 + module.Index):00}. {module.Title}");

                            if (Directory.Exists(moduleHashPath))
                            {
                                DirectoryInfo moduleInfo = Directory.Exists(newModulePath)
                                    ? new DirectoryInfo(newModulePath)
                                    : Directory.CreateDirectory(newModulePath);
                                //Decrypt all videos in current module folder
                                this.DecryptAllVideos(moduleHashPath, module, moduleInfo.FullName);
                            }
                            else
                            {
                                bgwDecrypt.ReportProgress(1, new { Text = $"Folder {moduleHash} not found in the current course path", Color = Color.Red, newLine = true });
                            }
                        }
                    }
                    bgwDecrypt.ReportProgress(1, new { Text = $"\"{courseItem.Course.Title}\" complete!", Color = Color.Magenta, newLine = true });
                }

                if (chkDelete.Checked)
                {
                    try
                    {
                        Directory.Delete(courseItem.CoursePath, true);
                    }
                    catch (Exception ex)
                    {
                        bgwDecrypt.ReportProgress(1, new { Text = $"Delete folder course {courseItem.Course.Title} fail\n{ex.Message}", Color = Color.Gray, newLine = true });
                    }

                    try
                    {
                        RemoveCourseInDb(courseItem.CoursePath);
                    }
                    catch (Exception ex)
                    {
                        bgwDecrypt.ReportProgress(1, new { Text = $"Delete course {courseItem.Course.Title} from db fail\n{ex.Message}", Color = Color.Gray, newLine = true });
                    }


                    bgwDecrypt.ReportProgress(1, new { Text = $"Delete course {courseItem.Course.Title} success!", Color = Color.Magenta, newLine = true });
                }
            }

            bgwDecrypt.ReportProgress(100);
        }
Beispiel #27
0
 public void TestCombineThreePathsThreeNulls()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(null, null, null));
 }
 public override void CreateDirectory(string name)
 {
     Directory.CreateDirectory(Path.Combine(Name, name));
 }
Beispiel #29
0
 public void TestCombineFourPathsThreeNulls()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(uncDirectory, null, null, null));
 }
Beispiel #30
0
 public void TestCombineArrayNullPath()
 {
     Path.Combine((string[])null);
 }