public static string DeleteImportFolder(int importFolderID) { try { ImportFolderRepository repNS = new ImportFolderRepository(); ImportFolder ns = repNS.GetByID(importFolderID); if (ns == null) return "Could not find Import Folder ID: " + importFolderID; // first delete all the files attached to this import folder Dictionary<int, AnimeSeries> affectedSeries = new Dictionary<int, AnimeSeries>(); VideoLocalRepository repVids = new VideoLocalRepository(); foreach (VideoLocal vid in repVids.GetByImportFolder(importFolderID)) { //Thread.Sleep(5000); logger.Info("Deleting video local record: {0}", vid.FullServerPath); AnimeSeries ser = null; List<AnimeEpisode> animeEpisodes = vid.GetAnimeEpisodes(); if (animeEpisodes.Count > 0) { ser = animeEpisodes[0].GetAnimeSeries(); if (ser != null && !affectedSeries.ContainsKey(ser.AnimeSeriesID)) affectedSeries.Add(ser.AnimeSeriesID, ser); } repVids.Delete(vid.VideoLocalID); } // delete any duplicate file records which reference this folder DuplicateFileRepository repDupFiles = new DuplicateFileRepository(); foreach (DuplicateFile df in repDupFiles.GetByImportFolder1(importFolderID)) repDupFiles.Delete(df.DuplicateFileID); foreach (DuplicateFile df in repDupFiles.GetByImportFolder2(importFolderID)) repDupFiles.Delete(df.DuplicateFileID); // delete the import folder repNS.Delete(importFolderID); ServerInfo.Instance.RefreshImportFolders(); foreach (AnimeSeries ser in affectedSeries.Values) { ser.QueueUpdateStats(); //StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID); } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } }
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); } }
public void RefreshImportFolders() { ImportFolders.Clear(); try { ImportFolderRepository repFolders = new ImportFolderRepository(); List <ImportFolder> fldrs = repFolders.GetAll(); foreach (ImportFolder ifolder in fldrs) { ImportFolders.Add(ifolder); } } catch (Exception ex) { Utils.ShowErrorMessage(ex); } }
public static void RunImport_DropFolders() { // get a complete list of files List<string> fileList = new List<string>(); ImportFolderRepository repNetShares = new ImportFolderRepository(); foreach (ImportFolder share in repNetShares.GetAll()) { if (!share.FolderIsDropSource) continue; logger.Debug("ImportFolder: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation); Utils.GetFilesForImportFolder(share.ImportFolderLocation, ref fileList); } // get a list of all the shares we are looking at int filesFound = 0, videosFound = 0; int i = 0; // get a list of all files in the share foreach (string fileName in fileList) { i++; filesFound++; logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName); if (!FileHashHelper.IsVideo(fileName)) continue; videosFound++; CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false); cr_hashfile.Save(); } logger.Debug("Found {0} files", filesFound); logger.Debug("Found {0} videos", videosFound); }
private VideoLocal ProcessFile_LocalInfo() { // hash and read media info for file int nshareID = -1; string filePath = ""; ImportFolderRepository repNS = new ImportFolderRepository(); List <ImportFolder> shares = repNS.GetAll(); DataAccessHelper.GetShareAndPath(FileName, shares, ref nshareID, ref filePath); if (!File.Exists(FileName)) { logger.Error("File does not exist: {0}", FileName); return(null); } int numAttempts = 0; // Wait 3 minutes seconds before giving up on trying to access the file while ((!CanAccessFile(FileName)) && (numAttempts < 180)) { numAttempts++; Thread.Sleep(1000); Console.WriteLine("Attempt # " + numAttempts.ToString()); } // if we failed to access the file, get ouuta here if (numAttempts == 180) { logger.Error("Could not access file: " + FileName); return(null); } // check if we have already processed this file VideoLocal vlocal = null; VideoLocalRepository repVidLocal = new VideoLocalRepository(); FileNameHashRepository repFNHash = new FileNameHashRepository(); List <VideoLocal> vidLocals = repVidLocal.GetByFilePathAndShareID(filePath, nshareID); FileInfo fi = new FileInfo(FileName); if (vidLocals.Count > 0) { vlocal = vidLocals[0]; logger.Trace("VideoLocal record found in database: {0}", vlocal.VideoLocalID); if (ForceHash) { vlocal.FileSize = fi.Length; vlocal.DateTimeUpdated = DateTime.Now; } } else { logger.Trace("VideoLocal, creating new record"); vlocal = new VideoLocal(); vlocal.DateTimeUpdated = DateTime.Now; vlocal.DateTimeCreated = vlocal.DateTimeUpdated; vlocal.FilePath = filePath; vlocal.FileSize = fi.Length; vlocal.ImportFolderID = nshareID; vlocal.Hash = ""; vlocal.CRC32 = ""; vlocal.MD5 = ""; vlocal.SHA1 = ""; vlocal.IsIgnored = 0; vlocal.IsVariation = 0; } // check if we need to get a hash this file Hashes hashes = null; if (string.IsNullOrEmpty(vlocal.Hash) || ForceHash) { // try getting the hash from the CrossRef if (!ForceHash) { CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); List <CrossRef_File_Episode> crossRefs = repCrossRefs.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (crossRefs.Count == 1) { vlocal.Hash = crossRefs[0].Hash; vlocal.HashSource = (int)HashSource.DirectHash; } } // try getting the hash from the LOCAL cache if (!ForceHash && string.IsNullOrEmpty(vlocal.Hash)) { List <FileNameHash> fnhashes = repFNHash.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (fnhashes != null && fnhashes.Count > 1) { // if we have more than one record it probably means there is some sort of corruption // lets delete the local records foreach (FileNameHash fnh in fnhashes) { repFNHash.Delete(fnh.FileNameHashID); } } if (fnhashes != null && fnhashes.Count == 1) { logger.Trace("Got hash from LOCAL cache: {0} ({1})", FileName, fnhashes[0].Hash); vlocal.Hash = fnhashes[0].Hash; vlocal.HashSource = (int)HashSource.WebCacheFileName; } } // hash the file if (string.IsNullOrEmpty(vlocal.Hash) || ForceHash) { DateTime start = DateTime.Now; logger.Trace("Calculating hashes for: {0}", FileName); // update the VideoLocal record with the Hash hashes = FileHashHelper.GetHashInfo(FileName, true, MainWindow.OnHashProgress, ServerSettings.Hash_CRC32, ServerSettings.Hash_MD5, ServerSettings.Hash_SHA1); TimeSpan ts = DateTime.Now - start; logger.Trace("Hashed file in {0} seconds --- {1} ({2})", ts.TotalSeconds.ToString("#0.0"), FileName, Utils.FormatByteSize(vlocal.FileSize)); vlocal.Hash = hashes.ed2k; vlocal.CRC32 = hashes.crc32; vlocal.MD5 = hashes.md5; vlocal.SHA1 = hashes.sha1; vlocal.HashSource = (int)HashSource.DirectHash; } // We should have a hash by now // before we save it, lets make sure there is not any other record with this hash (possible duplicate file) VideoLocal vidTemp = repVidLocal.GetByHash(vlocal.Hash); if (vidTemp != null) { // don't delete it, if it is actually the same record if (vidTemp.VideoLocalID != vlocal.VideoLocalID) { // delete the VideoLocal record logger.Warn("Deleting duplicate video file record"); logger.Warn("---------------------------------------------"); logger.Warn("Keeping record for: {0}", vlocal.FullServerPath); logger.Warn("Deleting record for: {0}", vidTemp.FullServerPath); logger.Warn("---------------------------------------------"); // check if we have a record of this in the database, if not create one DuplicateFileRepository repDups = new DuplicateFileRepository(); List <DuplicateFile> dupFiles = repDups.GetByFilePathsAndImportFolder(vlocal.FilePath, vidTemp.FilePath, vlocal.ImportFolderID, vidTemp.ImportFolderID); if (dupFiles.Count == 0) { dupFiles = repDups.GetByFilePathsAndImportFolder(vidTemp.FilePath, vlocal.FilePath, vidTemp.ImportFolderID, vlocal.ImportFolderID); } if (dupFiles.Count == 0) { DuplicateFile dup = new DuplicateFile(); dup.DateTimeUpdated = DateTime.Now; dup.FilePathFile1 = vlocal.FilePath; dup.FilePathFile2 = vidTemp.FilePath; dup.ImportFolderIDFile1 = vlocal.ImportFolderID; dup.ImportFolderIDFile2 = vidTemp.ImportFolderID; dup.Hash = vlocal.Hash; repDups.Save(dup); } repVidLocal.Delete(vidTemp.VideoLocalID); } } repVidLocal.Save(vlocal); // also save the filename to hash record // replace the existing records just in case it was corrupt FileNameHash fnhash = null; List <FileNameHash> fnhashes2 = repFNHash.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (fnhashes2 != null && fnhashes2.Count > 1) { // if we have more than one record it probably means there is some sort of corruption // lets delete the local records foreach (FileNameHash fnh in fnhashes2) { repFNHash.Delete(fnh.FileNameHashID); } } if (fnhashes2 != null && fnhashes2.Count == 1) { fnhash = fnhashes2[0]; } else { fnhash = new FileNameHash(); } fnhash.FileName = Path.GetFileName(vlocal.FilePath); fnhash.FileSize = vlocal.FileSize; fnhash.Hash = vlocal.Hash; fnhash.DateTimeUpdated = DateTime.Now; repFNHash.Save(fnhash); } // now check if we have stored a VideoInfo record bool refreshMediaInfo = false; VideoInfoRepository repVidInfo = new VideoInfoRepository(); VideoInfo vinfo = repVidInfo.GetByHash(vlocal.Hash); if (vinfo == null) { refreshMediaInfo = true; vinfo = new VideoInfo(); vinfo.Hash = vlocal.Hash; vinfo.Duration = 0; vinfo.FileSize = fi.Length; vinfo.DateTimeUpdated = DateTime.Now; vinfo.FileName = filePath; vinfo.AudioBitrate = ""; vinfo.AudioCodec = ""; vinfo.VideoBitrate = ""; vinfo.VideoBitDepth = ""; vinfo.VideoCodec = ""; vinfo.VideoFrameRate = ""; vinfo.VideoResolution = ""; repVidInfo.Save(vinfo); } else { // check if we need to update the media info if (vinfo.VideoCodec.Trim().Length == 0) { refreshMediaInfo = true; } else { refreshMediaInfo = false; } } if (refreshMediaInfo) { logger.Trace("Getting media info for: {0}", FileName); MediaInfoResult mInfo = FileHashHelper.GetMediaInfo(FileName, true); vinfo.AudioBitrate = string.IsNullOrEmpty(mInfo.AudioBitrate) ? "" : mInfo.AudioBitrate; vinfo.AudioCodec = string.IsNullOrEmpty(mInfo.AudioCodec) ? "" : mInfo.AudioCodec; vinfo.DateTimeUpdated = vlocal.DateTimeUpdated; vinfo.Duration = mInfo.Duration; vinfo.FileName = filePath; vinfo.FileSize = fi.Length; vinfo.VideoBitrate = string.IsNullOrEmpty(mInfo.VideoBitrate) ? "" : mInfo.VideoBitrate; vinfo.VideoBitDepth = string.IsNullOrEmpty(mInfo.VideoBitDepth) ? "" : mInfo.VideoBitDepth; vinfo.VideoCodec = string.IsNullOrEmpty(mInfo.VideoCodec) ? "" : mInfo.VideoCodec; vinfo.VideoFrameRate = string.IsNullOrEmpty(mInfo.VideoFrameRate) ? "" : mInfo.VideoFrameRate; vinfo.VideoResolution = string.IsNullOrEmpty(mInfo.VideoResolution) ? "" : mInfo.VideoResolution; vinfo.FullInfo = string.IsNullOrEmpty(mInfo.FullInfo) ? "" : mInfo.FullInfo; repVidInfo.Save(vinfo); } // now add a command to process the file CommandRequest_ProcessFile cr_procfile = new CommandRequest_ProcessFile(vlocal.VideoLocalID, false); cr_procfile.Save(); return(vlocal); }
public void MoveFileIfRequired() { // check if this file is in the drop folder // otherwise we don't need to move it if (this.ImportFolder.IsDropSource == 0) { return; } if (!File.Exists(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 (!Directory.Exists(destFolder.ImportFolderLocation)) { return; } // 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(); List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("AniDB_EpisodeID", true, SortType.eInteger)); allEps = Sorting.MultiSort <AnimeEpisode>(allEps, sortCriteria); foreach (AnimeEpisode ep in allEps) { 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().MainTitle); 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)) { // 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); } 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); 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 (this.ImportFolder.IsDropSource == 1) { foreach (string folderName in Directory.GetDirectories(this.ImportFolder.ImportFolderLocation, "*", SearchOption.AllDirectories)) { if (Directory.Exists(folderName)) { if (Directory.GetFiles(folderName, "*", SearchOption.AllDirectories).Length == 0) { try { Directory.Delete(folderName, true); } /*catch (IOException) * { * Thread.Sleep(0); * Directory.Delete(folderName, false); * }*/ catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } } } } } }
public override void ProcessCommand() { logger.Info("Reading Media Info for File: {0}", VideoLocalID); try { VideoLocalRepository repVids = new VideoLocalRepository(); VideoLocal vlocal = repVids.GetByID(VideoLocalID); if (vlocal == null) { logger.Error("Cound not find Video: {0}", VideoLocalID); return; } if (!File.Exists(vlocal.FullServerPath)) { logger.Error("Cound not find physical file: {0}", vlocal.FullServerPath); return; } int nshareID = -1; VideoInfoRepository repVidInfo = new VideoInfoRepository(); VideoInfo vinfo = repVidInfo.GetByHash(vlocal.Hash); ImportFolderRepository repNS = new ImportFolderRepository(); List <ImportFolder> shares = repNS.GetAll(); string fileName = vlocal.FullServerPath; string filePath = ""; DataAccessHelper.GetShareAndPath(fileName, shares, ref nshareID, ref filePath); FileInfo fi = new FileInfo(fileName); if (vinfo == null) { vinfo = new VideoInfo(); vinfo.Hash = vlocal.Hash; vinfo.Duration = 0; vinfo.FileSize = fi.Length; vinfo.DateTimeUpdated = DateTime.Now; vinfo.FileName = filePath; vinfo.AudioBitrate = ""; vinfo.AudioCodec = ""; vinfo.VideoBitrate = ""; vinfo.VideoBitDepth = ""; vinfo.VideoCodec = ""; vinfo.VideoFrameRate = ""; vinfo.VideoResolution = ""; } logger.Trace("Getting media info for: {0}", fileName); MediaInfoResult mInfo = FileHashHelper.GetMediaInfo(fileName, true); vinfo.AudioBitrate = string.IsNullOrEmpty(mInfo.AudioBitrate) ? "" : mInfo.AudioBitrate; vinfo.AudioCodec = string.IsNullOrEmpty(mInfo.AudioCodec) ? "" : mInfo.AudioCodec; vinfo.DateTimeUpdated = vlocal.DateTimeUpdated; vinfo.Duration = mInfo.Duration; vinfo.FileName = filePath; vinfo.FileSize = fi.Length; vinfo.VideoBitrate = string.IsNullOrEmpty(mInfo.VideoBitrate) ? "" : mInfo.VideoBitrate; vinfo.VideoBitDepth = string.IsNullOrEmpty(mInfo.VideoBitDepth) ? "" : mInfo.VideoBitDepth; vinfo.VideoCodec = string.IsNullOrEmpty(mInfo.VideoCodec) ? "" : mInfo.VideoCodec; vinfo.VideoFrameRate = string.IsNullOrEmpty(mInfo.VideoFrameRate) ? "" : mInfo.VideoFrameRate; vinfo.VideoResolution = string.IsNullOrEmpty(mInfo.VideoResolution) ? "" : mInfo.VideoResolution; vinfo.FullInfo = string.IsNullOrEmpty(mInfo.FullInfo) ? "" : mInfo.FullInfo; repVidInfo.Save(vinfo); } catch (Exception ex) { logger.Error("Error processing CommandRequest_ReadMediaInfo: {0} - {1}", VideoLocalID, ex.ToString()); return; } }
public static void RunImport_NewFiles() { VideoLocalRepository repVidLocals = new VideoLocalRepository(); // first build a list of files that we already know about, as we don't want to process them again List<VideoLocal> filesAll = repVidLocals.GetAll(); Dictionary<string, VideoLocal> dictFilesExisting = new Dictionary<string, VideoLocal>(); foreach (VideoLocal vl in filesAll) { try { dictFilesExisting[vl.FullServerPath] = vl; } catch (Exception ex) { string msg = string.Format("Error RunImport_NewFiles XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString()); logger.Info(msg); //throw; } } // Steps for processing a file // 1. Check if it is a video file // 2. Check if we have a VideoLocal record for that file // ......... // get a complete list of files List<string> fileList = new List<string>(); ImportFolderRepository repNetShares = new ImportFolderRepository(); foreach (ImportFolder share in repNetShares.GetAll()) { logger.Debug("ImportFolder: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation); try { Utils.GetFilesForImportFolder(share.ImportFolderLocation, ref fileList); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } // get a list fo files that we haven't processed before List<string> fileListNew = new List<string>(); foreach (string fileName in fileList) { if (!dictFilesExisting.ContainsKey(fileName)) fileListNew.Add(fileName); } // get a list of all the shares we are looking at int filesFound = 0, videosFound = 0; int i = 0; // get a list of all files in the share foreach (string fileName in fileListNew) { i++; filesFound++; logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName); if (!FileHashHelper.IsVideo(fileName)) continue; videosFound++; CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false); cr_hashfile.Save(); } logger.Debug("Found {0} files", filesFound); logger.Debug("Found {0} videos", videosFound); }
public static void RunImport_ScanFolder(int importFolderID) { // get a complete list of files List<string> fileList = new List<string>(); ImportFolderRepository repFolders = new ImportFolderRepository(); int filesFound = 0, videosFound = 0; int i = 0; try { ImportFolder fldr = repFolders.GetByID(importFolderID); if (fldr == null) return; VideoLocalRepository repVidLocals = new VideoLocalRepository(); // first build a list of files that we already know about, as we don't want to process them again List<VideoLocal> filesAll = repVidLocals.GetAll(); Dictionary<string, VideoLocal> dictFilesExisting = new Dictionary<string, VideoLocal>(); foreach (VideoLocal vl in filesAll) { try { dictFilesExisting[vl.FullServerPath] = vl; } catch (Exception ex) { string msg = string.Format("Error RunImport_ScanFolder XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString()); logger.Info(msg); } } logger.Debug("ImportFolder: {0} || {1}", fldr.ImportFolderName, fldr.ImportFolderLocation); Utils.GetFilesForImportFolder(fldr.ImportFolderLocation, ref fileList); // get a list of all files in the share foreach (string fileName in fileList) { i++; if (dictFilesExisting.ContainsKey(fileName)) { if (fldr.IsDropSource != 1) continue; else { // if this is a file in a drop source, try moving it string filePath = string.Empty; int nshareID = 0; DataAccessHelper.GetShareAndPath(fileName, repFolders.GetAll(), ref nshareID, ref filePath); List<VideoLocal> filesSearch = repVidLocals.GetByName(filePath); foreach (VideoLocal vid in filesSearch) vid.MoveFileIfRequired(); } } filesFound++; logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName); if (!FileHashHelper.IsVideo(fileName)) continue; videosFound++; CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false); cr_hashfile.Save(); } logger.Debug("Found {0} new files", filesFound); logger.Debug("Found {0} videos", videosFound); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
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); } }