public void TestGetFilesRecursiveWithSearchWithNoResults() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { Assert.IsTrue(Directory.Exists(tempLongPathFilename)); var randomFileName = Util.CreateNewEmptyFile(tempLongPathFilename); var files = Directory.GetFiles(uncDirectory, "gibberish", SearchOption.AllDirectories).ToArray(); Assert.AreEqual(0, files.Length); Assert.IsFalse(files.Contains(uncFilePath)); Assert.IsFalse(files.Contains(randomFileName)); } finally { const bool recursive = true; Directory.Delete(tempLongPathFilename, recursive); } }
public void TestEnumerateRecursiveFileSystemEntriesWithSearch() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { Assert.IsTrue(Directory.Exists(tempLongPathFilename)); var randomFileName = Util.CreateNewEmptyFile(tempLongPathFilename); var entries = Directory.EnumerateFileSystemEntries(uncDirectory, "*", SearchOption.AllDirectories).ToArray(); Assert.AreEqual(3, entries.Length); Assert.IsTrue(entries.Contains(uncFilePath)); Assert.IsTrue(entries.Contains(randomFileName)); } finally { const bool recursive = true; Directory.Delete(tempLongPathFilename, recursive); } }
public static string GetBaseImagesPath() { lock (assemblyLock) { if (Directory.Exists(AppSettings.ImagesPath)) { return(AppSettings.ImagesPath); } string serverpath = AppSettings.JMMServerImagePath; if (Directory.Exists(serverpath)) { return(serverpath); } serverpath = AppSettings.DefaultImagePath; if (!Directory.Exists(serverpath)) { Directory.CreateDirectory(serverpath); } return(serverpath); } }
public void TearDown() { try { if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception e) { Trace.WriteLine("Exception {0} deleting \"filePath\"", e.ToString()); throw; } finally { if (Directory.Exists(directory)) { Directory.Delete(directory, true); } } }
public void TearDown() { try { if (File.Exists(longPathFilename)) { File.Delete(longPathFilename); } } catch (Exception e) { Trace.WriteLine("Exception {0} deleting \"longPathFilename\"", e.ToString()); throw; } finally { if (Directory.Exists(longPathRoot)) { Directory.Delete(longPathRoot, true); } } }
public void TestMove() { var tempLongPathFilename1 = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename1); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename1))); var tempLongPathFilename2 = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename2); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename2))); string destinationPath = Path.GetFullPath(Path.Combine(tempLongPathFilename1, Path.GetFileName(tempLongPathFilename2))); Directory.Move(tempLongPathFilename2, destinationPath); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename1))); Assert.IsFalse(Directory.Exists(Path.GetFullPath(tempLongPathFilename2))); Assert.IsTrue(Directory.Exists(destinationPath)); const bool recursive = true; Directory.Delete(tempLongPathFilename1, recursive); Directory.Delete(tempLongPathFilename2, recursive); }
public void TestGetRecursiveFilesWithSubsetSearch() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { Assert.IsTrue(Directory.Exists(tempLongPathFilename)); var randomFileName = Util.CreateNewEmptyFile(tempLongPathFilename); var searchPattern = Path.GetFileName(randomFileName).Substring(0, 3) + "*" + Path.GetExtension(randomFileName); var files = Directory.GetFiles(uncDirectory, searchPattern, SearchOption.AllDirectories).ToArray(); Assert.AreEqual(1, files.Length); Assert.IsFalse(files.Contains(uncFilePath)); Assert.IsTrue(files.Contains(randomFileName)); } finally { const bool recursive = true; Directory.Delete(tempLongPathFilename, recursive); } }
public static string GetAniDBImagePath(int animeID) { string subFolder = ""; string sid = animeID.ToString(); if (sid.Length == 1) { subFolder = sid; } else { subFolder = sid.Substring(0, 2); } string filePath = Path.Combine(GetBaseAniDBImagesPath(), subFolder); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } return(filePath); }
public static bool GrantAccess(string path) { if (IsLinux) { return(true); //TODO: Implement properly, but as linux uses $HOME for the path, we should be fine. } if (Directory.Exists(path)) { List <string> perms = Misc.RecursiveGetDirectoriesWithoutEveryonePermission(path); if (perms.Count > 0) { bool result = Misc.RecursiveSetDirectoriesToEveryoneFullControlPermission(perms); if (result) { perms = Misc.RecursiveGetDirectoriesWithoutEveryonePermission(path); if (perms.Count > 0) { result = false; } } if (!result) { if (!IsAdministrator()) { logger.Info("Needed to set '" + path + "' permissions and failed, restarting as admin."); RestartAsAdmin(); } else { logger.Error("Unable to set Everyone permissions to '" + path + "' directory, or subdirectories, please chkdsk or set everyone permissions at hand."); return(false); } } } } return(true); }
public static string GetLatestFileOfPattern(string folder, string searchPattern) { Contract.Requires(!string.IsNullOrEmpty(folder)); Contract.Requires(!string.IsNullOrEmpty(searchPattern)); if (!Directory.Exists(folder)) { return(null); } var files = GetFiles(folder, searchPattern); if (files.Length == 0) { return(null); } if (files.Length == 1) { return(files[0]); } // If a pattern is present in the folder this is not going to work... var newset = new DateTime(0); string lastFile = null; foreach (var fileName in files) { var fileTime = FileInfo(fileName).LastWriteTime; if (fileTime <= newset) { continue; } newset = fileTime; lastFile = fileName; } return(lastFile); }
static void ProcessArchive(string rootPath, string folder, string file, IEnumerable <string> files, string destFolder) { if (Regex.IsMatch(file, @"(?i)\.(rar|r00|zip)$")) { var zipSize = GetAssociatedArchives(file, files).Sum(archiveFile => new FileInfo(archiveFile).Length); var tempPath = GetTempPath(zipSize * 2); var zipContentsPath = tempPath + folder.Substring(rootPath.Length) + Path.GetFileName(file); Console.WriteLine("Extracting {0} => {1}", Path.GetFileName(file), zipContentsPath); if (StartProcess(@"C:\Program Files\WinRAR\WinRar.exe", $"x -o+ -ibck -inul -y \"{file}\" \"{zipContentsPath}\"\\") < 2 && Directory.Exists(zipContentsPath)) { MarkFolderWritable(zipContentsPath); ProcessFolder(tempPath, zipContentsPath, destFolder, true, false); } else { Console.WriteLine("Error while extracting {0}", file); throw new UnzipError(); } Directory.Delete(zipContentsPath, true); } /* * else if (Path.GetExtension(file) == ".iso") * { * Console.WriteLine("Mounting {0} => G:", file); * StartProcess(@"C:\Program Files\PowerISO\piso.exe", string.Format("mount \"{0}\" G:", file)); * var isoSize = new FileInfo(file).Length; * var tempPath = GetTempPath(isoSize); * var isoContentsPath = tempPath + folder.Substring(rootPath.Length); * CopyFiles("G:", isoContentsPath, false); * MarkFolderWritable(isoContentsPath); * ProcessFolder(tempPath, isoContentsPath, destFolder, true, true, string.Format(@"\{0}", Path.GetFileName(file))); * Unmount(); * Directory.Delete(isoContentsPath, true); * } * */ }
public bool Exists(string path) { return(Directory.Exists(path)); }
public void MoveFileIfRequired() { try { logger.Trace("Attempting to move file: {0}", this.FullServerPath); // check if this file is in the drop folder // otherwise we don't need to move it if (this.ImportFolder.IsDropSource == 0) { logger.Trace("Not moving file as it is NOT in the drop folder: {0}", this.FullServerPath); return; } if (!File.Exists(this.FullServerPath)) { logger.Error("Could not find the file to move: {0}", this.FullServerPath); return; } // find the default destination ImportFolder destFolder = null; ImportFolderRepository repFolders = new ImportFolderRepository(); foreach (ImportFolder fldr in repFolders.GetAll()) { if (fldr.IsDropDestination == 1) { destFolder = fldr; break; } } if (destFolder == null) { return; } if (!System.IO.Directory.Exists(destFolder.ImportFolderLocation)) { return; } // keep the original drop folder for later (take a copy, not a reference) ImportFolder dropFolder = this.ImportFolder; // we can only move the file if it has an anime associated with it List <CrossRef_File_Episode> xrefs = this.EpisodeCrossRefs; if (xrefs.Count == 0) { return; } CrossRef_File_Episode xref = xrefs[0]; // find the series associated with this episode AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByAnimeID(xref.AnimeID); if (series == null) { return; } // find where the other files are stored for this series // if there are no other files except for this one, it means we need to create a new location bool foundLocation = false; string newFullPath = ""; // sort the episodes by air date, so that we will move the file to the location of the latest episode List <AnimeEpisode> allEps = series.GetAnimeEpisodes().OrderByDescending(a => a.AniDB_EpisodeID).ToList(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); CrossRef_File_EpisodeRepository repFileEpXref = new CrossRef_File_EpisodeRepository(); foreach (AnimeEpisode ep in allEps) { // check if this episode belongs to more than one anime // if it does we will ignore it List <CrossRef_File_Episode> fileEpXrefs = repFileEpXref.GetByEpisodeID(ep.AniDB_EpisodeID); int? animeID = null; bool crossOver = false; foreach (CrossRef_File_Episode fileEpXref in fileEpXrefs) { if (!animeID.HasValue) { animeID = fileEpXref.AnimeID; } else { if (animeID.Value != fileEpXref.AnimeID) { crossOver = true; } } } if (crossOver) { continue; } foreach (VideoLocal vid in ep.GetVideoLocals()) { if (vid.VideoLocalID != this.VideoLocalID) { // make sure this folder is not the drop source if (vid.ImportFolder.IsDropSource == 1) { continue; } string thisFileName = vid.FullServerPath; string folderName = Path.GetDirectoryName(thisFileName); if (Directory.Exists(folderName)) { newFullPath = folderName; foundLocation = true; break; } } } if (foundLocation) { break; } } if (!foundLocation) { // we need to create a new folder string newFolderName = Utils.RemoveInvalidFolderNameCharacters(series.GetAnime().PreferredTitle); newFullPath = Path.Combine(destFolder.ImportFolderLocation, newFolderName); if (!Directory.Exists(newFullPath)) { Directory.CreateDirectory(newFullPath); } } int newFolderID = 0; string newPartialPath = ""; string newFullServerPath = Path.Combine(newFullPath, Path.GetFileName(this.FullServerPath)); DataAccessHelper.GetShareAndPath(newFullServerPath, repFolders.GetAll(), ref newFolderID, ref newPartialPath); logger.Info("Moving file from {0} to {1}", this.FullServerPath, newFullServerPath); if (File.Exists(newFullServerPath)) { logger.Trace( "Not moving file as it already exists at the new location, deleting source file instead: {0} --- {1}", this.FullServerPath, newFullServerPath); // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(this.FullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this, true); } else { string originalFileName = this.FullServerPath; FileInfo fi = new FileInfo(originalFileName); // now move the file File.Move(this.FullServerPath, newFullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this, true); try { // move any subtitle files foreach (string subtitleFile in Utils.GetPossibleSubtitleFiles(originalFileName)) { if (File.Exists(subtitleFile)) { FileInfo fiSub = new FileInfo(subtitleFile); string newSubPath = Path.Combine(Path.GetDirectoryName(newFullServerPath), fiSub.Name); if (File.Exists(newSubPath)) { // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(newSubPath); } else { File.Move(subtitleFile, newSubPath); } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } // check for any empty folders in drop folder // only for the drop folder if (dropFolder.IsDropSource == 1) { foreach ( string folderName in Directory.GetDirectories(dropFolder.ImportFolderLocation, "*", SearchOption.AllDirectories)) { if (Directory.Exists(folderName)) { if (Directory.GetFiles(folderName, "*", SearchOption.AllDirectories).Length == 0) { try { Directory.Delete(folderName, true); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } } } } } } catch (Exception ex) { string msg = string.Format("Could not move file: {0} -- {1}", this.FullServerPath, ex.ToString()); logger.ErrorException(msg, ex); } }
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.CourseName == item.Name).Select(r => r).FirstOrDefault(); if (chkDecrypt.Checked) { bgwDecrypt.ReportProgress(1, new { Text = "Start to decrypt course \"" + courseItem.Course.CourseTitle + "\"", Color = Color.Magenta, newLine = true }); //Create new course path with the output path var newCoursePath = Path.Combine(txtOutputPath.Text, this.CleanName(courseItem.Course.CourseTitle)); 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.ModuleName, 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.ModuleIndex < 10 ? "0" : "") + (startAt1 + module.ModuleIndex) + ". " + module.ModuleTitle); 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 + " cannot be found in the current course path.", Color = Color.Red, newLine = true }); } } } bgwDecrypt.ReportProgress(1, new { Text = "\"" + courseItem.Course.CourseTitle + "\" 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.CourseTitle + " fail!" + Environment.NewLine + ex.Message, Color = Color.Gray, newLine = true }); } try { RemoveCourseInDb(courseItem.CoursePath); } catch (Exception ex) { bgwDecrypt.ReportProgress(1, new { Text = "Delete course " + courseItem.Course.CourseTitle + " from Db fail!" + Environment.NewLine + ex.Message, Color = Color.Gray, newLine = true }); } bgwDecrypt.ReportProgress(1, new { Text = "Delete course " + courseItem.Course.CourseTitle + " success!", Color = Color.Magenta, newLine = true }); } } bgwDecrypt.ReportProgress(100); }
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 Log { Text = $"Start to decrypt course \"{courseItem.Course.Title}\"", TextColor = Color.Magenta, NewLine = true, IsError = 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); if (chkCopyImage.Checked && File.Exists($"{courseItem.CoursePath}\\image.jpg")) { File.Copy($"{courseItem.CoursePath}\\image.jpg", $"{newCoursePath}\\image.jpg", true); } //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 Log { Text = $"Folder {moduleHash} not found in the current course path", TextColor = Color.Red, NewLine = true, IsError = true }); } } } bgwDecrypt.ReportProgress(1, new Log { Text = $"Decrypt \"{courseItem.Course.Title}\" complete!", TextColor = Color.Magenta, NewLine = true, IsError = true }); } if (chkDelete.Checked) { try { Directory.Delete(courseItem.CoursePath, true); } catch (Exception ex) { bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete folder course {courseItem.Course.Title} fail\n{ex.Message}", TextColor = Color.Gray, NewLine = true, IsError = true }); } try { RemoveCourseInDb(courseItem.CoursePath); } catch (Exception ex) { bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete course {courseItem.Course.Title} from db fail\n{ex.Message}", TextColor = Color.Gray, NewLine = true, IsError = true }); } bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete course {courseItem.Course.Title} success!", TextColor = Color.Magenta, NewLine = true }); } } bgwDecrypt.ReportProgress(100); }
public void ReadCourse(string coursePath, string dbPath) { try { if (Directory.Exists(coursePath) && this.InitDb(dbPath)) { bgwGetCourse.ReportProgress(1, new Log() { Text = "Getting course data . . .", TextColor = Color.Green, NewLine = true }); List <string> folderList = Directory.GetDirectories(coursePath, "*", SearchOption.TopDirectoryOnly).ToList(); logger.Debug($"FolderList1: {folderList.Count}"); folderList = folderList.Where(r => Directory.GetDirectories(r, "*", SearchOption.TopDirectoryOnly).Length > 0).ToList(); logger.Debug($"FolderList2: {folderList.Count}"); listCourse = folderList.Select(r => new CourseItem() { CoursePath = r, Course = this.GetCourseFromDb(r) }).Where(r => r.Course != null).OrderBy(r => r.Course.Title).ToList(); logger.Debug($"listCourse1: {listCourse.Count}"); listCourse = listCourse.Where(c => c.Course.IsDownloaded).ToList(); logger.Debug($"listCourse2: {listCourse.Count}"); foreach (CourseItem item in listCourse) { Image img, thumb; try { img = File.Exists(item.CoursePath + @"\image.jpg") ? Image.FromFile(item.CoursePath + @"\image.jpg", true) : new Bitmap(100, 100); thumb = img.GetThumbnailImage(160, 90, () => false, IntPtr.Zero); img.Dispose(); } catch { thumb = new Bitmap(160, 90); Graphics g = Graphics.FromImage(thumb); g.Clear(Color.Black); } ListViewItem listItem = new ListViewItem() { ImageKey = item.Course.Name, Name = item.Course.Name, Text = item.Course.Title }; bgwGetCourse.ReportProgress(1, new { Item = listItem, Image = thumb }); } bgwGetCourse.ReportProgress(1, new Log() { Text = $"Complete! Total: {listCourse.Count} courses", TextColor = Color.Green, NewLine = true }); bgwGetCourse.ReportProgress(100); } } catch (Exception ex) { MessageBox.Show(ex.Message); logger.Error(ex); } }
public void TestInUseMove() { const bool recursive = true; #if SHORT_SOURCE var tempPathFilename1 = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), System.IO.Path.GetRandomFileName()); System.IO.Directory.CreateDirectory(tempPathFilename1); Assert.IsTrue(System.IO.Directory.Exists(Path.GetFullPath(tempPathFilename1))); var tempPathFilename2 = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), System.IO.Path.GetRandomFileName()); System.IO.Directory.CreateDirectory(tempPathFilename2); Assert.IsTrue(System.IO.Directory.Exists(System.IO.Path.GetFullPath(tempPathFilename2))); try { using ( var writer = System.IO.File.CreateText(System.IO.Path.Combine(tempPathFilename2, "TestInUseMove"))) { string destinationPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(tempPathFilename1, System.IO.Path.GetFileName(tempPathFilename2))); System.IO.Directory.Move(tempPathFilename2, destinationPath); Assert.IsTrue(System.IO.Directory.Exists(System.IO.Path.GetFullPath(tempPathFilename1))); Assert.IsFalse(System.IO.Directory.Exists(System.IO.Path.GetFullPath(tempPathFilename2))); Assert.IsTrue(System.IO.Directory.Exists(destinationPath)); } } catch (Exception e) { throw; } finally { Directory.Delete(tempPathFilename1, recursive); Directory.Delete(tempPathFilename2, recursive); } #endif Assert.Throws <IOException>(() => { var tempLongPathFilename1 = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename1); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename1))); var tempLongPathFilename2 = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename2); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename2))); try { using ( var writer = File.CreateText(Path.Combine(tempLongPathFilename2, "TestInUseMove"))) { string destinationPath = Path.GetFullPath(Path.Combine(tempLongPathFilename1, Path.GetFileName(tempLongPathFilename2))); Directory.Move(tempLongPathFilename2, destinationPath); Assert.IsTrue(Directory.Exists(Path.GetFullPath(tempLongPathFilename1))); Assert.IsFalse(Directory.Exists(Path.GetFullPath(tempLongPathFilename2))); Assert.IsTrue(Directory.Exists(destinationPath)); } } finally { Directory.Delete(tempLongPathFilename1, recursive); Directory.Delete(tempLongPathFilename2, recursive); } }); }
public void TestExistsOnFile() { Assert.IsFalse(Directory.Exists(uncFilePath)); }
public void TestExistsOnNonexistentFile() { Assert.IsFalse(Directory.Exists(new StringBuilder(uncDirectory).Append(@"\").Append("does-not-exist").ToString())); }
public void TestExists() { Assert.IsTrue(Directory.Exists(uncDirectory)); }
public void TearDown() { Directory.Delete(longPathRoot, true); Debug.Assert(!Directory.Exists(longPathDirectory)); }
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); } }
public static void ClassCleanup() { Directory.Delete(longPathRoot, true); Debug.Assert(!Directory.Exists(longPathDirectory)); }
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(); }