public List <VideoInfosScanSource> ScanSource(List <string> sources, DoWorkEventArgs doWorkEvent) { if (sources.Count() == 0) { throw new ArgumentException("sources cannot be empty", "sources"); } ParseVideo parseVideo = new ParseVideo(); // Abort the operation if the user has canceled. // Note that a call to CancelAsync may have set // CancellationPending to true just after the // last invocation of this method exits, so this // code will not have the opportunity to set the // DoWorkEventArgs.Cancel flag to true. This means // that RunWorkerCompletedEventArgs.Cancelled will // not be set to true in your RunWorkerCompleted // event handler. This is a race condition. if (backgroundWorker.CancellationPending) { doWorkEvent.Cancel = true; return(null); } // Data structure to hold names of subfolders to be examined for files. Stack <DirInfo> dirNodes = new Stack <DirInfo>(1000); List <VideoInfosScanSource> videoInfosScanSources = new List <VideoInfosScanSource>(); percentComplete = 0; backgroundWorker.ReportProgress(percentComplete, "Processing sources.."); // get the root dirs from each source int nbrSources = sources.Count(); int processingSource = 0; foreach (string source in sources) { percentComplete = (int)Math.Floor((double)processingSource / (double)nbrSources * 100); backgroundWorker.ReportProgress(percentComplete, "Scanning source " + source + ".."); List <VideoInfo> videoInfos = new List <VideoInfo>(10000); string sourceAlias = Config.SourceDirectory2Alias(source); IEnumerable <string> directories = MyFile.EnumerateDirectories(source, "*", SearchOption.AllDirectories); int nbrDirectories = directories.Count(); int processingDirectory = 0; foreach (string directory in directories) { MyLog.Add("Scanning: " + directory); VideoInfo videoInfo = parseVideo.ReadDirectory(directory); if (videoInfo == null || videoInfo.videoItem == null || videoInfo.videoItem.title == null || videoInfo.files == null || videoInfo.files.video == null) { processingDirectory++; continue; } videoInfo.sourceAlias = sourceAlias; videoInfo.videoDirectory = directory; // see if any existing item or new videoInfo.index = videoInfos.Count; string hash = ListVideoInfo.CreateHash(videoInfo); videoInfo.hash = hash; VideoInfo foundVideoInfo = ListVideoInfo.FindVideoInfo("hash", hash); bool bNew = false; if (foundVideoInfo == null) { bNew = true; } if (bNew || foundVideoInfo.added == null || foundVideoInfo.added == DateTime.MinValue) { videoInfo.added = DateTime.UtcNow; } if (bNew || foundVideoInfo.updated == null || foundVideoInfo.updated == DateTime.MinValue) { videoInfo.updated = videoInfo.added; } if (!bNew) { // TODO ? needed? found item in list, merge list item with scanned item, scanned item wins videoInfo = ListVideoInfo.MergeVideoInfos(foundVideoInfo, videoInfo); } videoInfos.Add(videoInfo); processingDirectory++; if (processingDirectory % 1 == 0) { percentComplete = (int)Math.Floor((double)processingDirectory / (double)nbrDirectories * 100); string progressMessage = "Scanned " + processingDirectory + " of " + nbrDirectories + " directories\n" + directory.Split(Path.DirectorySeparatorChar).Last() + ".."; // progressMessage = directory.Split(Path.DirectorySeparatorChar).Last() + ".."; backgroundWorker.ReportProgress(percentComplete, progressMessage); // Thread.Sleep(1000); // dev if (backgroundWorker.CancellationPending) { doWorkEvent.Cancel = true; return(null); } } } // foreach directory VideoInfosScanSource videoInfosScanSource = new VideoInfosScanSource(); videoInfosScanSource.videoInfos = videoInfos; videoInfosScanSource.sourceAlias = sourceAlias; videoInfosScanSources.Add(videoInfosScanSource); processingSource++; } // end foreach source // add items to main list .. but not here .. in completed event // ListVideoInfo.Clear(); // ListVideoInfo.AddItems(videoInfos); percentComplete = 100; backgroundWorker.ReportProgress(percentComplete, "Completed scan"); // meh, so completed msg shows Thread.Sleep(500); return(videoInfosScanSources); }
/// <summary> /// update the MB .xml file /// </summary> /// <param name="videoItemFile"></param> /// <param name="videoItem"></param> /// <returns></returns> public bool UpdateMB(VideoInfo videoInfo) { string videoFullName = null; string fileContents = null; if (videoInfo.files == null || videoInfo.files.mb == null) { if (Config.settings.createMB) { videoFullName = videoInfo.videoDirectory + @"\movie.xml"; fileContents = GetDefaultMBxml(); } else { return(false); } } else if (!Config.settings.updateMB) { return(false); } else { videoFullName = videoInfo.GetFullName(videoInfo.files.mb); fileContents = MyFile.ReadAllText(videoFullName); } if (fileContents == null || videoFullName == null) { return(false); } VideoItem videoItem = videoInfo.videoItem; XmlDocument doc = MyXMLDoc.LoadXml(fileContents); if (doc == null) { return(false); } MyXMLDoc.SetSingleNodeString(doc, "/Title/LocalTitle", videoItem.title); MyXMLDoc.SetSingleNodeString(doc, "/Title/Overview", videoItem.plot); MyXMLDoc.SetSingleNodeString(doc, "/Title/set", videoItem.movieset); MyXMLDoc.SetSingleNodeString(doc, "/Title/tagline", videoItem.tagline); MyXMLDoc.SetSingleNodeString(doc, "/Title/IMDB", videoItem.imdbId); MyXMLDoc.SetSingleNodeString(doc, "/Title/TMDbId", videoItem.tmdbId); MyXMLDoc.SetSingleNodeString(doc, "/Title/ContentRating", videoItem.mpaa); MyXMLDoc.SetSingleNodeDecimal(doc, "/Title/Rating", videoItem.imdbRating); MyXMLDoc.SetSingleNodeInt(doc, "/Title/ProductionYear", videoItem.year); MyXMLDoc.SetSingleNodeInt(doc, "/Title/RunningTime", videoItem.runtime); bool ret = MyXMLDoc.SaveXML(doc, videoFullName); if (ret) { MyLog.Add("wrote " + videoFullName); } else { MyLog.Add("error writing to " + videoFullName); } return(ret); }
/// <summary> /// update the XBMC .nfo file /// </summary> /// <param name="videoItemFile"></param> /// <param name="videoItem"></param> /// <returns></returns> public bool UpdateXBMC(VideoInfo videoInfo) { // MyLog.Add("UpdateXBMC"); string videoFullName = null; string fileContents = null; if (videoInfo.files == null || videoInfo.files.xbmc == null) { if (Config.settings.createXBMC) { videoFullName = videoInfo.videoDirectory + @"\movie.nfo"; fileContents = GetDefaultXBMCxml(); } else { return(false); } } else if (!Config.settings.updateXBMC) { return(false); } else { videoFullName = videoInfo.GetFullName(videoInfo.files.xbmc); fileContents = MyFile.ReadAllText(videoFullName); } if (fileContents == null || videoFullName == null) { return(false); } VideoItem videoItem = videoInfo.videoItem; XmlDocument doc = MyXMLDoc.LoadXml(fileContents); if (doc == null) { return(false); } MyXMLDoc.SetSingleNodeString(doc, "/movie/title", videoItem.title); MyXMLDoc.SetSingleNodeString(doc, "/movie/plot", videoItem.plot); MyXMLDoc.SetSingleNodeString(doc, "/movie/set", videoItem.movieset); MyXMLDoc.SetSingleNodeString(doc, "/movie/tagline", videoItem.tagline); MyXMLDoc.SetSingleNodeString(doc, "/movie/id", videoItem.imdbId); MyXMLDoc.SetSingleNodeString(doc, "/movie/tmdbId", videoItem.tmdbId); MyXMLDoc.SetSingleNodeString(doc, "/movie/mpaa", videoItem.mpaa); MyXMLDoc.SetSingleNodeDecimal(doc, "/movie/rating", videoItem.imdbRating); MyXMLDoc.SetSingleNodeInt(doc, "/movie/year", videoItem.year); MyXMLDoc.SetSingleNodeInt(doc, "/movie/runtime", videoItem.runtime); MyXMLDoc.SetSingleNodeInt(doc, "/movie/playcount", videoItem.playCount); int watched = VideoFileEnums.watched.GetValueByKey(videoItem.watched); // either watched or not if (watched != 0 && watched != 1) { watched = 0; } MyXMLDoc.SetSingleNodeInt(doc, "/movie/watched", watched); bool ret = MyXMLDoc.SaveXML(doc, videoFullName); if (ret) { MyLog.Add("wrote " + videoFullName); } else { MyLog.Add("error writing to " + videoFullName); } return(ret); }
public bool SyncUpVideoSource(FileInfo sourceFileInfo) { // clean up old uploads IEnumerable <string> files = MyFile.EnumerateFiles(@"sync", "*.gz"); foreach (string file in files) { MyFile.DeleteFile(file); } // compress file, video source string compressedFile = @"sync\" + MyFile.SafeFileName(sourceFileInfo.Name); if (!MyFile.Compress(sourceFileInfo.FullName, compressedFile)) { return(false); } // rename file so has 'rand' key/iv Random random = new Random(); int rand = random.Next(0, MyEncrypt.sharedKeys.Length - 1); string uploadFile = compressedFile.Replace("." + Config.settings.exportExt, "-" + rand + "." + Config.settings.exportExt); File.Move(compressedFile + ".gz", uploadFile + ".gz"); string key = MyEncrypt.sharedKeys[rand]; string iv = MyEncrypt.GenerateIV(); string delimiter = "#"; // now encrypt compressed file contents string fileContents = MyFile.ReadAllBinaryToString(uploadFile + ".gz"); string contentsHeader = "{"; contentsHeader += "\"apiKey\":\"" + this.apiKey + "\", "; contentsHeader += "\"iv\":\"" + iv + "\", "; contentsHeader += "\"sync\":" + MySerialize.ToJSON(Sync.syncSettings); contentsHeader += "}"; contentsHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(contentsHeader)); fileContents = MyEncrypt.EncryptRJ256(key, iv, fileContents); if (fileContents == null) { return(false); } contentsHeader = MyEncrypt.EncryptRJ256(key, iv, contentsHeader); string contentsToEncode = contentsHeader + delimiter + fileContents; // write base64 encoded file File.WriteAllText(uploadFile + ".enc", contentsToEncode); // log it FileInfo encodedFileInfo = MyFile.FileInfo(uploadFile + ".enc"); if (encodedFileInfo == null) { return(false); } MyLog.Add(String.Format("Encrypted {0} to {1}", encodedFileInfo.Name, MyFile.FormatSize(encodedFileInfo.Length))); // test decrypt fileContents = MyFile.ReadAllText(uploadFile + ".enc"); string[] fileParts = fileContents.Split(new string[] { delimiter }, StringSplitOptions.None); fileContents = MyEncrypt.DecryptRJ256(key, iv, fileParts[1]); MyFile.DeleteFile(uploadFile + ".gz"); MyFile.WriteAllBinaryFromString(uploadFile + ".gz", fileContents); // post encoded file to website string url = apiURL; List <KeyValuePair <string, string> > headers = new List <KeyValuePair <string, string> > { }; headers.Add(new KeyValuePair <string, string>("api-key", apiKey)); headers.Add(new KeyValuePair <string, string>("access-token", iv)); Upload(url, uploadFile + ".enc", headers); return(true); }
public void SetForm(VideoInfo videoInfo) { this.selectedVideoInfo = videoInfo; VideoItem videoItem = videoInfo.videoItem; try { // set search title MyFormField.SetTextBoxText(textBoxTitle, videoItem.title); // set movie set MyFormField.SetTextBoxText(textBoxMovieSet, videoItem.movieset); // set plot MyFormField.SetRichTextBoxText(richTextBoxPlot, videoItem.plot); // set runtime MyFormField.SetTextBoxText(textBoxRunTime, videoItem.runtime.ToString()); // set tagline // MyFormField.SetTextBoxText(textBoxTagLine, videoItem.tagline); // not yet // set notes MyFormField.SetRichTextBoxText(richTextBoxNotes, videoItem.notes); if (videoItem.encoding != null) { // set width if (videoItem.encoding.width > 0) { MyFormField.SetTextBoxText(textBoxWidth, videoItem.encoding.width.ToString()); } else { MyFormField.SetTextBoxText(textBoxWidth, ""); } // set height if (videoItem.encoding.height > 0) { MyFormField.SetTextBoxText(textBoxHeight, videoItem.encoding.height.ToString()); } else { MyFormField.SetTextBoxText(textBoxHeight, ""); } // set bitrate if (videoItem.encoding.bitrate > 0) { MyFormField.SetTextBoxText(textBoxBitrate, videoItem.encoding.bitrate.ToString()); string bitrateFormatted = MyFile.FormatSize(videoItem.encoding.bitrate, 2); bitrateFormatted = bitrateFormatted.Replace(" ", "\n"); MyFormField.SetLabelText(labelForBitrateFormatted, bitrateFormatted); } else { MyFormField.SetTextBoxText(textBoxBitrate, ""); MyFormField.SetLabelText(labelForBitrateFormatted, ""); } // set codec if (!String.IsNullOrEmpty(videoItem.encoding.codec)) { MyFormField.SetComboBoxValue(comboBoxCodec, videoItem.encoding.codec); } else { MyFormField.SetComboBoxValue(comboBoxCodec, ""); } } // set tag for (int index = dataGridViewTags.Rows.Count - 1; index >= 0; index--) { if (dataGridViewTags.Rows[index].IsNewRow) { continue; } dataGridViewTags.Rows.RemoveAt(index); } if (videoItem.tags != null) { IComparer <VideoItemTag <string> > sortVideoItemTag = new SortVideoItemTag(); videoItem.tags.Sort(sortVideoItemTag); foreach (VideoItemTag <string> tag in videoItem.tags) { dataGridViewTags.Rows.Add(new object[] { tag.name }); } // prevent add row from being auto selected if (dataGridViewTags.CurrentCell != null) { dataGridViewTags.CurrentCell.Selected = false; } } // set genre for (int index = dataGridViewGenres.Rows.Count - 1; index >= 0; index--) { if (dataGridViewGenres.Rows[index].IsNewRow) { continue; } dataGridViewGenres.Rows.RemoveAt(index); } if (videoItem.genres != null) { IComparer <VideoItemGenre <string> > sortVideoItemGenre = new SortVideoItemGenre(); videoItem.genres.Sort(sortVideoItemGenre); foreach (VideoItemGenre <string> genre in videoItem.genres) { dataGridViewGenres.Rows.Add(new object[] { genre.name }); } // prevent add row from being auto selected if (dataGridViewGenres.CurrentCell != null) { dataGridViewGenres.CurrentCell.Selected = false; } } // set bing link SetLinkLabelFromTitle(linkLabelBing, "https://www.bing.com/search?q="); // set google link SetLinkLabelFromTitle(linkLabelGoogle, "https://www.google.com/search?q="); // set google link SetLinkLabelFromTitle(linkLabelRT, "https://www.rottentomatoes.com/search/?search="); // set upc MyFormField.SetTextBoxText(textBoxUPC, videoItem.upc); // set tmdbId link MyFormField.SetTextBoxText(textBoxTMDB, videoItem.tmdbId); MyFormField.SetLinkLabel(linkLabelTMDB, "http://www.themoviedb.org/movie/", videoItem.tmdbId); // set imdbId link MyFormField.SetTextBoxText(textBoxIMDB, videoItem.imdbId); MyFormField.SetLinkLabel(linkLabelIMDB, "http://www.imdb.com/title/", videoItem.imdbId); // set year MyFormField.SetComboBoxValue(comboBoxYear, videoItem.year); // set imdbRating MyFormField.SetComboBoxValue(comboBoxIMDBRating, Convert.ToInt32(videoItem.imdbRating)); // set mpaa MyFormField.SetComboBoxValue(comboBoxMPAA, videoItem.mpaa); // set playCount MyFormField.SetComboBoxValue(comboBoxPlayCount, videoItem.playCount); // set rating MyFormField.SetComboBoxValue(comboBoxRating, videoItem.rating); // set source MyFormField.SetComboBoxValue(comboBoxSource, videoItem.source); // set version MyFormField.SetComboBoxValue(comboBoxVersion, videoItem.version); // set lastPlayed MyFormField.SetLabelText(labelLastPlayed, videoItem.lastPlayed); // set labelUpdated MyFormField.SetLabelText(labelUpdated, videoInfo.updated); // set watched MyFormField.SetCheckBoxChecked(checkBoxWatched, ((videoItem.watched != "NO") ? true : false)); // set actor/director for (int index = dataGridViewActors.Rows.Count - 1; index >= 0; index--) { if (dataGridViewActors.Rows[index].IsNewRow) { continue; } dataGridViewActors.Rows.RemoveAt(index); } if (videoItem.directors != null) { IComparer <VideoItemDirector <string> > sortVideoItemDirector = new SortVideoItemDirector(); videoItem.directors.Sort(sortVideoItemDirector); foreach (VideoItemDirector <string> director in videoItem.directors) { dataGridViewActors.Rows.Add(new object[] { director.name, "Director" }); } } if (videoItem.actors != null) { IComparer <VideoItemActor <string, string> > sortVideoItemActor = new SortVideoItemActor(); videoItem.actors.Sort(sortVideoItemActor); foreach (VideoItemActor <string, string> actor in videoItem.actors) { dataGridViewActors.Rows.Add(new object[] { actor.name, actor.role }); } } // prevent add row from being auto selected if (dataGridViewActors.CurrentCell != null) { dataGridViewActors.CurrentCell.Selected = false; } } catch (Exception e) { MyLog.Add(e.ToString()); } this.Parent.Focus(); }
private void FormMain_FormClosed(object sender, FormClosedEventArgs e) { MyLog.Add("========================================== Closed application"); }
public bool SetList() { listViewSyncUp.SuspendLayout(); listViewSyncUp.Items.Clear(); // string syncFile; string fileSize; FileInfo fileInfo; ListViewItem listViewItem; /* * // get sync info * syncFile = @"sync\sync." + Config.settings.exportExt; * fileInfo = MyFile.FileInfo(syncFile); * if (fileInfo == null) * { * Sync.Save(); * fileInfo = MyFile.FileInfo(syncFile); * if (fileInfo == null) * { * MessageBox.Show("Unable to create [" + syncFile + "]"); * MyLog.Add("Unable to create [" + syncFile + "]"); * return false; * } * } * listViewItem = new ListViewItem("Sync"); * listViewItem.SubItems.Add("-"); * fileSize = Convert.ToString(MyFile.FormatSize(fileInfo.Length)); * listViewItem.SubItems.Add(fileSize); * listViewItem.Tag = fileInfo; * * listViewSyncUp.Items.Add(listViewItem); */ // get all sources IEnumerable <string> files = MyFile.EnumerateFiles("data", "videos_*." + Config.settings.exportExt); Regex regexIgnoreBackups = new Regex(@"\.[0-9]\." + Config.settings.exportExt); foreach (string file in files) { if (regexIgnoreBackups.IsMatch(file)) { continue; } fileInfo = MyFile.FileInfo(file); if (fileInfo == null) { continue; } string source = file.Replace(@"data\videos_", "").Replace("." + Config.settings.exportExt, ""); int qty = CalcStatsForSource(source); if (qty == 0) { MyLog.Add("Source [" + source + "] seems to have 0 videos, skipping"); continue; } listViewItem = new ListViewItem(source); listViewItem.SubItems.Add(qty.ToString()); fileSize = Convert.ToString(MyFile.FormatSize(fileInfo.Length)); listViewItem.SubItems.Add(fileSize); listViewItem.Tag = fileInfo; listViewSyncUp.Items.Add(listViewItem); } ResizeColumns(); listViewSyncUp.ResumeLayout(); return(true); }
protected void BackgroundWorkerRunFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { VideoItemFileInfo resultsVideoItemFileInfo = null; // First, handle the case where an exception was thrown. if (e.Error != null) { MyLog.Add(e.Error.ToString()); subFormProgress.Text(e.Error.Message); } else if (e.Cancelled) { // Next, handle the case where the user canceled the operation. // Note that due to a race condition in the DoWork event handler, the Cancelled // flag may not have been set, even though CancelAsync was called. subFormProgress.Text("Canceled"); } else { // Finally, handle the case where the operation succeeded. resultsVideoItemFileInfo = (VideoItemFileInfo)e.Result; if (resultsVideoItemFileInfo != null) { MyLog.Add("Played: " + resultsVideoItemFileInfo.videoItemFile.Name + " for " + resultsVideoItemFileInfo.elapsed + "s"); } else { MyLog.Add("Played: no results: " + e.ToString()); } long elapsed = resultsVideoItemFileInfo.elapsed; // kinda simple check to make sure updating video that was played if (subFormVideoForm.selectedVideoInfo.files != null && subFormVideoForm.selectedVideoInfo.files.video != null && resultsVideoItemFileInfo.videoItemFile != null && subFormVideoForm.selectedVideoInfo.files.video.Name == resultsVideoItemFileInfo.videoItemFile.Name) { subFormProgress.Text("Done playing.."); // MyLog.Add("elapsed:"+elapsed+" watchedAfter:" + (Config.settings.watchedAfter)); // if played for more than X minutes, assumed "watched" if (Config.settings.markWatched && elapsed > Config.settings.watchedAfter) { subFormProgress.Value(90); subFormProgress.Text("Updating watched.."); subFormVideoForm.SetWatched(); subFormVideoForm.SaveForm(); } subFormProgress.Value(0); subFormProgress.Text("Ready"); } subFormProgress.Value(0); subFormProgress.Text("Ready"); } // bubble the event up EventHandler <VideoItemFileInfo> handler = this.playFile_Completed; if (handler != null) { MessageBox.Show("bubble"); handler(this, resultsVideoItemFileInfo); } }
/// <summary> /// background process getting VideoInfos completed /// used for ScanSource and FilterSource /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void VideoInfos_RunWorkerCompleted(string action, string message, object sender, RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { MyLog.Add(e.Error.ToString()); subFormProgress.Text(e.Error.Message); } else if (e.Cancelled) { // Next, handle the case where the user canceled the operation. // Note that due to a race condition in the DoWork event handler, the Cancelled // flag may not have been set, even though CancelAsync was called. subFormProgress.Text("Canceled"); } else { // Finally, handle the case where the operation succeeded. if (action == "scan") { List <VideoInfosScanSource> videoInfosScanSources = (List <VideoInfosScanSource>)e.Result; if (videoInfosScanSources == null) { MyLog.Add(message + " Null VideoItems"); MyLog.AddElapsed(stopwatch.Elapsed); LoadVideos_Completed(sender, e); return; } MyLog.Add(message); MyLog.AddElapsed(stopwatch.Elapsed); subFormProgress.Text("Applying.."); subFormProgress.Value(0); int nbrAppliedSources = 0; int nbrSourcesToApply = videoInfosScanSources.Count(); foreach (VideoInfosScanSource videoInfosScanSource in videoInfosScanSources) { MyLog.Add("Applying " + videoInfosScanSource.sourceAlias + " with " + videoInfosScanSource.videoInfos.Count().ToString() + " VideoItems"); int progress = (int)Math.Floor((decimal)(nbrSourcesToApply - nbrAppliedSources) / nbrSourcesToApply * 100); subFormProgress.Text("Applying " + videoInfosScanSource.sourceAlias + ".."); subFormProgress.Value(progress); // sources scanned less than settings, // so remove scanned sources from existing list // and replace with scanned list List <VideoInfo> currentVideoInfos = ListVideoInfo.GetList(); if (currentVideoInfos == null) { ListVideoInfo.SetList(videoInfosScanSource.videoInfos); } else { currentVideoInfos.RemoveAll(s => s.sourceAlias == videoInfosScanSource.sourceAlias); currentVideoInfos.AddRange(videoInfosScanSource.videoInfos); ListVideoInfo.SetList(currentVideoInfos); } // videoInfos = videoInfos.Union(currentVideoInfos).ToList(); nbrAppliedSources++; } } else // filter { List <VideoInfo> videoInfos = (List <VideoInfo>)e.Result; if (videoInfos == null) { MyLog.Add(message + " Null VideoItems"); MyLog.AddElapsed(stopwatch.Elapsed); LoadVideos_Completed(sender, e); return; } MyLog.Add(message + " " + videoInfos.Count().ToString() + " VideoItems"); MyLog.AddElapsed(stopwatch.Elapsed); subFormProgress.Text("Applying.."); subFormProgress.Value(0); ListVideoInfo.SetList(videoInfos); } MyLog.Add("Setting List"); subFormProgress.Value(0); subFormProgress.Text("Setting List.."); subFormListView.SetListViewInfos(ListVideoInfo.GetList()); Application.DoEvents(); // meh, not needed but allow ui redraw if (Config.settings.gallery.enable) { MyLog.Add("Building Gallery"); subFormProgress.Text("Building Gallery.."); subFormProgress.Value(0); stopwatchBuildGalleryImages = Stopwatch.StartNew(); // stopped when background worker completed // build to either create thumbnails or get existing thumbnails // will call LoadVideos_Completed() via RunCalcStats() when done buildGalleryImages.Build(ListVideoInfo.GetList()); } else { RunCalcStats(sender, e); } } }
public bool SaveFilter(string filterName) { if (filterName.Length == 0) { return(false); } string dataFile; if (filterName == "<_reset_>") { MessageBox.Show("Cannot Save filter"); subFormFilterForm.ResetForm(); return(false); } else if (filterName == "<filter when closed>") { dataFile = MyFile.EnsureDataFile("Filter", Config.settings.exportExt, "filters", "filter when closed"); if (dataFile == null) { return(false); } } else if (filterName == "<last saved filter>") { MessageBox.Show("Cannot Save filter.\nThis Filter will be automaticlly be saved when you Save another Filter."); return(false); } else { filterName = MyFile.SafeFileName(filterName); dataFile = MyFile.EnsureDataFile("Filter", Config.settings.exportExt, "filters", filterName); if (dataFile == null) { return(false); } allow_comboBoxPreset_SelectedIndexChanged = false; comboBoxFilters.Text = filterName; allow_comboBoxPreset_SelectedIndexChanged = true; } FilterInfo filterInfo = subFormFilterForm.GetFilterForm(); MyLog.RotateFiles(dataFile); filterInfo.about = Config.GetConfigSettingsAbout(); filterInfo.name = filterName; if (filterInfo.description == null) { filterInfo.description = ""; } MySerialize.ToFile(Config.settings.exportFormat, dataFile, filterInfo); MyLog.Add("Saved Filter Preset " + dataFile.Replace(MyFile.exeDirectory, "")); // make a copy of last saved filter if (filterName != "<last saved filter>" && filterName != "<filter when closed>") { dataFile = MyFile.EnsureDataFile("Filter", Config.settings.exportExt, "filters", "last saved filter"); if (dataFile == null) { return(false); } MyLog.RotateFiles(dataFile); MySerialize.ToFile(Config.settings.exportFormat, dataFile, filterInfo); MyLog.Add("Saved Filter Preset " + dataFile.Replace(MyFile.exeDirectory, "")); } return(true); }
public static GalleryImageThumbnailInfo GetCachedThumbnail(VideoInfo videoInfo) { GalleryImageThumbnailInfo galleryImageThumbnailInfo = new GalleryImageThumbnailInfo(); galleryImageThumbnailInfo.fromCache = false; galleryImageThumbnailInfo.createdCache = false; galleryImageThumbnailInfo.thumbnail = null; Image thumbnail = null; string cachedThumbnailFullName = MyFile.EnsureDataFile("poster_" + videoInfo.hash, "jpg", @"cache\gallery"); if (Config.settings.gallery.cachePosterThumbnails && File.Exists(cachedThumbnailFullName)) { // use file stream so files not locked FileStream fileStream = new FileStream(cachedThumbnailFullName, FileMode.Open, FileAccess.Read); thumbnail = Image.FromStream(fileStream); fileStream.Close(); // thumbnail = Image.FromFile(cachedThumbnailFile); // locks file galleryImageThumbnailInfo.fromCache = true; } else if (videoInfo.files.poster == null) { thumbnail = null; } else { VideoItemFile videoItemFile = videoInfo.files.poster; string posterFullName = videoInfo.GetFullName(videoItemFile); // skip images smaller than y or larger than x if (videoItemFile.Length < 100) { MyLog.Add("Get Thumbnail: Skipping " + posterFullName + " " + MyFile.FormatSize(videoItemFile.Length)); thumbnail = null; } if (videoItemFile.Length > 5 * 1048576) { MyLog.Add("Get Thumbnail: Skipping " + posterFullName + " " + MyFile.FormatSize(videoItemFile.Length)); thumbnail = null; } try { if (!File.Exists(posterFullName)) { thumbnail = null; } else { // size of thumbails .. TODO make a config setting thumbnail = MyImage.GetThumbnail(posterFullName, 165, 250, Color.Black); if (Config.settings.gallery.cachePosterThumbnails && thumbnail != null) { // clone image so files not locked if (MyImage.SaveJpgImage((Image)thumbnail.Clone(), cachedThumbnailFullName)) { galleryImageThumbnailInfo.createdCache = true; } } } } catch (OutOfMemoryException) { // Image.FromFile will throw this if file is invalid/corrupted; Don't ask me why MyLog.Add("Invalid Image; Unable to read " + posterFullName + " " + MyFile.FormatSize(videoItemFile.Length)); thumbnail = null; } catch (Exception ei) { MyLog.Add(ei.ToString()); thumbnail = null; } } galleryImageThumbnailInfo.thumbnail = thumbnail; return(galleryImageThumbnailInfo); }
/// <summary> /// filter video items /// </summary> /// <param name="videoItem"></param> /// <param name="filterInfo"></param> /// <returns>true, remove item; false, keep item</returns> private bool VideoInfoFilter(VideoInfo videoInfo, FilterInfo filterInfo) { if (videoInfo == null || videoInfo.videoItem == null) { return(true); } VideoItem videoItem = videoInfo.videoItem; bool logFiltered = false; // for debug; log i/o slows down filter string message = ""; if (filterInfo.filterType == 1) { // filter by combo boxes if (VideoItemFilterContainsString(videoItem.title, filterInfo.title)) { return(true); } if (VideoItemFilterBetweenInt(videoItem.year, filterInfo.yearFrom, filterInfo.yearTo)) { return(true); } if (VideoItemFilterBetweenInt(videoItem.playCount, filterInfo.playCountFrom, filterInfo.playCountTo)) { return(true); } if (VideoItemFilterWatched(videoItem.watched, filterInfo.watched)) { return(true); } if (VideoItemFilterEqualString(videoItem.source, filterInfo.source)) { return(true); } if (VideoItemFilterEqualString(videoItem.mpaa, filterInfo.mpaa)) { return(true); } // MyLog.Add("title"+videoItem.searchTitle+ " vtag:" + videoItem.tag + " ftag:"+ filterInfo.tag); if (videoItem.tags != null && VideoItemFilterContainsString(String.Join(",", videoItem.tags), filterInfo.tag, true)) { return(true); } } else if (filterInfo.filterType == 0) { // filtler by tag cloud if (logFiltered) { message = videoItem.title; } if (VideoItemFilterContainsString(videoItem.title, filterInfo.title)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " title:" + videoItem.title + " filter:" + filterInfo.title); } return(true); } if (!String.IsNullOrEmpty(filterInfo.year) && videoItem.year == 0) { return(true); } if (VideoItemFilterContainsString(filterInfo.year, videoItem.year.ToString())) { if (logFiltered) { MyLog.Add("FILTER : " + message + " year:" + videoItem.year + " filter:" + filterInfo.year); } return(true); } if (VideoItemFilterContainsString(filterInfo.playCount, videoItem.playCount.ToString())) { if (logFiltered) { MyLog.Add("FILTER : " + message + " playCount:" + videoItem.playCount + " filter:" + filterInfo.playCount); } return(true); } if (VideoItemFilterWatched(videoItem.watched, filterInfo.watched)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " watched:" + videoItem.watched + " filter:" + filterInfo.watched); } return(true); } if (VideoItemFilterContainsString(filterInfo.source, videoItem.source)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " source:" + videoItem.source + " filter:" + filterInfo.source); } return(true); } if (VideoItemFilterContainsString(filterInfo.sourceAlias, videoInfo.sourceAlias)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " sourceAlias:" + videoInfo.sourceAlias + " filter:" + filterInfo.sourceAlias); } return(true); } if (VideoItemFilterContainsString(filterInfo.mpaa, videoItem.mpaa)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " mpaa:" + videoItem.mpaa + " filter:" + filterInfo.mpaa); } return(true); } if (videoItem.tags != null) { string tags = String.Join(",", videoItem.tags); if (VideoItemFilterContainsString(filterInfo.tag, tags)) { if (logFiltered) { MyLog.Add("FILTER : " + message + " tags:" + tags + " filter:" + filterInfo.tag); } return(true); } } } return(false); }
private string RunFFprobe(string videoFilePath) { Process process = null; string encoding = null; string error = null; if (!File.Exists(videoFilePath)) { // MyLog.Add("Video not found " + fileInfo.FullName); return(encoding); } string ffprobeExe = MyFile.EnsureDataFile("ffprobe", "exe", @"libs/ffmpeg/bin"); if (!File.Exists(ffprobeExe)) { // MyLog.Add("FFMPEG: not found " + ffprobeExe); return(encoding); } try { encodingFFProbeError = ""; encodingFFProbeOutput = ""; string workingDirectory = MyFile.exeDirectory; // MyFile.exeDirectory + "/temp"; // MyFile.exeDirectory; string arguments = string.Format("-v warning -show_error -show_format -show_streams -print_format xml \"{0}\"", videoFilePath); // MyLog.Add("RunFFprobe: Start " + videoItemFile.FullName + ": \"" + ffprobeExe + "\" " + arguments); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = ffprobeExe; startInfo.Arguments = arguments; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.WorkingDirectory = workingDirectory; process = new Process(); process.StartInfo = startInfo; process.OutputDataReceived += RunFFprobe_Output; process.ErrorDataReceived += RunFFprobe_Error; // use this order of events to avoid deadlock // http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx // http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived%28v=vs.110%29.aspx process.Start(); // StreamReader streamReaderError = process.StandardError; // encoding = process.StandardError.ReadToEnd(); // process.BeginOutputReadLine(); // encoding = process.StandardOutput.ReadToEnd(); // works, simplier process.BeginOutputReadLine(); process.BeginErrorReadLine(); // so far doesnt seem to catch errors process.WaitForExit(5000); if (!String.IsNullOrEmpty(encodingFFProbeError)) { MyLog.Add("RunFFprobe: Error on " + videoFilePath + " : " + encodingFFProbeError); } encoding = encodingFFProbeOutput.Trim(); // clean up temp folder occasionaly Random random = new Random(); int chance = random.Next(0, 100); if (false && chance < 25) { string[] ffprobeLogs = Directory.GetFiles(workingDirectory, "ffprobe*.log"); foreach (string ffprobeLog in ffprobeLogs) { File.Delete(ffprobeLog); } } } catch (Exception e) { MyLog.Add("RunFFprobe: " + e.ToString()); } // MyLog.Add("RunFFprobe: Finish " + videoItemFile.FullName + ": " + encoding); try { string status; if (process.ExitCode == 0) { status = "Success"; } else { status = "Error"; } MyLog.Add("RunFFprobe: " + status + " code:" + process.ExitCode.ToString() + " probed in:" + process.TotalProcessorTime.Milliseconds.ToString() + "ms"); } catch (Exception) { } if (error != null) { MyLog.Add(error); } if (process != null) { process.Close(); } // meh, throttle some Thread.Sleep(10); return(encoding); }
public void SetFilterForm(FilterInfo filterInfo) { try { if (filterInfo.filterType == 1) { } else if (filterInfo.filterType == 0) { foreach (KeyValuePair <string, string> type in criteriaTypes) { string selectedTags = null; switch (type.Key) { case "height": if (String.IsNullOrEmpty(filterInfo.height)) { continue; } selectedTags = filterInfo.height; break; case "imdbRating": if (String.IsNullOrEmpty(filterInfo.imdbRating)) { continue; } selectedTags = filterInfo.imdbRating; break; case "mpaa": if (String.IsNullOrEmpty(filterInfo.mpaa)) { continue; } selectedTags = filterInfo.mpaa; break; case "playCount": if (String.IsNullOrEmpty(filterInfo.playCount)) { continue; } selectedTags = filterInfo.playCount; break; case "rating": if (String.IsNullOrEmpty(filterInfo.rating)) { continue; } selectedTags = filterInfo.rating; break; case "source": if (String.IsNullOrEmpty(filterInfo.source)) { continue; } selectedTags = filterInfo.source; break; case "tag": if (String.IsNullOrEmpty(filterInfo.tag)) { continue; } selectedTags = filterInfo.tag; break; case "watched": if (filterInfo.watched == "ANY") { selectedTags = VideoFileEnums.watched.GetTextByKey("YES"); selectedTags += ","; selectedTags += VideoFileEnums.watched.GetTextByKey("NO"); } else if (!VideoFileEnums.watched.KeyExists(filterInfo.watched)) { continue; } else { selectedTags = VideoFileEnums.watched.GetTextByKey(filterInfo.watched); } break; case "width": if (String.IsNullOrEmpty(filterInfo.height)) { continue; } selectedTags = filterInfo.width; break; case "year": if (String.IsNullOrEmpty(filterInfo.year)) { continue; } selectedTags = filterInfo.year; break; default: continue; } AddCriteria(type.Key, selectedTags); } } } catch (Exception e) { MyLog.Add("SetFilterForm: " + e.ToString()); } }