Beispiel #1
0
        private void RecursivelyRetryDownload(string downloadURL, ref string tempFilePath, int count, int maxretry)
        {
            try
            {
                // download image
                if (downloadURL.Length <= 0)
                {
                    return;
                }
                using (WebClient client = new WebClient())
                {
                    client.Headers.Add("user-agent", "JMM");
                    //OnImageDownloadEvent(new ImageDownloadEventArgs("", req, ImageDownloadEventType.Started));
                    //BaseConfig.MyAnimeLog.Write("ProcessImages: Download: {0}  *** to ***  {1}", req.URL, fullName);

                    byte[] bytes = client.DownloadData(downloadURL);
                    if (bytes.Length < 4)
                    {
                        throw new WebException(
                                  "The image download stream returned less than 4 bytes (a valid image has 2-4 bytes in the header)");
                    }

                    ImageFormatEnum imageFormat = Misc.GetImageFormat(bytes);
                    string          extension;
                    switch (imageFormat)
                    {
                    case ImageFormatEnum.bmp:
                        extension = ".bmp";
                        break;

                    case ImageFormatEnum.gif:
                        extension = ".gif";
                        break;

                    case ImageFormatEnum.jpeg:
                        extension = ".jpeg";
                        break;

                    case ImageFormatEnum.png:
                        extension = ".png";
                        break;

                    case ImageFormatEnum.tiff:
                        extension = ".tiff";
                        break;

                    default: throw new WebException("The image download stream returned an invalid image");
                    }

                    if (extension.Length <= 0)
                    {
                        return;
                    }
                    string newFile = Path.ChangeExtension(tempFilePath, extension);
                    if (newFile == null)
                    {
                        return;
                    }

                    if (File.Exists(newFile))
                    {
                        File.Delete(newFile);
                    }
                    using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                    tempFilePath = newFile;
                }
            }
            catch (WebException)
            {
                if (count + 1 >= maxretry)
                {
                    throw;
                }
                Thread.Sleep(500);
                RecursivelyRetryDownload(downloadURL, ref tempFilePath, count + 1, maxretry);
            }
        }
Beispiel #2
0
 public void TestCombineFourPaths()
 {
     Assert.AreEqual(Path.Combine(Path.Combine(Path.Combine(uncDirectory, "subdir1"), "subdir2"), "filename.ext"),
                     Path.Combine(uncDirectory, "subdir1", "subdir2", "filename.ext"));
 }
Beispiel #3
0
 public void TestCombineThreePathsTwoNulls()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(uncDirectory, null, null));
 }
Beispiel #4
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 #5
0
        public void TestCombineArrayTwoPaths()
        {
            var strings = new[] { uncDirectory, "filename.ext" };

            Assert.AreEqual(Path.Combine(uncDirectory, "filename.ext"), Path.Combine(strings));
        }
Beispiel #6
0
 public void TestCombineWithEmpthPath1EndingInSeparator()
 {
     Assert.AreEqual(@"C:\test\test2", Path.Combine(@"C:\test\", "test2"));
 }
Beispiel #7
0
 public void TestHasExtensionWithoutExtension()
 {
     Assert.IsFalse(Path.HasExtension(uncDirectory));
 }
Beispiel #8
0
 public void TestGetRootLength()
 {
     Assert.AreEqual(15, Path.GetRootLength(uncFilePath));
 }
Beispiel #9
0
 public void TestGetRootLengthWithUnc()
 {
     Assert.AreEqual(23, Path.GetRootLength(@"\\servername\sharename\dir\filename.exe"));
 }
Beispiel #10
0
 public void TestGetInvalidPathChars()
 {
     Assert.IsTrue(Path.GetInvalidPathChars().SequenceEqual(System.IO.Path.GetInvalidPathChars()));
 }
Beispiel #11
0
 public void TestIsDirectorySeparator()
 {
     Assert.IsTrue(Path.IsDirectorySeparator(System.IO.Path.DirectorySeparatorChar));
     Assert.IsTrue(Path.IsDirectorySeparator(System.IO.Path.AltDirectorySeparatorChar));
 }
Beispiel #12
0
 public void TestLongPathDirectoryNameWithInvalidChars()
 {
     Assert.Throws <ArgumentException>(() => Path.GetDirectoryName(uncDirectory + '<'));
 }
Beispiel #13
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 #14
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 #15
0
 public void TestCombineWithEmpthPath1()
 {
     Assert.AreEqual("test", Path.Combine("test", string.Empty));
 }
Beispiel #16
0
        public void TestGetPathRootWithNullPath()
        {
            var root = Path.GetPathRoot(null);

            Assert.IsNull(root);
        }
Beispiel #17
0
 public void TestCombineWithEmpthPath2()
 {
     Assert.AreEqual(@"C:\test", Path.Combine(string.Empty, @"C:\test"));
 }
Beispiel #18
0
 public void TestNormalizeLongPathWithJustUncPrefix()
 {
     Assert.Throws <ArgumentException>(() => Path.NormalizeLongPath(@"\\"));
 }
Beispiel #19
0
 public void TestHasExtensionWithExtension()
 {
     Assert.IsTrue(Path.HasExtension(uncFilePath));
 }
Beispiel #20
0
        public void TestNormalizeLongPathWith()
        {
            string result = Path.NormalizeLongPath(uncDirectory);

            Assert.IsNotNull(result);
        }
Beispiel #21
0
        public void TestGetFileNameWithoutExtension()
        {
            var filename = Path.Combine(uncDirectory, "filename.ext");

            Assert.AreEqual("filename", Path.GetFileNameWithoutExtension(filename));
        }
Beispiel #22
0
        public void TestTryNormalizeLongPathWithJustUncPrefix()
        {
            string path;

            Assert.IsFalse(Path.TryNormalizeLongPath(@"\\", out path));
        }
Beispiel #23
0
        public void TestCombineArrayOnePath()
        {
            var strings = new[] { uncDirectory };

            Assert.AreEqual(uncDirectory, Path.Combine(strings));
        }
Beispiel #24
0
        public void TestNormalizeLongPathWithEmptyPath()
        {
            string path;

            Assert.IsFalse(Path.TryNormalizeLongPath(String.Empty, out path));
        }
Beispiel #25
0
 public void TestCombineArrayNullPath()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine((string[])null));
 }
Beispiel #26
0
        public void TestTryNormalizeLongPathWithNullPath()
        {
            string path;

            Assert.IsFalse(Path.TryNormalizeLongPath(null, out path));
        }
Beispiel #27
0
 public void TestCombineThreePathsOneNull()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(uncDirectory, "subdir1", null));
 }
Beispiel #28
0
 public void TestCombineWithNull()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(null, null));
 }
Beispiel #29
0
 public void TestCombineThreePathsThreeNulls()
 {
     Assert.Throws <ArgumentNullException>(() => Path.Combine(null, null, null));
 }
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);
            }
        }