private static void CreateImportFolders_Test() { logger.Debug("Creating import folders..."); ImportFolderRepository repImportFolders = new ImportFolderRepository(); ImportFolder sn = repImportFolders.GetByImportLocation(@"M:\[ Anime Test ]"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderName = "Anime"; sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderLocation = @"M:\[ Anime Test ]"; repImportFolders.Save(sn); } logger.Debug("Complete!"); }
private static void CreateImportFolders() { logger.Debug("Creating shares..."); ImportFolderRepository repNetShares = new ImportFolderRepository(); ImportFolder sn = repNetShares.GetByImportLocation(@"M:\[ Anime 2011 ]"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime 2011"; sn.ImportFolderLocation = @"M:\[ Anime 2011 ]"; repNetShares.Save(sn); } sn = repNetShares.GetByImportLocation(@"M:\[ Anime - DVD and Bluray IN PROGRESS ]"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime - DVD and Bluray IN PROGRESS"; sn.ImportFolderLocation = @"M:\[ Anime - DVD and Bluray IN PROGRESS ]"; repNetShares.Save(sn); } sn = repNetShares.GetByImportLocation(@"M:\[ Anime - DVD and Bluray COMPLETE ]"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime - DVD and Bluray COMPLETE"; sn.ImportFolderLocation = @"M:\[ Anime - DVD and Bluray COMPLETE ]"; repNetShares.Save(sn); } sn = repNetShares.GetByImportLocation(@"M:\[ Anime ]"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime"; sn.ImportFolderLocation = @"M:\[ Anime ]"; repNetShares.Save(sn); } logger.Debug("Creating shares complete!"); }
public static void StartWatchingFiles() { StopWatchingFiles(); watcherVids = new List<FileSystemWatcher>(); ImportFolderRepository repNetShares = new ImportFolderRepository(); foreach (ImportFolder share in repNetShares.GetAll()) { try { if (Directory.Exists(share.ImportFolderLocation) && share.FolderIsWatched) { logger.Info("Watching ImportFolder: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation); FileSystemWatcher fsw = new FileSystemWatcher(share.ImportFolderLocation); fsw.IncludeSubdirectories = true; fsw.Created += new FileSystemEventHandler(fsw_Created); fsw.EnableRaisingEvents = true; watcherVids.Add(fsw); } else { logger.Error("ImportFolder not found for watching: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } }
private static void ReadFiles() { // 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("Import Folder: {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++; if (fileName.Contains("Sennou")) { logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName); } if (!FileHashHelper.IsVideo(fileName)) continue; videosFound++; } logger.Debug("Found {0} files", filesFound); logger.Debug("Found {0} videos", videosFound); }
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); }
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 List<Contract_ImportFolder> GetImportFolders() { List<Contract_ImportFolder> ifolders = new List<Contract_ImportFolder>(); try { ImportFolderRepository repNS = new ImportFolderRepository(); foreach (ImportFolder ns in repNS.GetAll()) { ifolders.Add(ns.ToContract()); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return ifolders; }
void workerSetupDB_DoWork(object sender, DoWorkEventArgs e) { try { ServerState.Instance.ServerOnline = false; ServerState.Instance.CurrentSetupStatus = "Cleaning up..."; StopWatchingFiles(); AniDBDispose(); StopHost(); JMMService.CmdProcessorGeneral.Stop(); JMMService.CmdProcessorHasher.Stop(); JMMService.CmdProcessorImages.Stop(); // wait until the queue count is 0 // ie the cancel has actuall worked while (true) { if (JMMService.CmdProcessorGeneral.QueueCount == 0 && JMMService.CmdProcessorHasher.QueueCount == 0 && JMMService.CmdProcessorImages.QueueCount == 0) break; Thread.Sleep(250); } if (autoUpdateTimer != null) autoUpdateTimer.Enabled = false; if (autoUpdateTimerShort != null) autoUpdateTimerShort.Enabled = false; JMMService.CloseSessionFactory(); ServerState.Instance.CurrentSetupStatus = "Initializing..."; Thread.Sleep(1000); ServerState.Instance.CurrentSetupStatus = "Setting up database..."; logger.Info("Setting up database..."); if (!DatabaseHelper.InitDB()) { ServerState.Instance.DatabaseAvailable = false; if (string.IsNullOrEmpty(ServerSettings.DatabaseType)) ServerState.Instance.CurrentSetupStatus = "Please select and configure your database."; else ServerState.Instance.CurrentSetupStatus = "Failed to start. Please review database settings."; e.Result = false; return; } else ServerState.Instance.DatabaseAvailable = true; logger.Info("Initializing Session Factory..."); //init session factory ServerState.Instance.CurrentSetupStatus = "Initializing Session Factory..."; ISessionFactory temp = JMMService.SessionFactory; logger.Info("Initializing Hosts..."); ServerState.Instance.CurrentSetupStatus = "Initializing Hosts..."; FileServer.FileServer.RegisterFirewallAndHttpUser(int.Parse(ServerSettings.JMMServerPort),int.Parse(ServerSettings.JMMServerFilePort)); SetupAniDBProcessor(); StartImageHost(); StartBinaryHost(); StartMetroHost(); StartImageHostMetro(); StartPlexHost(); StartFileHost(); StartRESTHost(); StartStreamingHost(); // Load all stats ServerState.Instance.CurrentSetupStatus = "Initializing Stats..."; StatsCache.Instance.InitStats(); ServerState.Instance.CurrentSetupStatus = "Initializing Queue Processors..."; JMMService.CmdProcessorGeneral.Init(); JMMService.CmdProcessorHasher.Init(); JMMService.CmdProcessorImages.Init(); // timer for automatic updates autoUpdateTimer = new System.Timers.Timer(); autoUpdateTimer.AutoReset = true; autoUpdateTimer.Interval = 5 * 60 * 1000; // 5 minutes * 60 seconds autoUpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(autoUpdateTimer_Elapsed); autoUpdateTimer.Start(); // timer for automatic updates autoUpdateTimerShort = new System.Timers.Timer(); autoUpdateTimerShort.AutoReset = true; autoUpdateTimerShort.Interval = 15 * 1000; // 15 seconds autoUpdateTimerShort.Elapsed += new System.Timers.ElapsedEventHandler(autoUpdateTimerShort_Elapsed); autoUpdateTimerShort.Start(); ServerState.Instance.CurrentSetupStatus = "Initializing File Watchers..."; StartWatchingFiles(); DownloadAllImages(); ImportFolderRepository repFolders = new ImportFolderRepository(); List<ImportFolder> folders = repFolders.GetAll(); if (ServerSettings.ScanDropFoldersOnStart) ScanDropFolders(); if (ServerSettings.RunImportOnStart && folders.Count > 0) RunImport(); ServerState.Instance.ServerOnline = true; e.Result = true; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); ServerState.Instance.CurrentSetupStatus = ex.Message; e.Result = false; } }
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); } } } } } } }
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 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); } } 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 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.UpdateStats(true, true, true); StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID); } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } }
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); }
private static void CreateImportFolders2() { logger.Debug("Creating shares..."); ImportFolderRepository repNetShares = new ImportFolderRepository(); ImportFolder sn = repNetShares.GetByImportLocation(@"F:\Anime1"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime1"; sn.ImportFolderLocation = @"F:\Anime1"; repNetShares.Save(sn); } sn = repNetShares.GetByImportLocation(@"H:\Anime2"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime2"; sn.ImportFolderLocation = @"H:\Anime2"; repNetShares.Save(sn); } sn = repNetShares.GetByImportLocation(@"G:\Anime3"); if (sn == null) { sn = new ImportFolder(); sn.ImportFolderType = (int)ImportFolderType.HDD; sn.ImportFolderName = "Anime3"; sn.ImportFolderLocation = @"G:\Anime3"; repNetShares.Save(sn); } logger.Debug("Creating shares complete!"); }
public Contract_VideoLocalRenamed RenameFile(int videoLocalID, string renameRules) { Contract_VideoLocalRenamed ret = new Contract_VideoLocalRenamed(); ret.VideoLocalID = videoLocalID; ret.Success = true; try { VideoLocalRepository repVids = new VideoLocalRepository(); VideoLocal vid = repVids.GetByID(videoLocalID); if (vid == null) { ret.VideoLocal = null; ret.NewFileName = string.Format("ERROR: Could not find file record"); ret.Success = false; } else { ret.VideoLocal = null; ret.NewFileName = RenameFileHelper.GetNewFileName(vid, renameRules); if (!string.IsNullOrEmpty(ret.NewFileName)) { // check if the file exists string fullFileName = vid.FullServerPath; if (!File.Exists(fullFileName)) { ret.NewFileName = "Error could not find the original file"; ret.Success = false; return ret; } // actually rename the file string path = Path.GetDirectoryName(fullFileName); string newFullName = Path.Combine(path, ret.NewFileName); 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)); ret.NewFileName = newFullName; } else { File.Move(fullFileName, newFullName); logger.Info(string.Format("Renaming file SUCCESS From ({0}) to ({1})", fullFileName, newFullName)); ret.NewFileName = newFullName; string newPartialPath = ""; int folderID = vid.ImportFolderID; ImportFolderRepository repFolders = new ImportFolderRepository(); DataAccessHelper.GetShareAndPath(newFullName, repFolders.GetAll(), ref folderID, ref newPartialPath); vid.FilePath = newPartialPath; repVids.Save(vid); } } catch (Exception ex) { logger.Info(string.Format("Renaming file FAIL From ({0}) to ({1}) - {2}", fullFileName, newFullName, ex.Message)); logger.ErrorException(ex.ToString(), ex); ret.Success = false; ret.NewFileName = ex.Message; } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); ret.VideoLocal = null; ret.NewFileName = string.Format("ERROR: {0}", ex.Message); ret.Success = false; } return ret; }
void workerSetupDB_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { bool setupComplete = bool.Parse(e.Result.ToString()); if (setupComplete) { ServerInfo.Instance.RefreshImportFolders(); ServerState.Instance.CurrentSetupStatus = "Complete!"; ServerState.Instance.ServerOnline = true; tabControl1.SelectedIndex = 0; } else { ServerState.Instance.ServerOnline = false; if (string.IsNullOrEmpty(ServerSettings.DatabaseType)) { ServerSettings.DatabaseType = "SQLite"; ShowDatabaseSetup(); } } btnSaveDatabaseSettings.IsEnabled = true; cboDatabaseType.IsEnabled = true; btnRefreshMSSQLServerList.IsEnabled = true; if (setupComplete) { if (string.IsNullOrEmpty(ServerSettings.AniDB_Username) || string.IsNullOrEmpty(ServerSettings.AniDB_Password)) { InitialSetupForm frm = new InitialSetupForm(); frm.Owner = this; frm.ShowDialog(); } ImportFolderRepository repFolders = new ImportFolderRepository(); List<ImportFolder> folders = repFolders.GetAll(); if (folders.Count == 0) { tabControl1.SelectedIndex = 1; } } }
public Contract_ImportFolder_SaveResponse SaveImportFolder(Contract_ImportFolder contract) { Contract_ImportFolder_SaveResponse response = new Contract_ImportFolder_SaveResponse(); response.ErrorMessage = ""; response.ImportFolder = null; try { ImportFolderRepository repNS = new ImportFolderRepository(); ImportFolder ns = null; if (contract.ImportFolderID.HasValue) { // update ns = repNS.GetByID(contract.ImportFolderID.Value); if (ns == null) { response.ErrorMessage = "Could not find Import Folder ID: " + contract.ImportFolderID.Value.ToString(); return response; } } else { // create ns = new ImportFolder(); } if (string.IsNullOrEmpty(contract.ImportFolderName)) { response.ErrorMessage = "Must specify an Import Folder name"; return response; } if (string.IsNullOrEmpty(contract.ImportFolderLocation)) { response.ErrorMessage = "Must specify an Import Folder location"; return response; } if (!Directory.Exists(contract.ImportFolderLocation)) { response.ErrorMessage = "Cannot find Import Folder location"; return response; } if (!contract.ImportFolderID.HasValue) { ImportFolder nsTemp = repNS.GetByImportLocation(contract.ImportFolderLocation); if (nsTemp != null) { response.ErrorMessage = "An entry already exists for the specified Import Folder location"; return response; } } if (contract.IsDropDestination == 1 && contract.IsDropSource == 1) { response.ErrorMessage = "A folder cannot be a drop source and a drop destination at the same time"; return response; } // check to make sure we don't have multiple drop folders List<ImportFolder> allFolders = repNS.GetAll(); if (contract.IsDropDestination == 1) { foreach (ImportFolder imf in allFolders) { if (imf.IsDropDestination == 1 && (!contract.ImportFolderID.HasValue || (contract.ImportFolderID.Value != imf.ImportFolderID))) { imf.IsDropDestination = 0; repNS.Save(imf); } } } ns.ImportFolderName = contract.ImportFolderName; ns.ImportFolderLocation = contract.ImportFolderLocation; ns.IsDropDestination = contract.IsDropDestination; ns.IsDropSource = contract.IsDropSource; ns.IsWatched = contract.IsWatched; repNS.Save(ns); response.ImportFolder = ns.ToContract(); MainWindow.StopWatchingFiles(); MainWindow.StartWatchingFiles(); return response; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); response.ErrorMessage = ex.Message; return response; } }
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_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)) continue; 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); } }