diff --git a/TVRename#/App/ApplicationBase.cs b/TVRename#/App/ApplicationBase.cs index 2d8288ac9..4bce88104 100644 --- a/TVRename#/App/ApplicationBase.cs +++ b/TVRename#/App/ApplicationBase.cs @@ -94,7 +94,7 @@ protected override void OnCreateMainForm() } // Try loading TheTVDB cache file - TheTVDB.Instance.setup(tvdbFile, PathManager.TVDBFile, clargs); + TheTVDB.Instance.Setup(tvdbFile, PathManager.TVDBFile, clargs); // Try loading settings file doc = new TVDoc(settingsFile, clargs); @@ -111,7 +111,7 @@ protected override void OnCreateMainForm() if (!TheTVDB.Instance.LoadOK && !string.IsNullOrEmpty(TheTVDB.Instance.LoadErr)) recoverText += $"{Environment.NewLine}{TheTVDB.Instance.LoadErr}"; } while (recover); - convertSeriesTimeZones(doc, TheTVDB.Instance); + ConvertSeriesTimeZones(doc, TheTVDB.Instance); // Show user interface UI ui = new UI(doc, (TVRenameSplash)this.SplashScreen, !clargs.Unattended && !clargs.Hide); @@ -122,7 +122,7 @@ protected override void OnCreateMainForm() this.MainForm = ui; } - private void convertSeriesTimeZones(TVDoc doc, TheTVDB tvdb) + private static void ConvertSeriesTimeZones(TVDoc doc, TheTVDB tvdb) { //this is just to convert timezones in the TheTVDB into the TVDOC where they should be: //itshould only do anything the first time it is run and then be entirely begign @@ -131,12 +131,14 @@ private void convertSeriesTimeZones(TVDoc doc, TheTVDB tvdb) foreach (ShowItem si in doc.ShowItems) { string newTimeZone = tvdb.GetSeries(si.TVDBCode)?.tempTimeZone; - if ((si.ShowTimeZone == TimeZone.DefaultTimeZone()) && newTimeZone != TimeZone.DefaultTimeZone() && !string.IsNullOrWhiteSpace(newTimeZone)) - { - si.ShowTimeZone = newTimeZone; - doc.SetDirty(); - logger.Info("Copied timezone:{0} onto series {1}", newTimeZone, si.ShowName); - } + + if (string.IsNullOrWhiteSpace(newTimeZone)) continue; + if ( newTimeZone == TimeZone.DefaultTimeZone() ) continue; + if (si.ShowTimeZone != TimeZone.DefaultTimeZone()) continue; + + si.ShowTimeZone = newTimeZone; + doc.SetDirty(); + logger.Info("Copied timezone:{0} onto series {1}", newTimeZone, si.ShowName); } } diff --git a/TVRename#/App/AutoFolderMonitor.cs b/TVRename#/App/AutoFolderMonitor.cs index 18415d65c..5996cca64 100644 --- a/TVRename#/App/AutoFolderMonitor.cs +++ b/TVRename#/App/AutoFolderMonitor.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.IO; using Directory = Alphaleonis.Win32.Filesystem.Directory; @@ -5,10 +6,10 @@ namespace TVRename { - public class AutoFolderMonitor + public sealed class AutoFolderMonitor :IDisposable { - private TVDoc mDoc; - private UI mUI; + private readonly TVDoc mDoc; + private readonly UI mUI; private List Watchers = new List(); private System.Timers.Timer mScanDelayTimer; private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); @@ -114,5 +115,11 @@ public void StopMonitor() } Watchers.Clear(); } + + public void Dispose() + { + // ReSharper disable once UseNullPropagation + if (this.mScanDelayTimer != null) this.mScanDelayTimer.Dispose(); + } } } diff --git a/TVRename#/Custom Controls/MyListView.cs b/TVRename#/Custom Controls/MyListView.cs index e9d28533b..38a0b9d33 100644 --- a/TVRename#/Custom Controls/MyListView.cs +++ b/TVRename#/Custom Controls/MyListView.cs @@ -94,22 +94,28 @@ protected override void OnKeyUp(KeyEventArgs e) private const int SB_HORZ = 0; private const int SB_VERT = 1; - [DllImport("user32.dll")] - static extern int GetScrollPos(IntPtr hWnd, int nBar); - - [DllImport("user32.dll")] - static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); - public int GetScrollVerticalPos() { - return GetScrollPos(this.Handle, SB_VERT); + return NativeMethods.GetScrollPos(this.Handle, SB_VERT); } public void SetScrollVerticalPos(int position) { - var currentPos = GetScrollPos(this.Handle, SB_VERT); + var currentPos = NativeMethods.GetScrollPos(this.Handle, SB_VERT); var delta = -(currentPos - position); - SendMessage(this.Handle, LVM_SCROLL, IntPtr.Zero, (IntPtr)delta); // First param is horizontal scroll amount, second is vertical scroll amount + NativeMethods.SendMessage(this.Handle, LVM_SCROLL, IntPtr.Zero, (IntPtr)delta); // First param is horizontal scroll amount, second is vertical scroll amount } } -} \ No newline at end of file + internal static partial class NativeMethods + { + [DllImport("user32.dll")] + internal static extern int GetScrollPos(IntPtr hWnd, int nBar); + + [DllImport("user32.dll")] + internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + // MAH: Added in support of the Filter TextBox Button + [System.Runtime.InteropServices.DllImport("user32.dll")] + internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); + } +} diff --git a/TVRename#/Custom Controls/TheTVDBCodeFinder.cs b/TVRename#/Custom Controls/TheTVDBCodeFinder.cs index 5c95cde09..a31dbd6ab 100644 --- a/TVRename#/Custom Controls/TheTVDBCodeFinder.cs +++ b/TVRename#/Custom Controls/TheTVDBCodeFinder.cs @@ -58,27 +58,27 @@ public int SelectedCode() if (this.lvMatches.SelectedItems.Count == 0) return int.Parse(this.txtFindThis.Text); - return (int) (this.lvMatches.SelectedItems[0].Tag); + return (int.Parse(this.lvMatches.SelectedItems[0].SubItems[0].Text)); } catch { return -1; } } - public string SelectedShowName() + + public SeriesInfo SelectedShow() { try { - if (this.lvMatches.SelectedItems.Count == 0) return ""; + if (this.lvMatches.SelectedItems.Count == 0) return null; - return (string)(this.lvMatches.SelectedItems[0].SubItems[1].Text); + return ((SeriesInfo)(this.lvMatches.SelectedItems[0].Tag)); } catch { - return ""; + return null; } } - private void txtFindThis_TextChanged(object sender, EventArgs e) { if (!this.mInternal) @@ -135,7 +135,7 @@ private void DoFind(bool chooseOnlyMatch) lvi.SubItems.Add(show); lvi.SubItems.Add(kvp.Value.FirstAired != null ? kvp.Value.FirstAired.Value.Year.ToString() : ""); - lvi.Tag = num; + lvi.Tag = kvp.Value; if (numberMatch) lvi.Selected = true; this.lvMatches.Items.Add(lvi); diff --git a/TVRename#/DownloadIdentifers/DownloadEpisodeJPG.cs b/TVRename#/DownloadIdentifers/DownloadEpisodeJPG.cs index f943af77b..dfd031c38 100644 --- a/TVRename#/DownloadIdentifers/DownloadEpisodeJPG.cs +++ b/TVRename#/DownloadIdentifers/DownloadEpisodeJPG.cs @@ -11,7 +11,7 @@ class DownloadEpisodeJPG : DownloadIdentifier public DownloadEpisodeJPG() { - reset(); + this.reset(); } public override DownloadType GetDownloadType() @@ -42,10 +42,9 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo, bo return base.ProcessEpisode(dbep, filo, forceRefresh); } - public override void reset() + public sealed override void reset() { doneJPG = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadFanartJPG.cs b/TVRename#/DownloadIdentifers/DownloadFanartJPG.cs index df5aab21a..89a04957f 100644 --- a/TVRename#/DownloadIdentifers/DownloadFanartJPG.cs +++ b/TVRename#/DownloadIdentifers/DownloadFanartJPG.cs @@ -41,10 +41,9 @@ public override ItemList ProcessShow(ShowItem si, bool forceRefresh) return base.ProcessShow(si, forceRefresh); } - public override void reset() + public sealed override void reset() { doneFanartJPG = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadIdentifier.cs b/TVRename#/DownloadIdentifers/DownloadIdentifier.cs index 4b9729518..fc75d8e08 100644 --- a/TVRename#/DownloadIdentifers/DownloadIdentifier.cs +++ b/TVRename#/DownloadIdentifers/DownloadIdentifier.cs @@ -4,8 +4,7 @@ namespace TVRename { abstract class DownloadIdentifier { - - public DownloadIdentifier() + protected DownloadIdentifier() { } @@ -51,6 +50,6 @@ public virtual void notifyComplete(FileInfo file) { } - public virtual void reset() { } + public abstract void reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadIdentifiersController.cs b/TVRename#/DownloadIdentifers/DownloadIdentifiersController.cs index 6daa4e872..d6cd6c712 100644 --- a/TVRename#/DownloadIdentifers/DownloadIdentifiersController.cs +++ b/TVRename#/DownloadIdentifers/DownloadIdentifiersController.cs @@ -15,7 +15,7 @@ public DownloadIdentifiersController() { Identifiers.Add(new DownloadMede8erMetaData()); Identifiers.Add(new DownloadpyTivoMetaData()); Identifiers.Add(new DownloadSeriesJPG()); - Identifiers.Add(new DownloadKODIMetaData()); + Identifiers.Add(new DownloadKodiMetaData()); Identifiers.Add(new DownloadKODIImages()); Identifiers.Add(new IncorrectFileDates()); } diff --git a/TVRename#/DownloadIdentifers/DownloadJolderJPG.cs b/TVRename#/DownloadIdentifers/DownloadJolderJPG.cs index 6a37d8844..b9666376f 100644 --- a/TVRename#/DownloadIdentifers/DownloadJolderJPG.cs +++ b/TVRename#/DownloadIdentifers/DownloadJolderJPG.cs @@ -88,10 +88,9 @@ public override ItemList ProcessSeason(ShowItem si, string folder, int snum, boo return base.ProcessSeason(si,folder,snum,forceRefresh); } - public override void reset() + public sealed override void reset() { doneFolderJPG = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadMede8erMetaData.cs b/TVRename#/DownloadIdentifers/DownloadMede8erMetaData.cs index 2c228a51f..50004668b 100644 --- a/TVRename#/DownloadIdentifers/DownloadMede8erMetaData.cs +++ b/TVRename#/DownloadIdentifers/DownloadMede8erMetaData.cs @@ -3,6 +3,7 @@ namespace TVRename { + // ReSharper disable once InconsistentNaming class DownloadMede8erMetaData : DownloadIdentifier { private List doneFiles; @@ -83,10 +84,9 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo, bo return base.ProcessEpisode(dbep, filo, forceRefresh); } - public override void reset() + public sealed override void reset() { this.doneFiles = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadSeriesJPG.cs b/TVRename#/DownloadIdentifers/DownloadSeriesJPG.cs index b6bcf92ff..87a9d7dc6 100644 --- a/TVRename#/DownloadIdentifers/DownloadSeriesJPG.cs +++ b/TVRename#/DownloadIdentifers/DownloadSeriesJPG.cs @@ -3,7 +3,7 @@ namespace TVRename { - class DownloadSeriesJPG : DownloadIdentifier + sealed class DownloadSeriesJPG : DownloadIdentifier { private List doneJPG; private const string defaultFileName = "series.jpg"; @@ -41,7 +41,6 @@ public override ItemList ProcessSeason(ShowItem si, string folder, int snum, boo public override void reset() { doneJPG = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadXBMCImages.cs b/TVRename#/DownloadIdentifers/DownloadXBMCImages.cs index 42f8b6e6d..9d7f3e0d0 100644 --- a/TVRename#/DownloadIdentifers/DownloadXBMCImages.cs +++ b/TVRename#/DownloadIdentifers/DownloadXBMCImages.cs @@ -207,13 +207,12 @@ private ActionDownloadImage DoEpisode(ShowItem si, Episode ep, FileInfo filo,str } - public override void reset() + public sealed override void reset() { doneBannerJPG = new List(); donePosterJPG = new List(); doneFanartJPG = new List(); doneTBN = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadXBMCMetaData.cs b/TVRename#/DownloadIdentifers/DownloadXBMCMetaData.cs index af63d2fe8..0cd855247 100644 --- a/TVRename#/DownloadIdentifers/DownloadXBMCMetaData.cs +++ b/TVRename#/DownloadIdentifers/DownloadXBMCMetaData.cs @@ -5,11 +5,11 @@ namespace TVRename { - class DownloadKODIMetaData : DownloadIdentifier + class DownloadKodiMetaData : DownloadIdentifier { private static List doneNFO; - public DownloadKODIMetaData() + public DownloadKodiMetaData() { reset(); } @@ -23,7 +23,7 @@ public override void notifyComplete(FileInfo file) { if (file.FullName.EndsWith(".nfo", true, new CultureInfo("en"))) { - DownloadKODIMetaData.doneNFO.Add(file.FullName); + DownloadKodiMetaData.doneNFO.Add(file.FullName); } base.notifyComplete(file); } @@ -41,12 +41,12 @@ public override ItemList ProcessShow(ShowItem si, bool forceRefresh) // was it written before we fixed the bug in ? (tvshownfo.LastWriteTime.ToUniversalTime().CompareTo(new DateTime(2009, 9, 13, 7, 30, 0, 0, DateTimeKind.Utc)) < 0); - bool alreadyOnTheList = DownloadKODIMetaData.doneNFO.Contains(tvshownfo.FullName); + bool alreadyOnTheList = DownloadKodiMetaData.doneNFO.Contains(tvshownfo.FullName); if ((forceRefresh || needUpdate) && !alreadyOnTheList) { TheActionList.Add(new ActionNFO(tvshownfo, si)); - DownloadKODIMetaData.doneNFO.Add(tvshownfo.FullName); + DownloadKodiMetaData.doneNFO.Add(tvshownfo.FullName); } return TheActionList; @@ -66,7 +66,7 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo,boo if (!nfo.Exists || (dbep.Srv_LastUpdated > TimeZone.Epoch(nfo.LastWriteTime)) || forceRefresh) { //If we do not already have plans to put the file into place - if (!(DownloadKODIMetaData.doneNFO.Contains(nfo.FullName))) + if (!(DownloadKodiMetaData.doneNFO.Contains(nfo.FullName))) { TheActionList.Add(new ActionNFO(nfo, dbep)); doneNFO.Add(nfo.FullName); @@ -77,10 +77,9 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo,boo return base.ProcessEpisode(dbep, filo, forceRefresh); } - public override void reset() + public sealed override void reset() { doneNFO = new List(); - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/DownloadpyTivoMetaData.cs b/TVRename#/DownloadIdentifers/DownloadpyTivoMetaData.cs index 2b8a9940a..473d696ea 100644 --- a/TVRename#/DownloadIdentifers/DownloadpyTivoMetaData.cs +++ b/TVRename#/DownloadIdentifers/DownloadpyTivoMetaData.cs @@ -35,9 +35,8 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo, bo return base.ProcessEpisode(dbep, filo, forceRefresh); } - public override void reset() + public sealed override void reset() { - base.reset(); } } diff --git a/TVRename#/DownloadIdentifers/IncorrectFileDates.cs b/TVRename#/DownloadIdentifers/IncorrectFileDates.cs index 5e5943d36..1092fc579 100644 --- a/TVRename#/DownloadIdentifers/IncorrectFileDates.cs +++ b/TVRename#/DownloadIdentifers/IncorrectFileDates.cs @@ -74,7 +74,6 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo, bo public override void reset() { this.doneFilesAndFolders = new List(); - base.reset(); } } diff --git a/TVRename#/Exporter/Exporter.cs b/TVRename#/Exporter/Exporter.cs index 58ba8b367..025cd2345 100644 --- a/TVRename#/Exporter/Exporter.cs +++ b/TVRename#/Exporter/Exporter.cs @@ -41,16 +41,19 @@ private string Produce() // when windows restarts, the share isn't "back" before this timer times out and fires // windows explorer tends to lose explorer windows on shares when slept/resumed, too, so its not // just me :P - - MemoryStream ms = new MemoryStream(); //duplicated the IF statement one for RSS and one for XML so that both can be generated. - List lpe = mDoc.NextNShows(TVSettings.Instance.ExportRSSMaxShows, TVSettings.Instance.ExportRSSDaysPast, TVSettings.Instance.ExportRSSMaxDays); - if (lpe != null) - if (this.Generate(ms,lpe )) - { - return System.Text.Encoding.ASCII.GetString(ms.ToArray()); - } - + + using (MemoryStream ms = new MemoryStream()) + { + List lpe = mDoc.NextNShows(TVSettings.Instance.ExportRSSMaxShows, + TVSettings.Instance.ExportRSSDaysPast, TVSettings.Instance.ExportRSSMaxDays); + if (lpe != null) + if (this.Generate(ms, lpe)) + { + return System.Text.Encoding.ASCII.GetString(ms.ToArray()); + } + } } + catch (Exception e) { Logger.Error(e, "Failed to produce records to put into Export file at: {0}", Location()); @@ -67,12 +70,13 @@ public void Run() //Create the directory if needed Directory.CreateDirectory(Path.GetDirectoryName(Location()) ??""); + string contents = Produce(); //Write Contents to file - StreamWriter file = new StreamWriter(Location()); - String contents = Produce(); - file.Write(contents); - file.Close(); + using (StreamWriter file = new StreamWriter(Location())) + { + file.Write(contents); + } Logger.Info("Output File to :{0}", Location()); Logger.Trace("contents of File are :{0}", contents); diff --git a/TVRename#/Exporter/MissingXML.cs b/TVRename#/Exporter/MissingXML.cs index de2fd7d2e..cfaf44e51 100644 --- a/TVRename#/Exporter/MissingXML.cs +++ b/TVRename#/Exporter/MissingXML.cs @@ -51,7 +51,6 @@ public override void Run(ItemList TheActionList) writer.WriteEndElement(); // MissingItems writer.WriteEndElement(); // tvrename writer.WriteEndDocument(); - writer.Close(); } } } diff --git a/TVRename#/Exporter/UpcomingRSS.cs b/TVRename#/Exporter/UpcomingRSS.cs index 2bb4bd0d9..deb9bc30a 100644 --- a/TVRename#/Exporter/UpcomingRSS.cs +++ b/TVRename#/Exporter/UpcomingRSS.cs @@ -54,7 +54,6 @@ protected override bool Generate(System.IO.Stream str, List el writer.WriteEndElement(); //channel writer.WriteEndElement(); //rss writer.WriteEndDocument(); - writer.Close(); } return true; } // try diff --git a/TVRename#/Exporter/UpcomingXML.cs b/TVRename#/Exporter/UpcomingXML.cs index aa2d0d203..666b7f0c7 100644 --- a/TVRename#/Exporter/UpcomingXML.cs +++ b/TVRename#/Exporter/UpcomingXML.cs @@ -65,7 +65,6 @@ protected override bool Generate(System.IO.Stream str, List e } writer.WriteEndElement(); writer.WriteEndDocument(); - writer.Close(); } return true; } // try diff --git a/TVRename#/Finders/RSSFinder.cs b/TVRename#/Finders/RSSFinder.cs index ddf23ade0..da3f883f1 100644 --- a/TVRename#/Finders/RSSFinder.cs +++ b/TVRename#/Finders/RSSFinder.cs @@ -106,35 +106,35 @@ public bool DownloadRSS(string URL, List rexps) IgnoreComments = true, IgnoreWhitespace = true }; - XmlReader reader = XmlReader.Create(ms, settings); - - reader.Read(); - if (reader.Name != "xml") - return false; + using (XmlReader reader = XmlReader.Create(ms, settings)) + { - reader.Read(); + reader.Read(); + if (reader.Name != "xml") + return false; - if (reader.Name != "rss") - return false; + reader.Read(); - reader.Read(); + if (reader.Name != "rss") + return false; - while (!reader.EOF) - { - if ((reader.Name == "rss") && (!reader.IsStartElement())) - break; + reader.Read(); - if (reader.Name == "channel") + while (!reader.EOF) { - if (!this.ReadChannel(reader.ReadSubtree())) - return false; - reader.Read(); + if ((reader.Name == "rss") && (!reader.IsStartElement())) + break; + + if (reader.Name == "channel") + { + if (!this.ReadChannel(reader.ReadSubtree())) + return false; + reader.Read(); + } + else + reader.ReadOuterXml(); } - else - reader.ReadOuterXml(); } - - ms.Close(); } catch { diff --git a/TVRename#/Forms/AddEditSearchEngine.Designer.cs b/TVRename#/Forms/AddEditSearchEngine.Designer.cs index 2dd7843f3..ae608db2d 100644 --- a/TVRename#/Forms/AddEditSearchEngine.Designer.cs +++ b/TVRename#/Forms/AddEditSearchEngine.Designer.cs @@ -1,4 +1,4 @@ -// +// // Main website for TVRename is http://tvrename.com // // Source code available at https://github.com/TV-Rename/tvrename @@ -22,6 +22,7 @@ partial class AddEditSearchEngine /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { + this.Cntfw?.Close(); if (disposing && (components != null)) { components.Dispose(); @@ -145,4 +146,4 @@ private void InitializeComponent() private System.Windows.Forms.Button bnOK; private System.Windows.Forms.Button bnTags; } -} \ No newline at end of file +} diff --git a/TVRename#/Forms/AddEditSearchEngine.cs b/TVRename#/Forms/AddEditSearchEngine.cs index 2763c4689..7176c79b9 100644 --- a/TVRename#/Forms/AddEditSearchEngine.cs +++ b/TVRename#/Forms/AddEditSearchEngine.cs @@ -96,14 +96,9 @@ public void AddNewRow() this.Grid1[r, 1] = new SourceGrid.Cells.Cell("", typeof(string)); } - /// - /// Clean up any resources being used. - /// - ~AddEditSearchEngine() - { - if (this.Cntfw != null) - this.Cntfw.Close(); - } + + + private void bnAdd_Click(object sender, System.EventArgs e) { @@ -138,4 +133,4 @@ private void bnTags_Click(object sender, System.EventArgs e) this.Focus(); } } -} \ No newline at end of file +} diff --git a/TVRename#/Forms/AutoAddShow.cs b/TVRename#/Forms/AutoAddShow.cs index 515553654..4b7cb753b 100644 --- a/TVRename#/Forms/AutoAddShow.cs +++ b/TVRename#/Forms/AutoAddShow.cs @@ -22,14 +22,14 @@ public AutoAddShow(string hint) this.cbDirectory.SuspendLayout(); this.cbDirectory.Items.Clear(); - this.cbDirectory.Items.AddRange(TVSettings.Instance.MonitorFoldersNames.ToArray()); + this.cbDirectory.Items.AddRange(TVSettings.Instance.LibraryFoldersNames.ToArray()); this.cbDirectory.SelectedIndex = 0; this.cbDirectory.ResumeLayout(); } private void MTCCF_SelectionChanged(object sender, EventArgs e) { - this.lblDirectoryName.Text = System.IO.Path.DirectorySeparatorChar + TVSettings.Instance.FilenameFriendly(FileHelper.MakeValidPath(this.mTCCF.SelectedShowName( ))); + this.lblDirectoryName.Text = System.IO.Path.DirectorySeparatorChar + TVSettings.Instance.FilenameFriendly(FileHelper.MakeValidPath(this.mTCCF.SelectedShow()?.Name )); } public ShowItem ShowItem => this.mSI; @@ -42,8 +42,9 @@ private void SetShowItem() this.mSI.TVDBCode = code; this.mSI.AutoAdd_FolderBase = this.cbDirectory.Text+this.lblDirectoryName.Text; this.mSI.PadSeasonToTwoDigits = true; - //Set Default Timezone based on Network?? - //this.mSI.ShowTimeZone + //Set Default Timezone based on Network + this.mSI.ShowTimeZone = TimeZone.TimeZoneForNetwork(this.mTCCF.SelectedShow()?.getNetwork()); + } private void btnOK_Click(object sender, EventArgs e) @@ -63,7 +64,7 @@ private bool OkToClose() { if (TheTVDB.Instance.HasSeries(this.mTCCF.SelectedCode())) return true; - DialogResult dr = MessageBox.Show("tvdb code unknown, close anyway?", "TVRename Add/Edit Show", + DialogResult dr = MessageBox.Show("tvdb code unknown, close anyway?", "TVRename Auto Add Show", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); return dr != DialogResult.No; diff --git a/TVRename#/Forms/BugReport.cs b/TVRename#/Forms/BugReport.cs index f4e4594f1..1f54c369c 100644 --- a/TVRename#/Forms/BugReport.cs +++ b/TVRename#/Forms/BugReport.cs @@ -48,9 +48,9 @@ private void bnCreate_Click(object sender, System.EventArgs e) txt.Append("\r\n"); try { - StreamReader sr = new StreamReader(PathManager.TVDocSettingsFile.FullName); - txt.Append(sr.ReadToEnd()); - sr.Close(); + using (StreamReader sr = new StreamReader(PathManager.TVDocSettingsFile.FullName)) + txt.Append(sr.ReadToEnd()); + txt.Append("\r\n"); } catch diff --git a/TVRename#/Forms/CopyMoveProgress.Designer.cs b/TVRename#/Forms/CopyMoveProgress.Designer.cs index 82e9c46a3..09fc172a6 100644 --- a/TVRename#/Forms/CopyMoveProgress.Designer.cs +++ b/TVRename#/Forms/CopyMoveProgress.Designer.cs @@ -22,10 +22,21 @@ partial class CopyMoveProgress /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { + this.copyTimer.Stop(); + this.diskSpaceTimer.Stop(); + if (disposing && (components != null)) { components.Dispose(); } + if (disposing && (copyTimer != null)) + { + copyTimer.Dispose(); + } + if (disposing && (diskSpaceTimer != null)) + { + diskSpaceTimer.Dispose(); + } base.Dispose(disposing); } diff --git a/TVRename#/Forms/CopyMoveProgress.cs b/TVRename#/Forms/CopyMoveProgress.cs index 41fba5d65..648249dda 100644 --- a/TVRename#/Forms/CopyMoveProgress.cs +++ b/TVRename#/Forms/CopyMoveProgress.cs @@ -45,14 +45,7 @@ public CopyMoveProgress(TVDoc doc, ActionQueue[] todo) this.diskSpaceTimer.Start(); } - /// - /// Clean up any resources being used. - /// - ~CopyMoveProgress() - { - this.copyTimer.Stop(); - this.diskSpaceTimer.Stop(); - } + private void SetPercentages(double file, double group) { diff --git a/TVRename#/Forms/Filters.cs b/TVRename#/Forms/Filters.cs index 5dca7cb46..abffa61cc 100644 --- a/TVRename#/Forms/Filters.cs +++ b/TVRename#/Forms/Filters.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Windows.Forms; @@ -15,7 +15,7 @@ public Filters(TVDoc doc) this.clbGenre.Items.AddRange(doc.getGenres().Cast().ToArray()); this.cmbNetwork.Items.AddRange(doc.getNetworks().Cast().ToArray()); this.cmbShowStatus.Items.AddRange(doc.getStatuses().Cast().ToArray()); - this.cmbRating.Items.AddRange(doc.GetRatings().Cast().ToArray()); + this.cmbRating.Items.AddRange(doc.GetContentRatings().Cast().ToArray()); setButtonStates(); } diff --git a/TVRename#/Forms/Preferences.Designer.cs b/TVRename#/Forms/Preferences.Designer.cs index 9a5eb705b..7d47cc531 100644 --- a/TVRename#/Forms/Preferences.Designer.cs +++ b/TVRename#/Forms/Preferences.Designer.cs @@ -128,6 +128,7 @@ private void InitializeComponent() this.txtMissingCSV = new System.Windows.Forms.TextBox(); this.cbMissingCSV = new System.Windows.Forms.CheckBox(); this.tpScanOptions = new System.Windows.Forms.TabPage(); + this.chkAutoSearchForDownloadedFiles = new System.Windows.Forms.CheckBox(); this.chkAutoMergeEpisodes = new System.Windows.Forms.CheckBox(); this.chkPreventMove = new System.Windows.Forms.CheckBox(); this.label40 = new System.Windows.Forms.Label(); @@ -235,7 +236,15 @@ private void InitializeComponent() this.pyTivoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mede8erToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.noneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.chkAutoSearchForDownloadedFiles = new System.Windows.Forms.CheckBox(); + this.tpBulkAdd = new System.Windows.Forms.TabPage(); + this.cbIgnoreRecycleBin = new System.Windows.Forms.CheckBox(); + this.cbIgnoreNoVideoFolders = new System.Windows.Forms.CheckBox(); + this.label41 = new System.Windows.Forms.Label(); + this.label42 = new System.Windows.Forms.Label(); + this.label43 = new System.Windows.Forms.Label(); + this.label44 = new System.Windows.Forms.Label(); + this.tbIgnoreSuffixes = new System.Windows.Forms.TextBox(); + this.tbMovieTerms = new System.Windows.Forms.TextBox(); this.groupBox2.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tbGeneral.SuspendLayout(); @@ -256,6 +265,7 @@ private void InitializeComponent() this.groupBox6.SuspendLayout(); this.tpTreeColoring.SuspendLayout(); this.cmDefaults.SuspendLayout(); + this.tpBulkAdd.SuspendLayout(); this.SuspendLayout(); // // OKButton @@ -584,6 +594,7 @@ private void InitializeComponent() this.tabControl1.Controls.Add(this.tbSearchFolders); this.tabControl1.Controls.Add(this.tbuTorrentNZB); this.tabControl1.Controls.Add(this.tpTreeColoring); + this.tabControl1.Controls.Add(this.tpBulkAdd); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Multiline = true; this.tabControl1.Name = "tabControl1"; @@ -981,10 +992,10 @@ private void InitializeComponent() this.tbAutoExport.Controls.Add(this.groupBox2); this.tbAutoExport.Controls.Add(this.txtMissingCSV); this.tbAutoExport.Controls.Add(this.cbMissingCSV); - this.tbAutoExport.Location = new System.Drawing.Point(4, 40); + this.tbAutoExport.Location = new System.Drawing.Point(4, 22); this.tbAutoExport.Name = "tbAutoExport"; this.tbAutoExport.Padding = new System.Windows.Forms.Padding(3); - this.tbAutoExport.Size = new System.Drawing.Size(416, 401); + this.tbAutoExport.Size = new System.Drawing.Size(416, 419); this.tbAutoExport.TabIndex = 2; this.tbAutoExport.Text = "Automatic Export"; this.tbAutoExport.UseVisualStyleBackColor = true; @@ -1199,14 +1210,24 @@ private void InitializeComponent() this.tpScanOptions.Controls.Add(this.cbCheckSABnzbd); this.tpScanOptions.Controls.Add(this.cbCheckuTorrent); this.tpScanOptions.Controls.Add(this.cbSearchLocally); - this.tpScanOptions.Location = new System.Drawing.Point(4, 40); + this.tpScanOptions.Location = new System.Drawing.Point(4, 22); this.tpScanOptions.Name = "tpScanOptions"; this.tpScanOptions.Padding = new System.Windows.Forms.Padding(3); - this.tpScanOptions.Size = new System.Drawing.Size(416, 401); + this.tpScanOptions.Size = new System.Drawing.Size(416, 419); this.tpScanOptions.TabIndex = 6; this.tpScanOptions.Text = "Scan Options"; this.tpScanOptions.UseVisualStyleBackColor = true; // + // chkAutoSearchForDownloadedFiles + // + this.chkAutoSearchForDownloadedFiles.AutoSize = true; + this.chkAutoSearchForDownloadedFiles.Location = new System.Drawing.Point(9, 334); + this.chkAutoSearchForDownloadedFiles.Name = "chkAutoSearchForDownloadedFiles"; + this.chkAutoSearchForDownloadedFiles.Size = new System.Drawing.Size(186, 17); + this.chkAutoSearchForDownloadedFiles.TabIndex = 14; + this.chkAutoSearchForDownloadedFiles.Text = "Notify when new shows are found"; + this.chkAutoSearchForDownloadedFiles.UseVisualStyleBackColor = true; + // // chkAutoMergeEpisodes // this.chkAutoMergeEpisodes.AutoSize = true; @@ -1368,10 +1389,10 @@ private void InitializeComponent() this.tbFolderDeleting.Controls.Add(this.cbEmptyIgnoreWords); this.tbFolderDeleting.Controls.Add(this.cbEmptyIgnoreExtensions); this.tbFolderDeleting.Controls.Add(this.cbDeleteEmpty); - this.tbFolderDeleting.Location = new System.Drawing.Point(4, 40); + this.tbFolderDeleting.Location = new System.Drawing.Point(4, 22); this.tbFolderDeleting.Name = "tbFolderDeleting"; this.tbFolderDeleting.Padding = new System.Windows.Forms.Padding(3); - this.tbFolderDeleting.Size = new System.Drawing.Size(416, 401); + this.tbFolderDeleting.Size = new System.Drawing.Size(416, 419); this.tbFolderDeleting.TabIndex = 9; this.tbFolderDeleting.Text = "Folder Deleting"; this.tbFolderDeleting.UseVisualStyleBackColor = true; @@ -2309,15 +2330,100 @@ private void InitializeComponent() this.noneToolStripMenuItem.Tag = "4"; this.noneToolStripMenuItem.Text = "&None"; // - // chkAutoSearchForDownloadedFiles - // - this.chkAutoSearchForDownloadedFiles.AutoSize = true; - this.chkAutoSearchForDownloadedFiles.Location = new System.Drawing.Point(9, 334); - this.chkAutoSearchForDownloadedFiles.Name = "chkAutoSearchForDownloadedFiles"; - this.chkAutoSearchForDownloadedFiles.Size = new System.Drawing.Size(186, 17); - this.chkAutoSearchForDownloadedFiles.TabIndex = 14; - this.chkAutoSearchForDownloadedFiles.Text = "Notify when new shows are found"; - this.chkAutoSearchForDownloadedFiles.UseVisualStyleBackColor = true; + // tpBulkAdd + // + this.tpBulkAdd.Controls.Add(this.label43); + this.tpBulkAdd.Controls.Add(this.label44); + this.tpBulkAdd.Controls.Add(this.tbIgnoreSuffixes); + this.tpBulkAdd.Controls.Add(this.tbMovieTerms); + this.tpBulkAdd.Controls.Add(this.label42); + this.tpBulkAdd.Controls.Add(this.label41); + this.tpBulkAdd.Controls.Add(this.cbIgnoreRecycleBin); + this.tpBulkAdd.Controls.Add(this.cbIgnoreNoVideoFolders); + this.tpBulkAdd.Location = new System.Drawing.Point(4, 40); + this.tpBulkAdd.Name = "tpBulkAdd"; + this.tpBulkAdd.Padding = new System.Windows.Forms.Padding(3); + this.tpBulkAdd.Size = new System.Drawing.Size(416, 401); + this.tpBulkAdd.TabIndex = 10; + this.tpBulkAdd.Text = "Bulk/Auto Add"; + this.tpBulkAdd.UseVisualStyleBackColor = true; + // + // cbIgnoreRecycleBin + // + this.cbIgnoreRecycleBin.AutoSize = true; + this.cbIgnoreRecycleBin.Location = new System.Drawing.Point(15, 62); + this.cbIgnoreRecycleBin.Name = "cbIgnoreRecycleBin"; + this.cbIgnoreRecycleBin.Size = new System.Drawing.Size(116, 17); + this.cbIgnoreRecycleBin.TabIndex = 4; + this.cbIgnoreRecycleBin.Text = "Ignore &Recycle Bin"; + this.toolTip1.SetToolTip(this.cbIgnoreRecycleBin, "If set then Bulk Add ignores all files in the Recycle Bin"); + this.cbIgnoreRecycleBin.UseVisualStyleBackColor = true; + // + // cbIgnoreNoVideoFolders + // + this.cbIgnoreNoVideoFolders.AutoSize = true; + this.cbIgnoreNoVideoFolders.Location = new System.Drawing.Point(15, 39); + this.cbIgnoreNoVideoFolders.Name = "cbIgnoreNoVideoFolders"; + this.cbIgnoreNoVideoFolders.Size = new System.Drawing.Size(225, 17); + this.cbIgnoreNoVideoFolders.TabIndex = 3; + this.cbIgnoreNoVideoFolders.Text = "&Only Include Folders containing Video files"; + this.toolTip1.SetToolTip(this.cbIgnoreNoVideoFolders, "If set then only folders that contain video files are considered for the \'Bulk Ad" + + "d\' feature"); + this.cbIgnoreNoVideoFolders.UseVisualStyleBackColor = true; + // + // label41 + // + this.label41.AutoSize = true; + this.label41.Location = new System.Drawing.Point(12, 13); + this.label41.Name = "label41"; + this.label41.Size = new System.Drawing.Size(53, 13); + this.label41.TabIndex = 5; + this.label41.Text = "Bulk Add:"; + // + // label42 + // + this.label42.AutoSize = true; + this.label42.Location = new System.Drawing.Point(12, 92); + this.label42.Name = "label42"; + this.label42.Size = new System.Drawing.Size(54, 13); + this.label42.TabIndex = 6; + this.label42.Text = "Auto Add:"; + // + // label43 + // + this.label43.AutoSize = true; + this.label43.Location = new System.Drawing.Point(12, 141); + this.label43.Name = "label43"; + this.label43.Size = new System.Drawing.Size(78, 13); + this.label43.TabIndex = 10; + this.label43.Text = "&Ignore suffixes:"; + // + // label44 + // + this.label44.AutoSize = true; + this.label44.Location = new System.Drawing.Point(12, 115); + this.label44.Name = "label44"; + this.label44.Size = new System.Drawing.Size(71, 13); + this.label44.TabIndex = 8; + this.label44.Text = "&Movie Terms:"; + // + // tbIgnoreSuffixes + // + this.tbIgnoreSuffixes.Location = new System.Drawing.Point(108, 138); + this.tbIgnoreSuffixes.Name = "tbIgnoreSuffixes"; + this.tbIgnoreSuffixes.Size = new System.Drawing.Size(293, 20); + this.tbIgnoreSuffixes.TabIndex = 11; + this.toolTip1.SetToolTip(this.tbIgnoreSuffixes, "These terms and any text after them will be ignored when\r\nsearching on TVDB for t" + + "he show title based on the filename."); + // + // tbMovieTerms + // + this.tbMovieTerms.Location = new System.Drawing.Point(108, 112); + this.tbMovieTerms.Name = "tbMovieTerms"; + this.tbMovieTerms.Size = new System.Drawing.Size(293, 20); + this.tbMovieTerms.TabIndex = 9; + this.toolTip1.SetToolTip(this.tbMovieTerms, "If a filename contains any of these terms then it is assumed\r\nthat it is a Film a" + + "nd not a TV Show. Hence \'Auto Add\' is not\r\ninvoked for this file."); // // Preferences // @@ -2376,6 +2482,8 @@ private void InitializeComponent() this.tpTreeColoring.ResumeLayout(false); this.tpTreeColoring.PerformLayout(); this.cmDefaults.ResumeLayout(false); + this.tpBulkAdd.ResumeLayout(false); + this.tpBulkAdd.PerformLayout(); this.ResumeLayout(false); } @@ -2591,5 +2699,14 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox chkPreventMove; private System.Windows.Forms.CheckBox chkAutoMergeEpisodes; private System.Windows.Forms.CheckBox chkAutoSearchForDownloadedFiles; + private System.Windows.Forms.TabPage tpBulkAdd; + private System.Windows.Forms.Label label41; + private System.Windows.Forms.CheckBox cbIgnoreRecycleBin; + private System.Windows.Forms.CheckBox cbIgnoreNoVideoFolders; + private System.Windows.Forms.Label label42; + private System.Windows.Forms.Label label43; + private System.Windows.Forms.Label label44; + private System.Windows.Forms.TextBox tbIgnoreSuffixes; + private System.Windows.Forms.TextBox tbMovieTerms; } } diff --git a/TVRename#/Forms/Preferences.cs b/TVRename#/Forms/Preferences.cs index b0ab4dc86..c9e40eb60 100644 --- a/TVRename#/Forms/Preferences.cs +++ b/TVRename#/Forms/Preferences.cs @@ -196,6 +196,11 @@ private void OKButton_Click(object sender, System.EventArgs e) S.Tidyup.EmptyMaxSizeCheck = this.cbEmptyMaxSize.Checked; int.TryParse(this.txtEmptyMaxSize.Text, out S.Tidyup.EmptyMaxSizeMB); + S.BulkAddCompareNoVideoFolders = this.cbIgnoreNoVideoFolders.Checked; + S.BulkAddIgnoreRecycleBin = this.cbIgnoreRecycleBin.Checked; + S.AutoAddIgnoreSuffixes = this.tbIgnoreSuffixes.Text; + S.AutoAddMovieTerms = this.tbMovieTerms.Text; + if (this.rbFolderFanArt.Checked) S.FolderJpgIs = TVSettings.FolderJpgIsType.FanArt; else if (this.rbFolderBanner.Checked) @@ -249,10 +254,7 @@ private void OKButton_Click(object sender, System.EventArgs e) break; } } - if (rbWTWScan.Checked) - S.WTWDoubleClick = TVSettings.WTWDoubleClickAction.Scan; - else - S.WTWDoubleClick = TVSettings.WTWDoubleClickAction.Search; + S.WTWDoubleClick = this.rbWTWScan.Checked ? TVSettings.WTWDoubleClickAction.Scan : TVSettings.WTWDoubleClickAction.Search; TheTVDB.Instance.SaveCache(); TheTVDB.Instance.Unlock("Preferences-OK"); @@ -431,7 +433,11 @@ private void Preferences_Load(object sender, System.EventArgs e) this.txtEmptyMaxSize.Text = S.Tidyup.EmptyMaxSizeMB.ToString(); this.txtSeasonFolderName.Text = S.defaultSeasonWord; - + + this.cbIgnoreRecycleBin.Checked = S.BulkAddIgnoreRecycleBin; + this.cbIgnoreNoVideoFolders.Checked = S.BulkAddCompareNoVideoFolders; + this.tbMovieTerms.Text = S.AutoAddMovieTerms; + this.tbIgnoreSuffixes.Text = S.AutoAddIgnoreSuffixes; switch (S.WTWDoubleClick) { @@ -525,11 +531,13 @@ private void Preferences_Load(object sender, System.EventArgs e) System.Collections.Generic.KeyValuePair showStatusColor in S.ShowStatusColors) { - ListViewItem item = new ListViewItem(); - item.Text = showStatusColor.Key.Text; - item.Tag = showStatusColor.Key; + ListViewItem item = new ListViewItem + { + Text = showStatusColor.Key.Text, + Tag = showStatusColor.Key, + ForeColor = showStatusColor.Value + }; item.SubItems.Add(TranslateColorToHtml(showStatusColor.Value)); - item.ForeColor = showStatusColor.Value; this.lvwDefinedColors.Items.Add(item); } } @@ -754,9 +762,8 @@ private void lbSearchFolders_DragOver(object sender, System.Windows.Forms.DragEv private void lbSearchFolders_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { string[] files = (string[]) (e.Data.GetData(DataFormats.FileDrop)); - for (int i = 0; i < files.Length; i++) + foreach (string path in files) { - string path = files[i]; try { DirectoryInfo di = new DirectoryInfo(path); diff --git a/TVRename#/Forms/UI.Designer.cs b/TVRename#/Forms/UI.Designer.cs index 7427c5095..bee9ce7b7 100644 --- a/TVRename#/Forms/UI.Designer.cs +++ b/TVRename#/Forms/UI.Designer.cs @@ -22,10 +22,16 @@ partial class UI /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { + this.mDoc = null; + if (disposing && (components != null)) { components.Dispose(); } + if (disposing && (this.mAutoFolderMonitor != null)) + { + mAutoFolderMonitor.Dispose(); + } base.Dispose(disposing); } diff --git a/TVRename#/Forms/UI.cs b/TVRename#/Forms/UI.cs index 965a82b6f..aa64638fb 100644 --- a/TVRename#/Forms/UI.cs +++ b/TVRename#/Forms/UI.cs @@ -250,12 +250,6 @@ public void ProcessArgs() this.Close(); } - ~UI() - { - // mDoc->StopBGDownloadThread(); TODO - this.mDoc = null; - } - public void UpdateSearchButton() { string name = this.mDoc.GetSearchers().Name(TVSettings.Instance.TheSearchers.CurrentSearchNum()); @@ -314,7 +308,7 @@ private void UI_Load(object sender, System.EventArgs e) filterButton.Click += filterButton_Click; filterTextBox.Controls.Add(filterButton); // Send EM_SETMARGINS to prevent text from disappearing underneath the button - SendMessage(filterTextBox.Handle, 0xd3, (IntPtr) 2, (IntPtr) (filterButton.Width << 16)); + NativeMethods.SendMessage(filterTextBox.Handle, 0xd3, (IntPtr) 2, (IntPtr) (filterButton.Width << 16)); this.betaToolsToolStripMenuItem.Visible = TVSettings.Instance.IncludeBetaUpdates(); @@ -338,10 +332,6 @@ private void UI_Load(object sender, System.EventArgs e) if (TVSettings.Instance.RunOnStartUp()){ RunAutoScan("Startup Scan"); } } - // MAH: Added in support of the Filter TextBox Button - [System.Runtime.InteropServices.DllImport("user32.dll")] - private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); - // MAH: Added in support of the Filter TextBox Button private void filterButton_Click(object sender, EventArgs e) { @@ -421,70 +411,71 @@ private bool LoadLayoutXML() if (!File.Exists(fn)) return true; - XmlReader reader = XmlReader.Create(fn, settings); + using (XmlReader reader = XmlReader.Create(fn, settings)) + { - reader.Read(); - if (reader.Name != "xml") - return false; + reader.Read(); + if (reader.Name != "xml") + return false; - reader.Read(); - if (reader.Name != "TVRename") - return false; + reader.Read(); + if (reader.Name != "TVRename") + return false; - if (reader.GetAttribute("Version") != "2.1") - return false; + if (reader.GetAttribute("Version") != "2.1") + return false; - reader.Read(); - if (reader.Name != "Layout") - return false; + reader.Read(); + if (reader.Name != "Layout") + return false; - reader.Read(); - while (reader.Name != "Layout") - { - if (reader.Name == "Window") + reader.Read(); + while (reader.Name != "Layout") { - reader.Read(); - while (reader.Name != "Window") + if (reader.Name == "Window") { - if (reader.Name == "Size") - { - int x = int.Parse(reader.GetAttribute("Width")); - int y = int.Parse(reader.GetAttribute("Height")); - this.Size = new System.Drawing.Size(x, y); - reader.Read(); - } - else if (reader.Name == "Location") + reader.Read(); + while (reader.Name != "Window") { - int x = int.Parse(reader.GetAttribute("X")); - int y = int.Parse(reader.GetAttribute("Y")); - this.Location = new Point(x, y); - reader.Read(); + if (reader.Name == "Size") + { + int x = int.Parse(reader.GetAttribute("Width")); + int y = int.Parse(reader.GetAttribute("Height")); + this.Size = new System.Drawing.Size(x, y); + reader.Read(); + } + else if (reader.Name == "Location") + { + int x = int.Parse(reader.GetAttribute("X")); + int y = int.Parse(reader.GetAttribute("Y")); + this.Location = new Point(x, y); + reader.Read(); + } + else if (reader.Name == "Maximized") + this.WindowState = (reader.ReadElementContentAsBoolean() + ? FormWindowState.Maximized + : FormWindowState.Normal); + else + reader.ReadOuterXml(); } - else if (reader.Name == "Maximized") - this.WindowState = (reader.ReadElementContentAsBoolean() - ? FormWindowState.Maximized - : FormWindowState.Normal); - else - reader.ReadOuterXml(); - } - reader.Read(); - } // window - else if (reader.Name == "ColumnWidths") - ok = this.LoadWidths(reader) && ok; - else if (reader.Name == "Splitter") - { - this.splitContainer1.SplitterDistance = int.Parse(reader.GetAttribute("Distance")); - this.splitContainer1.Panel2Collapsed = bool.Parse(reader.GetAttribute("HTMLCollapsed")); - if (this.splitContainer1.Panel2Collapsed) - this.bnHideHTMLPanel.ImageKey = "FillLeft.bmp"; - reader.Read(); - } - else - reader.ReadOuterXml(); - } // while + reader.Read(); + } // window + else if (reader.Name == "ColumnWidths") + ok = this.LoadWidths(reader) && ok; + else if (reader.Name == "Splitter") + { + this.splitContainer1.SplitterDistance = int.Parse(reader.GetAttribute("Distance")); + this.splitContainer1.Panel2Collapsed = bool.Parse(reader.GetAttribute("HTMLCollapsed")); + if (this.splitContainer1.Panel2Collapsed) + this.bnHideHTMLPanel.ImageKey = "FillLeft.bmp"; + reader.Read(); + } + else + reader.ReadOuterXml(); + } // while + } - reader.Close(); return ok; } @@ -533,8 +524,6 @@ private bool SaveLayoutXML() writer.WriteEndElement(); // Layout writer.WriteEndElement(); // tvrename writer.WriteEndDocument(); - - writer.Close(); } return true; @@ -865,11 +854,7 @@ private string GetSeasonImagesHTMLOverview(ShowItem si, SeriesInfo ser, int snum private string GetShowImagesHTMLOverview(ShowItem si, SeriesInfo ser) { - string body = ""; - - body += "

" + si.ShowName + - " " + "

"; - + string body =$"

{si.ShowName}

"; body += ImageSection("Show Banner", 758, 140, ser.GetSeriesWideBannerPath()); body += ImageSection("Show Poster", 350, 500, ser.GetSeriesPosterPath()); body += ImageSection("Show Fanart", 960, 540, ser.GetSeriesFanartPath()); @@ -879,23 +864,21 @@ private string GetShowImagesHTMLOverview(ShowItem si, SeriesInfo ser) private static string ImageSection(string title, int width, int height, string bannerPath) { - string body = ""; + + if (string.IsNullOrEmpty(bannerPath)) return ""; - if ((!string.IsNullOrEmpty(bannerPath)) && (!string.IsNullOrEmpty(TheTVDB.Instance.WebsiteRoot))) - { - body += "

" + title + "

"; - body += "
"; - } + string url = TheTVDB.GetBannerURL(bannerPath); - return body; + if ((string.IsNullOrEmpty(url))) return ""; + + return $"

{title}


"; } private string GetShowHTMLOverview(ShowItem si, SeriesInfo ser) { string body = ""; - List skip = new List + List skip = new List { "Actors", "banner", @@ -917,27 +900,23 @@ private string GetShowHTMLOverview(ShowItem si, SeriesInfo ser) if ((!string.IsNullOrEmpty(ser.GetSeriesWideBannerPath())) && - (!string.IsNullOrEmpty(TheTVDB.Instance.WebsiteRoot))) - body += "
"; + (!string.IsNullOrEmpty(TheTVDB.GetBannerURL(ser.GetSeriesWideBannerPath()) ))) + body += "
"; - body += "

" + si.ShowName + - " " + "

"; + body += $"

{si.ShowName}

"; body += "

Overview

" + ser.GetOverview(); //get overview in either format bool first = true; foreach (string aa in ser.GetActors()) { - if (!string.IsNullOrEmpty(aa)) - { - if (!first) - body += ", "; - else - body += "

Actors

"; - body += "" + aa + ""; - first = false; - } + if (string.IsNullOrEmpty(aa)) continue; + if (!first) + body += ", "; + else + body += "

Actors

"; + body += "" + aa + ""; + first = false; } string airsTime = ser.getAirsTime(); @@ -989,9 +968,8 @@ private string GetSeasonHTMLOverview(ShowItem si, SeriesInfo ser, int snum) string body = ""; if (!string.IsNullOrEmpty(ser.GetSeriesWideBannerPath()) && - !string.IsNullOrEmpty(TheTVDB.Instance.WebsiteRoot)) - body += "
"; + !string.IsNullOrEmpty(TheTVDB.GetBannerURL(ser.GetSeriesWideBannerPath()))) + body += "
"; Season s = si.DVDOrder ? ser.DVDSeasons[snum]: ser.AiredSeasons[snum]; @@ -1056,8 +1034,7 @@ private string GetSeasonHTMLOverview(ShowItem si, SeriesInfo ser, int snum) body += "" + getOverview(ei) + ""; // 300x168 / 300x225 if (!string.IsNullOrEmpty(ei.GetFilename())) - body += ""; + body += ""; body += ""; } else @@ -1131,11 +1108,14 @@ public static void SetHTMLbody(string body, string path, WebBrowser web) web.Navigate("about:blank"); // make it close any file it might have open try { - BinaryWriter bw = new BinaryWriter(new FileStream(path, System.IO.FileMode.Create)); - bw.Write(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(html)); + using (FileStream fs = new FileStream(path, System.IO.FileMode.Create)) + { + BinaryWriter bw = new BinaryWriter(fs); - bw.Close(); - web.Navigate(LocalFileURLBase(path)); + bw.Write(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(html)); + } + + web.Navigate(LocalFileURLBase(path)); } catch (Exception ex) { @@ -3052,7 +3032,6 @@ private void GetNewShows(bool unattended) } List addedShows = new List(); - foreach (string hint in possibleShowNames) { //MessageBox.Show($"Search for {hint}"); @@ -3062,6 +3041,15 @@ private void GetNewShows(bool unattended) //If the hint contains certain terms then we'll ignore it if (IgnoreHint(hint)) continue; + //If there are no LibraryFolders then we cant use the simplified UI + if (TVSettings.Instance.LibraryFoldersNames.Count == 0) + { + MessageBox.Show( + "Please add some monitor (library) folders under 'Bulk Add Shows'to use the 'Auto Add' functionity (Alternatively you can turn it off in settings).", + "Can't Auto Add Show", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + //Remove anything we can from hint to make it cleaner and hence more likely to match string refinedHint = RemoveSeriesEpisodeIndicators(hint); @@ -3102,14 +3090,12 @@ private void GetNewShows(bool unattended) private static bool IgnoreHint(string hint) { - string[] removeHintsContaining = { "dvdrip", "camrip", "screener", "dvdscr", "r5", "bluray" }; - - return removeHintsContaining.Any(hint.ToLower().Contains); + return TVSettings.Instance.AutoAddMovieTermsArray.Any(term => hint.Contains(term,StringComparison.OrdinalIgnoreCase)); } private string RemoveSeriesEpisodeIndicators(string hint) { - string[] removeAfterTerms = {"1080p","720p"}; + string hint2 = Helpers.RemoveDiacritics(hint); hint2 = RemoveSE(hint2); @@ -3117,7 +3103,7 @@ private string RemoveSeriesEpisodeIndicators(string hint) hint2 = hint2.Replace("'", ""); hint2 = hint2.Replace("&", "and"); hint2 = Regex.Replace(hint2, "[_\\W]+", " "); - foreach (string term in removeAfterTerms) + foreach (string term in TVSettings.Instance.AutoAddIgnoreSuffixesArray) { hint2 = hint2.RemoveAfter(term); } @@ -3949,7 +3935,7 @@ private void filterTextBox_SizeChanged(object sender, EventArgs e) filterButton.Location = new Point(filterTextBox.ClientSize.Width - filterButton.Width, (filterTextBox.ClientSize.Height - 16) / 2 + 1); // Send EM_SETMARGINS to prevent text from disappearing underneath the button - SendMessage(filterTextBox.Handle, 0xd3, (IntPtr) 2, (IntPtr) (filterButton.Width << 16)); + NativeMethods.SendMessage(filterTextBox.Handle, 0xd3, (IntPtr) 2, (IntPtr) (filterButton.Width << 16)); } } diff --git a/TVRename#/Forms/UpdateNotification.cs b/TVRename#/Forms/UpdateNotification.cs index 92dd14385..676947581 100644 --- a/TVRename#/Forms/UpdateNotification.cs +++ b/TVRename#/Forms/UpdateNotification.cs @@ -38,11 +38,12 @@ private void UpdateWithMarkdown() request.Add("text", this.newVersion.ReleaseNotesText); request.Add("mode", "gfm"); request.Add("context", "TV-Rename/tvrename"); - - StreamWriter writer = new StreamWriter(req.GetRequestStream()); - writer.Write(request.ToString()); - writer.Close(); + using (StreamWriter writer = new StreamWriter(req.GetRequestStream())) + { + writer.Write(request.ToString()); + } + string result = null; using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { diff --git a/TVRename#/ItemsAndActions/ActionDelete.cs b/TVRename#/ItemsAndActions/ActionDelete.cs index 9eeb99638..934c4c8d2 100644 --- a/TVRename#/ItemsAndActions/ActionDelete.cs +++ b/TVRename#/ItemsAndActions/ActionDelete.cs @@ -145,7 +145,7 @@ public override bool Go(ref bool pause, TVRenameStats stats) { //if the directory is the root download folder do not delete if (TVSettings.Instance.MonitorFolders && - TVSettings.Instance.SearchFoldersNames.Contains(this.toRemove.FullName)) + TVSettings.Instance.DownloadFoldersNames.Contains(this.toRemove.FullName)) { this.Error = true; this.ErrorText = $@"Not removing {this.toRemove.FullName} as it is a Search Folder"; diff --git a/TVRename#/ItemsAndActions/ActionItem.cs b/TVRename#/ItemsAndActions/ActionItem.cs index 141a1174a..6e560626e 100644 --- a/TVRename#/ItemsAndActions/ActionItem.cs +++ b/TVRename#/ItemsAndActions/ActionItem.cs @@ -129,11 +129,11 @@ protected void DoTidyup(DirectoryInfo di) return; //if the directory is the root download folder do not delete - if (TVSettings.Instance.SearchFoldersNames.Contains(di.FullName)) + if (TVSettings.Instance.DownloadFoldersNames.Contains(di.FullName)) return; // Do not delete any monitor folders either - if (TVSettings.Instance.MonitorFoldersNames.Contains(di.FullName)) + if (TVSettings.Instance.LibraryFoldersNames.Contains(di.FullName)) return; diff --git a/TVRename#/ItemsAndActions/ActionMede8erViewXML.cs b/TVRename#/ItemsAndActions/ActionMede8erViewXML.cs index 55e14a9ae..c896f6cf6 100644 --- a/TVRename#/ItemsAndActions/ActionMede8erViewXML.cs +++ b/TVRename#/ItemsAndActions/ActionMede8erViewXML.cs @@ -5,6 +5,9 @@ // // This code is released under GPLv3 https://github.com/TV-Rename/tvrename/blob/master/LICENSE.md // + +using System.Linq.Expressions; + namespace TVRename { using System; @@ -43,33 +46,38 @@ public override bool Go(ref bool pause, TVRenameStats stats) Indent = true, NewLineOnAttributes = true }; - // "try" and silently fail. eg. when file is use by other... - XmlWriter writer; try { - writer = XmlWriter.Create(this.Where.FullName, settings); + using (XmlWriter writer = XmlWriter.Create(this.Where.FullName, settings)) + { + + writer.WriteStartElement("FolderTag"); + // is it a show or season folder + if (this.Snum >= 0) + { + // if episode thumbnails are generated, use ViewMode Photo, otherwise use List + XMLHelper.WriteElementToXML(writer, "ViewMode", TVSettings.Instance.EpJPGs ? "Photo" : "List"); + XMLHelper.WriteElementToXML(writer, "ViewType", "Video"); + } + else + { + XMLHelper.WriteElementToXML(writer, "ViewMode", "Preview"); + } + + writer.WriteEndElement(); + + } } - catch (Exception) + + catch (Exception e) { + this.Error = true; + this.ErrorText = e.Message; this.Done = true; - return true; - } + return false; - writer.WriteStartElement("FolderTag"); - // is it a show or season folder - if (this.Snum >= 0) - { - // if episode thumbnails are generated, use ViewMode Photo, otherwise use List - XMLHelper.WriteElementToXML(writer, "ViewMode", TVSettings.Instance.EpJPGs ? "Photo" : "List"); - XMLHelper.WriteElementToXML(writer, "ViewType", "Video"); - } - else - { - XMLHelper.WriteElementToXML(writer, "ViewMode", "Preview"); } - writer.WriteEndElement(); - writer.Close(); this.Done = true; return true; } diff --git a/TVRename#/ItemsAndActions/ActionMede8erXML.cs b/TVRename#/ItemsAndActions/ActionMede8erXML.cs index 3e273c5ea..113caa9d1 100644 --- a/TVRename#/ItemsAndActions/ActionMede8erXML.cs +++ b/TVRename#/ItemsAndActions/ActionMede8erXML.cs @@ -38,188 +38,207 @@ public ActionMede8erXML(FileInfo nfo, ShowItem si) public override bool Go(ref bool pause, TVRenameStats stats) { - XmlWriterSettings settings = new XmlWriterSettings - { - Indent = true, - NewLineOnAttributes = true - }; - // "try" and silently fail. eg. when file is use by other... - XmlWriter writer; try { - writer = XmlWriter.Create(this.Where.FullName, settings); - } - catch (Exception) - { - this.Done = true; - return true; - } - - - if (this.Episode != null) // specific episode - { - // See: http://xbmc.org/wiki/?title=Import_-_Export_Library#TV_Episodes - writer.WriteStartElement("details"); - writer.WriteStartElement("movie"); - XMLHelper.WriteElementToXML(writer,"title",this.Episode.Name); - XMLHelper.WriteElementToXML(writer,"season",this.Episode.AppropriateSeasonNumber); - XMLHelper.WriteElementToXML(writer,"episode",this.Episode.AppropriateEpNum); - - writer.WriteStartElement("year"); - if (this.Episode.FirstAired != null) - writer.WriteValue(this.Episode.FirstAired.Value.ToString("yyyy")); - writer.WriteEndElement(); - - writer.WriteStartElement("rating"); - string rating = (this.Episode.EpisodeRating); - if (!string.IsNullOrEmpty(rating)) + XmlWriterSettings settings = new XmlWriterSettings { - rating = rating.Trim('.'); - rating = rating.Replace(".", ""); - writer.WriteValue(rating); - } - writer.WriteEndElement(); // rating + Indent = true, + NewLineOnAttributes = true + }; - //Get the Series OverView - string sov = this.Episode.SI.TheSeries().GetOverview(); - if (!string.IsNullOrEmpty(sov)) + using (XmlWriter writer = XmlWriter.Create(this.Where.FullName, settings)) { - XMLHelper.WriteElementToXML(writer,"plot",sov); - } - //Get the Episode overview - XMLHelper.WriteElementToXML(writer,"episodeplot",this.Episode.Overview); - - if (this.Episode.SI != null) + + if (this.Episode != null) // specific episode { - WriteInfo(writer, this.Episode.SI.TheSeries().GetRating(), "mpaa"); - } + // See: http://xbmc.org/wiki/?title=Import_-_Export_Library#TV_Episodes + writer.WriteStartElement("details"); + writer.WriteStartElement("movie"); + XMLHelper.WriteElementToXML(writer, "title", this.Episode.Name); + XMLHelper.WriteElementToXML(writer, "season", this.Episode.AppropriateSeasonNumber); + XMLHelper.WriteElementToXML(writer, "episode", this.Episode.AppropriateEpNum); + + writer.WriteStartElement("year"); + if (this.Episode.FirstAired != null) + writer.WriteValue(this.Episode.FirstAired.Value.ToString("yyyy")); + writer.WriteEndElement(); + + //Mede8er Ratings are on a 100 point scale; TVDB are on a 10 point scale + float siteRating = float.Parse(this.Episode.EpisodeRating) * 10; + int intSiteRating = (int)siteRating; + if (intSiteRating > 0) XMLHelper.WriteElementToXML(writer, "rating", intSiteRating); + +// writer.WriteStartElement("rating"); +// string rating = (this.Episode.EpisodeRating); +// if (!string.IsNullOrEmpty(rating)) +// { +// rating = rating.Trim('.'); +// rating = rating.Replace(".", ""); +// writer.WriteValue(rating); +// } +// +// writer.WriteEndElement(); // rating + + //Get the Series OverView + string sov = this.Episode.SI.TheSeries().GetOverview(); + if (!string.IsNullOrEmpty(sov)) + { + XMLHelper.WriteElementToXML(writer, "plot", sov); + } - //Runtime...taken from overall Series, not episode specific due to thetvdb - string rt = this.Episode.SI.TheSeries().GetRuntime(); - if (!string.IsNullOrEmpty(rt)) - { - XMLHelper.WriteElementToXML(writer,"runtime",rt + " min"); - } + //Get the Episode overview + XMLHelper.WriteElementToXML(writer, "episodeplot", this.Episode.Overview); - //Genres...taken from overall Series, not episode specific due to thetvdb - writer.WriteStartElement("genres"); - string genre = String.Join(" / ", this.Episode.SI.TheSeries().GetGenres()); - if (!string.IsNullOrEmpty(genre)) - { - XMLHelper.WriteElementToXML(writer,"genre",genre); - } - writer.WriteEndElement(); // genres + if (this.Episode.SI != null) + { + WriteInfo(writer, this.Episode.SI.TheSeries().GetContentRating(), "mpaa"); + } - //Director(s) - if (!string.IsNullOrEmpty(this.Episode.EpisodeDirector)) - { - string epDirector = this.Episode.EpisodeDirector; - if (!string.IsNullOrEmpty(epDirector)) + //Runtime...taken from overall Series, not episode specific due to thetvdb + string rt = this.Episode.SI.TheSeries().GetRuntime(); + if (!string.IsNullOrEmpty(rt)) + { + XMLHelper.WriteElementToXML(writer, "runtime", rt + " min"); + } + + //Genres...taken from overall Series, not episode specific due to thetvdb + writer.WriteStartElement("genres"); + string genre = String.Join(" / ", this.Episode.SI.TheSeries().GetGenres()); + if (!string.IsNullOrEmpty(genre)) { - foreach (string daa in epDirector.Split('|')) + XMLHelper.WriteElementToXML(writer, "genre", genre); + } + + writer.WriteEndElement(); // genres + + //Director(s) + if (!string.IsNullOrEmpty(this.Episode.EpisodeDirector)) + { + string epDirector = this.Episode.EpisodeDirector; + if (!string.IsNullOrEmpty(epDirector)) { - if (string.IsNullOrEmpty(daa)) - continue; + foreach (string daa in epDirector.Split('|')) + { + if (string.IsNullOrEmpty(daa)) + continue; - XMLHelper.WriteElementToXML(writer,"director",daa); + XMLHelper.WriteElementToXML(writer, "director", daa); + } } } - } - //Writers(s) - if (!String.IsNullOrEmpty(this.Episode.Writer)) - { - string epWriter = this.Episode.Writer; - if (!string.IsNullOrEmpty(epWriter)) + //Writers(s) + if (!String.IsNullOrEmpty(this.Episode.Writer)) { - XMLHelper.WriteElementToXML(writer,"credits",epWriter); + string epWriter = this.Episode.Writer; + if (!string.IsNullOrEmpty(epWriter)) + { + XMLHelper.WriteElementToXML(writer, "credits", epWriter); + } } - } - - writer.WriteStartElement("cast"); - // actors... - if (this.Episode.SI != null) - { + writer.WriteStartElement("cast"); + + // actors... + if (this.Episode.SI != null) + { foreach (string aa in this.Episode.SI.TheSeries().GetActors()) { if (string.IsNullOrEmpty(aa)) continue; - XMLHelper.WriteElementToXML(writer,"actor",aa); + XMLHelper.WriteElementToXML(writer, "actor", aa); } + } + + writer.WriteEndElement(); // cast + writer.WriteEndElement(); // movie + writer.WriteEndElement(); // details } + else if (this.SI != null) // show overview (Series.xml) + { + // http://www.xbmc.org/wiki/?title=Import_-_Export_Library#TV_Shows - writer.WriteEndElement(); // cast - writer.WriteEndElement(); // movie - writer.WriteEndElement(); // details - } - else if (this.SI != null) // show overview (Series.xml) - { - // http://www.xbmc.org/wiki/?title=Import_-_Export_Library#TV_Shows + writer.WriteStartElement("details"); + writer.WriteStartElement("movie"); - writer.WriteStartElement("details"); - writer.WriteStartElement("movie"); + XMLHelper.WriteElementToXML(writer, "title", this.SI.ShowName); - XMLHelper.WriteElementToXML(writer,"title",this.SI.ShowName); - - writer.WriteStartElement("genres"); - string genre = String.Join(" / ", this.SI.TheSeries().GetGenres()); - if (!string.IsNullOrEmpty(genre)) - { - XMLHelper.WriteElementToXML(writer,"genre",genre); - } - writer.WriteEndElement(); // genres + writer.WriteStartElement("genres"); + string genre = String.Join(" / ", this.SI.TheSeries().GetGenres()); + if (!string.IsNullOrEmpty(genre)) + { + XMLHelper.WriteElementToXML(writer, "genre", genre); + } - WriteInfo(writer, this.SI.TheSeries().GetFirstAired(), "premiered"); - WriteInfo(writer, this.SI.TheSeries().GetYear(), "year"); + writer.WriteEndElement(); // genres - writer.WriteStartElement("rating"); - string rating = this.SI.TheSeries().GetRating(); - if (!string.IsNullOrEmpty(rating)) - { - rating = rating.Trim('.'); - rating = rating.Replace(".", ""); - writer.WriteValue(rating); - } - writer.WriteEndElement(); // rating + WriteInfo(writer, this.SI.TheSeries().GetFirstAired(), "premiered"); + WriteInfo(writer, this.SI.TheSeries().GetYear(), "year"); - WriteInfo(writer, this.SI.TheSeries().getStatus(), "status"); - WriteInfo(writer, this.SI.TheSeries().GetRating(), "mpaa"); - WriteInfo(writer, this.SI.TheSeries().GetIMDB(), "id", "moviedb", "imdb"); + //Mede8er Ratings are on a 100 point scale; TVDB are on a 10 point scale + float siteRating = float.Parse(this.SI.TheSeries().GetSiteRating()) * 10; + int intSiteRating = (int)siteRating; + if (intSiteRating > 0) XMLHelper.WriteElementToXML(writer, "rating", intSiteRating); - XMLHelper.WriteElementToXML(writer,"tvdbid",this.SI.TheSeries().TVDBCode); + /* + writer.WriteStartElement("rating"); + string rating = this.SI.TheSeries().GetSiteRating(); + if (!string.IsNullOrEmpty(rating)) + { + rating = rating.Trim('.'); + rating = rating.Replace(".", ""); + writer.WriteValue(rating); + } - string rt = this.SI.TheSeries().GetRuntime(); - if (!string.IsNullOrEmpty(rt)) - { - XMLHelper.WriteElementToXML(writer,"runtime",rt + " min"); - } + writer.WriteEndElement(); // rating + */ - WriteInfo(writer, this.SI.TheSeries().GetOverview(), "plot"); - - writer.WriteStartElement("cast"); + WriteInfo(writer, this.SI.TheSeries().getStatus(), "status"); - // actors... - - foreach (string aa in this.SI.TheSeries().GetActors()) - { - if (string.IsNullOrEmpty(aa)) - continue; - XMLHelper.WriteElementToXML(writer,"actor",aa); + WriteInfo(writer, this.SI.TheSeries().GetContentRating(), "mpaa"); + WriteInfo(writer, this.SI.TheSeries().GetIMDB(), "id", "moviedb", "imdb"); + + XMLHelper.WriteElementToXML(writer, "tvdbid", this.SI.TheSeries().TVDBCode); + + string rt = this.SI.TheSeries().GetRuntime(); + if (!string.IsNullOrEmpty(rt)) + { + XMLHelper.WriteElementToXML(writer, "runtime", rt + " min"); + } + + WriteInfo(writer, this.SI.TheSeries().GetOverview(), "plot"); + + writer.WriteStartElement("cast"); + + // actors... + + foreach (string aa in this.SI.TheSeries().GetActors()) + { + if (string.IsNullOrEmpty(aa)) + continue; + XMLHelper.WriteElementToXML(writer, "actor", aa); + } + + writer.WriteEndElement(); // cast + writer.WriteEndElement(); // movie + writer.WriteEndElement(); // tvshow } - - writer.WriteEndElement(); // cast - writer.WriteEndElement(); // movie - writer.WriteEndElement(); // tvshow - } - writer.Close(); - this.Done = true; - return true; + this.Done = true; + return true; + } + } + catch (Exception e) + { + this.ErrorText = e.Message; + this.Error = true; + this.Done = true; + return false; + } } #endregion diff --git a/TVRename#/ItemsAndActions/ActionNFO.cs b/TVRename#/ItemsAndActions/ActionNFO.cs index 2c2fb0281..5df774bd2 100644 --- a/TVRename#/ItemsAndActions/ActionNFO.cs +++ b/TVRename#/ItemsAndActions/ActionNFO.cs @@ -61,7 +61,7 @@ private void WriteEpisodeDetailsFor(Episode episode, XmlWriter writer,bool multi writer.WriteValue(episode.FirstAired.Value.ToString("yyyy-MM-dd")); writer.WriteEndElement(); - XMLHelper.WriteElementToXML(writer, "mpaa", this.Episode.SI?.TheSeries()?.GetRating(),true); + XMLHelper.WriteElementToXML(writer, "mpaa", this.Episode.SI?.TheSeries()?.GetContentRating(),true); //Director(s) string epDirector = episode.EpisodeDirector; @@ -164,85 +164,77 @@ public override bool Go(ref bool pause, TVRenameStats stats) //Multipart NFO files are not actually valid XML as they have multiple episodeDetails elements ConformanceLevel = ConformanceLevel.Fragment }; - // "try" and silently fail. eg. when file is use by other... - XmlWriter writer; try { - // XmlWriter writer = XmlWriter.Create(this.Where.FullName, settings); - writer = XmlWriter.Create(this.Where.FullName, settings); - } - catch (Exception) - { - this.Done = true; - return true; - } - - if (this.Episode != null) // specific episode - { - if (this.Episode.type == ProcessedEpisode.ProcessedEpisodeType.merged) + // "try" and silently fail. eg. when file is use by other... + using (XmlWriter writer = XmlWriter.Create(this.Where.FullName, settings)) { - foreach (Episode ep in this.Episode.sourceEpisodes) WriteEpisodeDetailsFor(ep, writer, true, this.Episode.SI.DVDOrder); - } - else WriteEpisodeDetailsFor(this.Episode, writer, false, this.Episode.SI.DVDOrder); - } - else if (this.SI != null) // show overview (tvshow.nfo) - { - // http://www.xbmc.org/wiki/?title=Import_-_Export_Library#TV_Shows + if (this.Episode != null) // specific episode + { + if (this.Episode.type == ProcessedEpisode.ProcessedEpisodeType.merged) + { + foreach (Episode ep in this.Episode.sourceEpisodes) + WriteEpisodeDetailsFor(ep, writer, true, this.Episode.SI.DVDOrder); + } + else WriteEpisodeDetailsFor(this.Episode, writer, false, this.Episode.SI.DVDOrder); + } + else if (this.SI != null) // show overview (tvshow.nfo) + { + // http://www.xbmc.org/wiki/?title=Import_-_Export_Library#TV_Shows - writer.WriteStartElement("tvshow"); + writer.WriteStartElement("tvshow"); - XMLHelper.WriteElementToXML(writer,"title",this.SI.ShowName); + XMLHelper.WriteElementToXML(writer, "title", this.SI.ShowName); - XMLHelper.WriteElementToXML(writer, "episodeguideurl", TheTVDB.BuildURL(true, true, this.SI.TVDBCode, TheTVDB.Instance.RequestLanguage)); + XMLHelper.WriteElementToXML(writer, "episodeguideurl", + TheTVDB.BuildURL(true, true, this.SI.TVDBCode, TheTVDB.Instance.RequestLanguage)); - XMLHelper.WriteElementToXML(writer, "plot", this.SI.TheSeries().GetOverview()); + XMLHelper.WriteElementToXML(writer, "plot", this.SI.TheSeries().GetOverview()); - string genre = String.Join(" / ", this.SI.TheSeries().GetGenres()); - if (!string.IsNullOrEmpty(genre)) - { - XMLHelper.WriteElementToXML(writer,"genre",genre); - } + string genre = String.Join(" / ", this.SI.TheSeries().GetGenres()); + if (!string.IsNullOrEmpty(genre)) + { + XMLHelper.WriteElementToXML(writer, "genre", genre); + } - XMLHelper.WriteElementToXML(writer, "premiered", this.SI.TheSeries().GetFirstAired()); - XMLHelper.WriteElementToXML(writer, "year", this.SI.TheSeries().GetYear()); - XMLHelper.WriteElementToXML(writer, "rating", this.SI.TheSeries().GetRating()); - XMLHelper.WriteElementToXML(writer, "status", this.SI.TheSeries().getStatus()); + XMLHelper.WriteElementToXML(writer, "premiered", this.SI.TheSeries().GetFirstAired()); + XMLHelper.WriteElementToXML(writer, "year", this.SI.TheSeries().GetYear()); + XMLHelper.WriteElementToXML(writer, "rating", this.SI.TheSeries().GetContentRating()); + XMLHelper.WriteElementToXML(writer, "status", this.SI.TheSeries().getStatus()); - // actors... - foreach (string aa in this.SI.TheSeries().GetActors() ) - { - if (string.IsNullOrEmpty(aa)) - continue; + // actors... + foreach (string aa in this.SI.TheSeries().GetActors()) + { + if (string.IsNullOrEmpty(aa)) + continue; - writer.WriteStartElement("actor"); - XMLHelper.WriteElementToXML(writer,"name",aa); - writer.WriteEndElement(); // actor - } + writer.WriteStartElement("actor"); + XMLHelper.WriteElementToXML(writer, "name", aa); + writer.WriteEndElement(); // actor + } - XMLHelper.WriteElementToXML(writer, "mpaa", this.SI.TheSeries().GetRating()); - XMLHelper.WriteInfo(writer, "id", "moviedb","imdb", this.SI.TheSeries().GetIMDB()); + XMLHelper.WriteElementToXML(writer, "mpaa", this.SI.TheSeries().GetContentRating()); + XMLHelper.WriteInfo(writer, "id", "moviedb", "imdb", this.SI.TheSeries().GetIMDB()); - XMLHelper.WriteElementToXML(writer,"tvdbid",this.SI.TheSeries().TVDBCode); + XMLHelper.WriteElementToXML(writer, "tvdbid", this.SI.TheSeries().TVDBCode); - string rt = this.SI.TheSeries().GetRuntime(); - if (!string.IsNullOrEmpty(rt)) - { - XMLHelper.WriteElementToXML(writer,"runtime",rt + " minutes"); - } + string rt = this.SI.TheSeries().GetRuntime(); + if (!string.IsNullOrEmpty(rt)) + { + XMLHelper.WriteElementToXML(writer, "runtime", rt + " minutes"); + } - writer.WriteEndElement(); // tvshow + writer.WriteEndElement(); // tvshow + } + } } - try - { - writer.Close(); - } catch (Exception e) { this.ErrorText = e.Message; this.Error = true; this.Done = true; - return false; + return false; } this.Done = true; diff --git a/TVRename#/ItemsAndActions/ActionPyTivoMeta.cs b/TVRename#/ItemsAndActions/ActionPyTivoMeta.cs index 0c65fae56..a127929ec 100644 --- a/TVRename#/ItemsAndActions/ActionPyTivoMeta.cs +++ b/TVRename#/ItemsAndActions/ActionPyTivoMeta.cs @@ -27,46 +27,53 @@ public ActionPyTivoMeta(FileInfo nfo, ProcessedEpisode pe) public override string Name => "Write pyTivo Meta"; - public override bool Go( ref bool pause, TVRenameStats stats) + public override bool Go(ref bool pause, TVRenameStats stats) { - // "try" and silently fail. eg. when file is use by other... - StreamWriter writer; try { // create folder if it does not exist. (Only really applies when .meta\ folder is being used.) if (!this.Where.Directory.Exists) Directory.CreateDirectory(this.Where.Directory.FullName); - writer = new StreamWriter(this.Where.FullName, false, System.Text.Encoding.GetEncoding(1252)); + + using ( + StreamWriter writer = new StreamWriter(this.Where.FullName, false, + System.Text.Encoding.GetEncoding(1252))) + { + + + // See: http://pytivo.sourceforge.net/wiki/index.php/Metadata + writer.WriteLine($"title : {this.Episode.SI.ShowName}"); + writer.WriteLine($"seriesTitle : {this.Episode.SI.ShowName}"); + writer.WriteLine($"episodeTitle : {this.Episode.Name}"); + writer.WriteLine( + $"episodeNumber : {this.Episode.AppropriateSeasonNumber}{this.Episode.AppropriateEpNum:0#}"); + writer.WriteLine("isEpisode : true"); + writer.WriteLine($"description : {this.Episode.Overview}"); + if (this.Episode.FirstAired != null) + writer.WriteLine($"originalAirDate : {this.Episode.FirstAired.Value:yyyy-MM-dd}T00:00:00Z"); + writer.WriteLine($"callsign : {this.Episode.SI.TheSeries().getNetwork()}"); + + WriteEntries(writer, "vDirector", this.Episode.EpisodeDirector); + WriteEntries(writer, "vWriter", this.Episode.Writer); + WriteEntries(writer, "vActor", string.Join("|", this.Episode.SI.TheSeries().GetActors())); + WriteEntries(writer, "vGuestStar", + this.Episode.EpisodeGuestStars); // not worring about actors being repeated + WriteEntries(writer, "vProgramGenre", string.Join("|", this.Episode.SI.TheSeries().GetGenres())); + + } + + this.Done = true; + return true; } - catch (Exception) + catch (Exception e) { + this.ErrorText = e.Message; + this.Error = true; this.Done = true; - return true; + return false; } - - // See: http://pytivo.sourceforge.net/wiki/index.php/Metadata - writer.WriteLine($"title : {this.Episode.SI.ShowName}"); - writer.WriteLine($"seriesTitle : {this.Episode.SI.ShowName}"); - writer.WriteLine($"episodeTitle : {this.Episode.Name}"); - writer.WriteLine( - $"episodeNumber : {this.Episode.AppropriateSeasonNumber}{this.Episode.AppropriateEpNum:0#}"); - writer.WriteLine("isEpisode : true"); - writer.WriteLine($"description : {this.Episode.Overview}"); - if (this.Episode.FirstAired != null) - writer.WriteLine($"originalAirDate : {this.Episode.FirstAired.Value:yyyy-MM-dd}T00:00:00Z"); - writer.WriteLine($"callsign : {this.Episode.SI.TheSeries().getNetwork()}"); - - WriteEntries(writer, "vDirector", this.Episode.EpisodeDirector); - WriteEntries(writer, "vWriter", this.Episode.Writer); - WriteEntries(writer, "vActor", String.Join("|", this.Episode.SI.TheSeries().GetActors())); - WriteEntries(writer, "vGuestStar", this.Episode.EpisodeGuestStars); // not worring about actors being repeated - WriteEntries(writer, "vProgramGenre", String.Join("|", this.Episode.SI.TheSeries().GetGenres())); - - writer.Close(); - this.Done = true; - return true; } - + private static void WriteEntries(TextWriter writer, string heading, string entries) { if (string.IsNullOrEmpty(entries)) diff --git a/TVRename#/Settings/Settings.cs b/TVRename#/Settings/Settings.cs index b5a728c20..26d9bb018 100644 --- a/TVRename#/Settings/Settings.cs +++ b/TVRename#/Settings/Settings.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using Alphaleonis.Win32.Filesystem; using System.Text.RegularExpressions; using System.Xml; @@ -28,14 +29,8 @@ public class TidySettings public bool EmptyMaxSizeCheck = true; public int EmptyMaxSizeMB = 100; - public string[] EmptyIgnoreExtensionsArray - { - get { return EmptyIgnoreExtensionList.Split(';'); } - } - public string[] EmptyIgnoreWordsArray - { - get { return EmptyIgnoreWordList.Split(';'); } - } + public string[] EmptyIgnoreExtensionsArray => EmptyIgnoreExtensionList.Split(';'); + public string[] EmptyIgnoreWordsArray => EmptyIgnoreWordList.Split(';'); } public class Replacement @@ -74,8 +69,16 @@ public FilenameProcessorRE(bool enabled, string re, bool useFullPath, string not } } + [Serializable()] public class ShowStatusColoringTypeList : Dictionary { + public ShowStatusColoringTypeList() + { + } + protected ShowStatusColoringTypeList(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + public bool IsShowStatusDefined(string showStatus) { foreach (KeyValuePair e in this) @@ -122,11 +125,11 @@ public string Text { if (IsShowLevel && IsMetaType) { - return string.Format("Show Seasons Status: {0}", StatusTextForDisplay); + return $"Show Seasons Status: {this.StatusTextForDisplay}"; } if (!IsShowLevel && IsMetaType) { - return string.Format("Season Status: {0}", StatusTextForDisplay); + return $"Season Status: {this.StatusTextForDisplay}"; } if (IsShowLevel && !IsMetaType) { @@ -264,9 +267,9 @@ public enum KeepTogetherModes } - public List MonitorFoldersNames = new List(); + public List LibraryFoldersNames = new List(); public List IgnoreFoldersNames = new List(); - public List SearchFoldersNames = new List(); + public List DownloadFoldersNames = new List(); public bool AutoSelectShowInMyShows = true; @@ -321,20 +324,23 @@ public enum KeepTogetherModes public BetaMode mode = BetaMode.ProductionOnly; public float upgradeDirtyPercent = 20; public KeepTogetherModes keepTogetherMode = KeepTogetherModes.All; - - public string[] keepTogetherExtensionsArray - { - get { return keepTogetherExtensionsString.Split(';'); } - } + public bool BulkAddIgnoreRecycleBin = false; + public bool BulkAddCompareNoVideoFolders = false; + public string AutoAddMovieTerms = "dvdrip;camrip;screener;dvdscr;r5;bluray"; + public string AutoAddIgnoreSuffixes = "1080p;720p"; + + public string[] AutoAddMovieTermsArray => AutoAddMovieTerms.Split(';'); + + public string[] AutoAddIgnoreSuffixesArray => AutoAddIgnoreSuffixes.Split(';'); + + public string[] keepTogetherExtensionsArray => keepTogetherExtensionsString.Split(';'); public string keepTogetherExtensionsString = ""; public string defaultSeasonWord = "Season"; - public string[] searchSeasonWordsArray - { - get { return searchSeasonWordsString.Split(';'); } - } + public string[] searchSeasonWordsArray => searchSeasonWordsString.Split(';'); + public string searchSeasonWordsString = "Season;Series;Saison;Temporada;Seizoen"; @@ -346,10 +352,7 @@ internal bool IncludeBetaUpdates() public string OtherExtensionsString = ""; public ShowFilter Filter = new ShowFilter(); - public string[] OtherExtensionsArray - { - get { return OtherExtensionsString.Split(';'); } - } + public string[] OtherExtensionsArray => OtherExtensionsString.Split(';'); public int ParallelDownloads = 4; public List RSSURLs = DefaultRSSURLList(); @@ -370,12 +373,8 @@ public string[] OtherExtensionsArray public int StartupTab = 0; public Searchers TheSearchers = new Searchers(); - public string[] VideoExtensionsArray - { - get { return VideoExtensionsString.Split(';'); } - } + public string[] VideoExtensionsArray => VideoExtensionsString.Split(';'); - public bool AutoMergeEpisodes = false; public string VideoExtensionsString = ""; @@ -633,6 +632,15 @@ public void load(XmlReader reader) else if (reader.Name == "EmptyMaxSizeMB") this.Tidyup.EmptyMaxSizeMB = reader.ReadElementContentAsInt(); + else if (reader.Name == "BulkAddIgnoreRecycleBin") + this.BulkAddIgnoreRecycleBin = reader.ReadElementContentAsBoolean(); + else if (reader.Name == "BulkAddCompareNoVideoFolders") + this.BulkAddCompareNoVideoFolders = reader.ReadElementContentAsBoolean(); + else if (reader.Name == "AutoAddMovieTerms") + this.AutoAddMovieTerms = reader.ReadElementContentAsString(); + else if (reader.Name == "AutoAddIgnoreSuffixes") + this.AutoAddIgnoreSuffixes = reader.ReadElementContentAsString(); + else if (reader.Name == "BetaMode") this.mode = (BetaMode)reader.ReadElementContentAsInt(); else if (reader.Name == "PercentDirtyUpgrade") @@ -910,6 +918,11 @@ public void WriteXML(XmlWriter writer) XMLHelper.WriteElementToXML(writer, "BaseSeasonName", this.defaultSeasonWord); XMLHelper.WriteElementToXML(writer, "SearchSeasonNames", this.searchSeasonWordsString); + XMLHelper.WriteElementToXML(writer, "BulkAddIgnoreRecycleBin", this.BulkAddIgnoreRecycleBin); + XMLHelper.WriteElementToXML(writer, "BulkAddCompareNoVideoFolders", this.BulkAddCompareNoVideoFolders); + XMLHelper.WriteElementToXML(writer, "AutoAddMovieTerms", this.AutoAddMovieTerms); + XMLHelper.WriteElementToXML(writer, "AutoAddIgnoreSuffixes", this.AutoAddIgnoreSuffixes); + writer.WriteStartElement("FNPRegexs"); foreach (FilenameProcessorRE re in this.FNPRegexs) { @@ -1146,6 +1159,8 @@ public string BTSearchURL(ProcessedEpisode epi) public string FilenameFriendly(string fn) { + if (string.IsNullOrWhiteSpace(fn)) return ""; + foreach (Replacement R in this.Replacements) { if (R.CaseInsensitive) diff --git a/TVRename#/Settings/ShowFilter.cs b/TVRename#/Settings/ShowFilter.cs index 30ff530a3..2ce2d6a3e 100644 --- a/TVRename#/Settings/ShowFilter.cs +++ b/TVRename#/Settings/ShowFilter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace TVRename @@ -29,7 +29,7 @@ public Boolean filter(ShowItem show) Boolean isNetworkOK = (ShowNetwork == null) || (show.TheSeries() == null ) || show.TheSeries().getNetwork().Equals(ShowNetwork); //Filter on show rating - Boolean isRatingOK = (ShowRating == null) || (show.TheSeries() == null) || show.TheSeries().GetRating().Equals(ShowRating); + Boolean isRatingOK = (ShowRating == null) || (show.TheSeries() == null) || show.TheSeries().GetContentRating().Equals(ShowRating); //Filter on show genres Boolean areGenresIgnored = (Genres.Count == 0); diff --git a/TVRename#/Settings/Statistics.cs b/TVRename#/Settings/Statistics.cs index 892dc7472..acacdb139 100644 --- a/TVRename#/Settings/Statistics.cs +++ b/TVRename#/Settings/Statistics.cs @@ -65,7 +65,7 @@ private static TVRenameStats LoadFrom(String filename) XmlSerializer xs = new XmlSerializer(typeof (TVRenameStats)); sc = (TVRenameStats) xs.Deserialize(reader); System.Diagnostics.Debug.Assert(sc != null); - reader.Close(); + } } catch (Exception e) @@ -88,8 +88,7 @@ private void SaveToFile(String toFile) { XmlSerializer xs = new XmlSerializer(typeof (TVRenameStats)); xs.Serialize(writer, this); - writer.Close(); } } } -} \ No newline at end of file +} diff --git a/TVRename#/TVRename/TVDoc.cs b/TVRename#/TVRename/TVDoc.cs index 63ef04934..b2e205ec9 100644 --- a/TVRename#/TVRename/TVDoc.cs +++ b/TVRename#/TVRename/TVDoc.cs @@ -27,7 +27,7 @@ namespace TVRename { - public class TVDoc + public class TVDoc :IDisposable { public List ShowItems; public List MonitorFolders; @@ -124,12 +124,12 @@ public List getNetworks() return distinctValues; } - public List GetRatings() + public List GetContentRatings() { List allValues = new List { }; foreach (ShowItem si in ShowItems) { - if (si.TheSeries()?.GetRating() != null) allValues.Add(si.TheSeries().GetRating()); + if (si.TheSeries()?.GetContentRating() != null) allValues.Add(si.TheSeries().GetContentRating()); } List distinctValues = allValues.Distinct().ToList(); distinctValues.Sort(); @@ -189,11 +189,6 @@ public void UpdateTVDBLanguage() TheTVDB.Instance.RequestLanguage = TVSettings.Instance.PreferredLanguage; } - ~TVDoc() - { - this.StopBGDownloadThread(); - } - private void LockShowItems() { return; @@ -312,7 +307,7 @@ public bool HasSeasonFolders(DirectoryInfo di, out string folderName, out Direct { if (subDir.Name.Contains(sw, StringComparison.InvariantCultureIgnoreCase)) { - logger.Info("Assuming {0} contains a show becasue keyword '{1}' is found in subdirectory {2}", di.FullName, sw, subDir.FullName); + logger.Info("Assuming {0} contains a show because keyword '{1}' is found in subdirectory {2}", di.FullName, sw, subDir.FullName); folderName = sw; return true; @@ -324,7 +319,7 @@ public bool HasSeasonFolders(DirectoryInfo di, out string folderName, out Direct catch (UnauthorizedAccessException uae) { // e.g. recycle bin, system volume information - logger.Warn(uae, "Could not access {0} (or a subdir), may not be an issue as could be expected e.g. recycle bin, system volume information",di.FullName); + logger.Warn("Could not access {0} (or a subdir), may not be an issue as could be expected e.g. recycle bin, system volume information",di.FullName); subDirs = null; } @@ -381,9 +376,14 @@ public bool CheckFolderForShows(DirectoryInfo di2, bool andGuess, out DirectoryI bool hasSubFolders = subDirectories?.Length > 0; if (!hasSubFolders || hasSeasonFolders) { + if (TVSettings.Instance.BulkAddCompareNoVideoFolders && !HasFilmFiles(di2)) return false; + + if (TVSettings.Instance.BulkAddIgnoreRecycleBin && di2.FullName.Contains("$RECYCLE.BIN",StringComparison.OrdinalIgnoreCase)) + return true; + // ....its good! FolderMonitorEntry ai = new FolderMonitorEntry(di2.FullName, hasSeasonFolders, folderName); - AddItems.Add(ai); + this.AddItems.Add(ai); logger.Info("Adding {0} as a new folder", theFolder); if (andGuess) this.GuessShowItem(ai); @@ -400,6 +400,11 @@ public bool CheckFolderForShows(DirectoryInfo di2, bool andGuess, out DirectoryI return hasSeasonFolders; } + private static bool HasFilmFiles(DirectoryInfo directory) + { + return directory.GetFiles("*", System.IO.SearchOption.TopDirectoryOnly).Any(file => TVSettings.Instance.UsefulExtension(file.Extension, false)); + } + public void CheckFolderForShows(DirectoryInfo di, ref bool stop) { // is it on the ''Bulk Add Shows' ignore list? @@ -1302,7 +1307,6 @@ public void WriteXMLSettings() writer.WriteEndElement(); // tvrename writer.WriteEndDocument(); - writer.Close(); } this.mDirty = false; @@ -1331,98 +1335,99 @@ public bool LoadXMLSettings(FileInfo from) return true; // that's ok } - XmlReader reader = XmlReader.Create(from.FullName, settings); - - reader.Read(); - if (reader.Name != "xml") - { - this.LoadErr = from.Name + " : Not a valid XML file"; - return false; - } - - reader.Read(); - - if (reader.Name != "TVRename") + using (XmlReader reader = XmlReader.Create(from.FullName, settings)) { - this.LoadErr = from.Name + " : Not a TVRename settings file"; - return false; - } - if (reader.GetAttribute("Version") != "2.1") - { - this.LoadErr = from.Name + " : Incompatible version"; - return false; - } + reader.Read(); + if (reader.Name != "xml") + { + this.LoadErr = from.Name + " : Not a valid XML file"; + return false; + } - reader.Read(); // move forward one + reader.Read(); - while (!reader.EOF) - { - if (reader.Name == "TVRename" && !reader.IsStartElement()) - break; // end of it all + if (reader.Name != "TVRename") + { + this.LoadErr = from.Name + " : Not a TVRename settings file"; + return false; + } - if (reader.Name == "Settings") + if (reader.GetAttribute("Version") != "2.1") { - TVSettings.Instance.load(reader.ReadSubtree()); - reader.Read(); + this.LoadErr = from.Name + " : Incompatible version"; + return false; } - else if (reader.Name == "MyShows") + + reader.Read(); // move forward one + + while (!reader.EOF) { - XmlReader r2 = reader.ReadSubtree(); - r2.Read(); - r2.Read(); - while (!r2.EOF) + if (reader.Name == "TVRename" && !reader.IsStartElement()) + break; // end of it all + + if (reader.Name == "Settings") { - if ((r2.Name == "MyShows") && (!r2.IsStartElement())) - break; - if (r2.Name == "ShowItem") + TVSettings.Instance.load(reader.ReadSubtree()); + reader.Read(); + } + else if (reader.Name == "MyShows") + { + XmlReader r2 = reader.ReadSubtree(); + r2.Read(); + r2.Read(); + while (!r2.EOF) { - ShowItem si = new ShowItem(r2.ReadSubtree()); - - if (si.UseCustomShowName) // see if custom show name is actually the real show name + if ((r2.Name == "MyShows") && (!r2.IsStartElement())) + break; + if (r2.Name == "ShowItem") { - SeriesInfo ser = si.TheSeries(); - if ((ser != null) && (si.CustomShowName == ser.Name)) + ShowItem si = new ShowItem(r2.ReadSubtree()); + + if (si.UseCustomShowName) // see if custom show name is actually the real show name { - // then, turn it off - si.CustomShowName = ""; - si.UseCustomShowName = false; + SeriesInfo ser = si.TheSeries(); + if ((ser != null) && (si.CustomShowName == ser.Name)) + { + // then, turn it off + si.CustomShowName = ""; + si.UseCustomShowName = false; + } } - } - ShowItems.Add(si); - r2.Read(); + ShowItems.Add(si); + + r2.Read(); + } + else + r2.ReadOuterXml(); } - else - r2.ReadOuterXml(); + + reader.Read(); } - reader.Read(); - } - else if (reader.Name == "MonitorFolders") - this.MonitorFolders = XMLHelper.ReadStringsFromXml(reader, "MonitorFolders", "Folder"); - else if (reader.Name == "IgnoreFolders") - this.IgnoreFolders = XMLHelper.ReadStringsFromXml(reader, "IgnoreFolders", "Folder"); - else if (reader.Name == "FinderSearchFolders") - this.SearchFolders = XMLHelper.ReadStringsFromXml(reader, "FinderSearchFolders", "Folder"); - else if (reader.Name == "IgnoreItems") - { - XmlReader r2 = reader.ReadSubtree(); - r2.Read(); - r2.Read(); - while (r2.Name == "Ignore") - this.Ignore.Add(new IgnoreItem(r2)); - reader.Read(); + else if (reader.Name == "MonitorFolders") + this.MonitorFolders = XMLHelper.ReadStringsFromXml(reader, "MonitorFolders", "Folder"); + else if (reader.Name == "IgnoreFolders") + this.IgnoreFolders = XMLHelper.ReadStringsFromXml(reader, "IgnoreFolders", "Folder"); + else if (reader.Name == "FinderSearchFolders") + this.SearchFolders = XMLHelper.ReadStringsFromXml(reader, "FinderSearchFolders", "Folder"); + else if (reader.Name == "IgnoreItems") + { + XmlReader r2 = reader.ReadSubtree(); + r2.Read(); + r2.Read(); + while (r2.Name == "Ignore") + this.Ignore.Add(new IgnoreItem(r2)); + reader.Read(); + } + else + reader.ReadOuterXml(); } - else - reader.ReadOuterXml(); } - - reader.Close(); - reader = null; } catch (Exception e) { - logger.Warn(e,"Problem on Startup loading File"); + logger.Warn(e, "Problem on Startup loading File"); this.LoadErr = from.Name + " : " + e.Message; return false; } @@ -1436,10 +1441,10 @@ public bool LoadXMLSettings(FileInfo from) // not worried if stats loading fails } - //Set these on the settigns object so others can read them too - iealy shuld be refactored into the settings code - TVSettings.Instance.MonitorFoldersNames = this.MonitorFolders; + //Set these on the settings object so others can read them too - ideally should be refactored into the settings code + TVSettings.Instance.LibraryFoldersNames = this.MonitorFolders; TVSettings.Instance.IgnoreFoldersNames = this.IgnoreFolders; - TVSettings.Instance.SearchFoldersNames = this.SearchFolders; + TVSettings.Instance.DownloadFoldersNames = this.SearchFolders; return true; } @@ -3296,6 +3301,34 @@ public UpdateVersion CheckForUpdates() return null; } + + private void ReleaseUnmanagedResources() + { + this.StopBGDownloadThread(); + } + + private void Dispose(bool disposing) + { + ReleaseUnmanagedResources(); + if (disposing) + { + // ReSharper disable once UseNullPropagation + if (this.ScanProgDlg != null) this.ScanProgDlg.Dispose(); + // ReSharper disable once UseNullPropagation + if (this.WorkerSemaphore != null) this.WorkerSemaphore.Dispose(); + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + ~TVDoc() + { + Dispose(false); + } } public class UpdateVersion :IComparable diff --git a/TVRename#/TheTVDB/Banner.cs b/TVRename#/TheTVDB/Banner.cs index c04866d44..441017054 100644 --- a/TVRename#/TheTVDB/Banner.cs +++ b/TVRename#/TheTVDB/Banner.cs @@ -211,7 +211,7 @@ public bool isFanart() return ((this.BannerType == "fanart") ); } - public void SetDefaults(SeriesInfo ser, Season seas) + private void SetDefaults(SeriesInfo ser, Season seas) { this.TheSeason = seas; this.TheSeries = ser; diff --git a/TVRename#/TheTVDB/SeriesInfo.cs b/TVRename#/TheTVDB/SeriesInfo.cs index 053c95a28..8b0266561 100644 --- a/TVRename#/TheTVDB/SeriesInfo.cs +++ b/TVRename#/TheTVDB/SeriesInfo.cs @@ -454,7 +454,8 @@ public void LoadJSON(JObject bestLanguageR, JObject backupLanguageR) public string getNetwork() => getValueAcrossVersions("Network", "network", ""); public string GetOverview() => getValueAcrossVersions("Overview", "overview", ""); public string GetRuntime() => getValueAcrossVersions("Runtime", "runtime", ""); - public string GetRating() => getValueAcrossVersions("Rating","rating",""); // check , "ContentRating" + public string GetContentRating() => getValueAcrossVersions("Rating","rating",""); + public string GetSiteRating() => getValueAcrossVersions("SiteRating", "siteRating", ""); public string GetIMDB() => getValueAcrossVersions("IMDB_ID", "imdb_id", ""); public string GetYear() => getValueAcrossVersions("Year", "year", ""); public string GetFirstAired() => getValueAcrossVersions("FirstAired", "firstAired", ""); diff --git a/TVRename#/TheTVDB/TheTVDB.cs b/TVRename#/TheTVDB/TheTVDB.cs index 6aa584f2c..bb639dceb 100644 --- a/TVRename#/TheTVDB/TheTVDB.cs +++ b/TVRename#/TheTVDB/TheTVDB.cs @@ -25,7 +25,7 @@ namespace TVRename { - + [Serializable()] public class TVDBException : System.Exception { // Thrown if an error occurs in the XML when reading TheTVDB.xml @@ -39,14 +39,14 @@ public static class KeepTVDBAliveTimer { static System.Timers.Timer _timer; // From System.Timers - static public void Start() + public static void Start() { _timer = new System.Timers.Timer(23 * 60 * 60 * 1000); // Set up the timer for 23 hours - _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); + _timer.Elapsed += _timer_Elapsed; _timer.Enabled = true; // Enable it } - static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + private static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { TheTVDB.Instance.RefreshToken(); } @@ -70,7 +70,7 @@ public Language(int id, string abbreviation, string name, string englishName) { public class TheTVDB { - public string WebsiteRoot; + private static string WebsiteRoot; private FileInfo CacheFile; public bool Connected; public string CurrentDLTask; @@ -84,7 +84,7 @@ public class TheTVDB private System.Collections.Generic.Dictionary Series; // TODO: make this private or a property. have online/offline state that controls auto downloading of needed info. private long Srv_Time; // only update this after a 100% successful download // private List WhoHasLock; - private string APIRoot; + private static string APIRoot; private string authenticationToken; //The JSON Web token issued by TVDB public String RequestLanguage = "en"; // Set and updated by TVDoc @@ -98,7 +98,7 @@ public class TheTVDB //http://msdn.microsoft.com/en-au/library/ff650316.aspx private static volatile TheTVDB instance; - private static object syncRoot = new Object(); + private static object syncRoot = new object(); public static TheTVDB Instance { @@ -117,9 +117,9 @@ public static TheTVDB Instance } } - public void setup(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args) + public void Setup(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args) { - Args = args; + this.Args = args; System.Diagnostics.Debug.Assert(cacheFile != null); this.CacheFile = cacheFile; @@ -129,11 +129,10 @@ public void setup(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args) this.Connected = false; this.ExtraEpisodes = new System.Collections.Generic.List(); - this.LanguageList = new List(); - this.LanguageList.Add(new Language(7,"en","English","English")); + this.LanguageList = new List {new Language(7, "en", "English", "English")}; - this.WebsiteRoot = "http://thetvdb.com"; - this.APIRoot = "https://api.thetvdb.com"; + WebsiteRoot = "http://thetvdb.com"; + APIRoot = "https://api.thetvdb.com"; this.Series = new System.Collections.Generic.Dictionary(); @@ -145,7 +144,7 @@ public void setup(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args) this.LoadOK = (loadFrom == null) || this.LoadCache(loadFrom); - this.ForceReloadOn = new System.Collections.Generic.List(); + this.ForceReloadOn = new List(); } private void LockEE() @@ -195,7 +194,6 @@ public System.Collections.Generic.Dictionary GetSeriesDictMatch return matchingSeries; } - public bool GetLock(string whoFor) { logger.Trace("Lock Series for " + whoFor); @@ -229,7 +227,7 @@ private void Say(string s) public bool LoadCache(FileInfo loadFrom) { logger.Info("Loading Cache from: {0}", loadFrom.FullName); - if ((loadFrom == null) || !loadFrom.Exists) + if (!loadFrom.Exists) return true; // that's ok FileStream fs = null; @@ -248,8 +246,7 @@ public bool LoadCache(FileInfo loadFrom) logger.Warn(e, "Problem on Startup loading File"); this.LoadErr = loadFrom.Name + " : " + e.Message; - if (fs != null) - fs.Close(); + fs?.Close(); fs = null; @@ -363,7 +360,6 @@ public void SaveCache() writer.WriteEndElement(); // data writer.WriteEndDocument(); - writer.Close(); } this.Unlock("SaveCache"); } @@ -419,7 +415,7 @@ public bool Connect() public static string BuildURL(bool withHttpAndKey, bool episodesToo, int code, string lang) //would rather make this private to hide api key from outside world { - string r = withHttpAndKey ? "http://thetvdb.com/api/" + APIKey() + "/" : ""; + string r = withHttpAndKey ? WebsiteRoot + "/api/" + APIKey() + "/" : ""; r += episodesToo ? "series/" + code + "/all/" + lang + ".zip" : "series/" + code + "/" + lang + ".xml"; return r; } @@ -431,7 +427,7 @@ private static string APIKey() public string GetTVDBDownloadURL(string url) { - string mirr = this.WebsiteRoot; + string mirr = WebsiteRoot; if (url.StartsWith("/")) url = url.Substring(1); @@ -445,8 +441,6 @@ public string GetTVDBDownloadURL(string url) return theURL; } - - public byte[] GetTVDBDownload(string url, bool forceReload = false) { @@ -599,7 +593,6 @@ public bool RefreshToken() } - public bool GetUpdates() { this.Say("Updates list"); @@ -779,18 +772,16 @@ public bool GetUpdates() while (morePages) { - String episodeUri = APIRoot + "/series/" + id + "/episodes"; - JObject jsonEpisodeResponse; + string episodeUri = APIRoot + "/series/" + id + "/episodes"; try { - jsonEpisodeResponse = HTTPHelper.JsonHTTPGETRequest(episodeUri, + JObject jsonEpisodeResponse = HTTPHelper.JsonHTTPGETRequest(episodeUri, new Dictionary {{"page", pageNumber.ToString()}}, this.authenticationToken); episodeResponses.Add(jsonEpisodeResponse); int numberOfResponses = ((JArray) jsonEpisodeResponse["data"]).Count; - logger.Info("Page " + pageNumber + " of " + this.Series[id].Name + " had " + - numberOfResponses + " episodes listed"); + logger.Info($"Page {pageNumber} of {this.Series[id].Name} had {numberOfResponses} episodes listed"); if (numberOfResponses < 100) { morePages = false; @@ -913,6 +904,7 @@ public bool GetUpdates() return true; } + private bool ProcessXML(Stream str, Stream bannerStr, int? codeHint) { bool response = ProcessXML(str, codeHint); @@ -1001,9 +993,8 @@ private bool ProcessXMLBanner(Stream str, int? codeHint) IgnoreComments = true, IgnoreWhitespace = true }; - XmlReader r = XmlReader.Create(str, settings); - - ProcessXMLBanner(r, codeHint); + using (XmlReader r = XmlReader.Create(str, settings)) + ProcessXMLBanner(r, codeHint); } catch (XmlException e) @@ -1070,6 +1061,7 @@ private void ProcessXMLBanner(XmlReader r, int? codeHint) } } + private int getLanguageId() { foreach (Language l in LanguageList) { if (l.abbreviation == this.RequestLanguage) return l.id; @@ -1077,6 +1069,7 @@ private int getLanguageId() { return -1; } + private int getDefaultLanguageId() { foreach (Language l in LanguageList) @@ -1086,6 +1079,7 @@ private int getDefaultLanguageId() return -1; } + private bool ProcessXML(Stream str, int? codeHint) { // Will have one or more series, and episodes @@ -1118,56 +1112,59 @@ private bool ProcessXML(Stream str, int? codeHint) IgnoreComments = true, IgnoreWhitespace = true }; - XmlReader r = XmlReader.Create(str, settings); + using (XmlReader r = XmlReader.Create(str, settings)) + { - r.Read(); + r.Read(); - while (!r.EOF) - { - if ((r.Name == "Data") && !r.IsStartElement()) - break; // that's it. - if (r.Name == "Series") + while (!r.EOF) { - // The returned by GetSeries have - // less info than other results from - // thetvdb.com, so we need to smartly merge - // in a if we already have some/all - // info on it (depending on which one came - // first). + if ((r.Name == "Data") && !r.IsStartElement()) + break; // that's it. + if (r.Name == "Series") + { + // The returned by GetSeries have + // less info than other results from + // thetvdb.com, so we need to smartly merge + // in a if we already have some/all + // info on it (depending on which one came + // first). - SeriesInfo si = new SeriesInfo(r.ReadSubtree()); - if (this.Series.ContainsKey(si.TVDBCode)) - this.Series[si.TVDBCode].Merge(si, this.getLanguageId()); - else - this.Series[si.TVDBCode] = si; - r.Read(); - } - else if (r.Name == "Episode") - { - Episode e = new Episode(null, null,null, r.ReadSubtree(), Args); - if (e.OK()) + SeriesInfo si = new SeriesInfo(r.ReadSubtree()); + if (this.Series.ContainsKey(si.TVDBCode)) + this.Series[si.TVDBCode].Merge(si, this.getLanguageId()); + else + this.Series[si.TVDBCode] = si; + r.Read(); + } + else if (r.Name == "Episode") + { + Episode e = new Episode(null, null, null, r.ReadSubtree(), Args); + if (e.OK()) + { + AddOrUpdateEpisode(e); + } + + r.Read(); + } + else if (r.Name == "xml") + r.Read(); + else if (r.Name == "BannersCache") { - AddOrUpdateEpisode(e); + //this wil not be found in a standard response from the TVDB website + //will only be in the response when we are reading from the cache + ProcessXMLBannerCache(r); + r.Read(); } - r.Read(); - } - else if (r.Name == "xml") - r.Read(); - else if (r.Name == "BannersCache") - { - //this wil not be found in a standard response from the TVDB website - //will only be in the response when we are reading from the cache - ProcessXMLBannerCache(r); - r.Read(); - } - else if (r.Name == "Data") - { - string time = r.GetAttribute("time"); - this.New_Srv_Time = (time == null)?0:long.Parse(time); - r.Read(); + else if (r.Name == "Data") + { + string time = r.GetAttribute("time"); + this.New_Srv_Time = (time == null) ? 0 : long.Parse(time); + r.Read(); + } + else + r.ReadOuterXml(); } - else - r.ReadOuterXml(); } } catch (XmlException e) @@ -1175,9 +1172,9 @@ private bool ProcessXML(Stream str, int? codeHint) str.Position = 0; - StreamReader sr = new StreamReader(str); - string myStr = sr.ReadToEnd(); - + string myStr; + using (StreamReader sr = new StreamReader(str)) myStr = sr.ReadToEnd(); + string message = "Error processing data from TheTVDB (top level)."; message += "\r\n" + myStr; message += "\r\n" + e.Message; @@ -1186,6 +1183,7 @@ private bool ProcessXML(Stream str, int? codeHint) { name += "Show \"" + Series[codeHint.Value].Name + "\" "; } + if (codeHint.HasValue) { name += "ID #" + codeHint.Value + " "; @@ -1199,6 +1197,7 @@ private bool ProcessXML(Stream str, int? codeHint) { this.Unlock("ProcessTVDBResponse"); } + return true; } @@ -1217,8 +1216,6 @@ private void AddOrUpdateEpisode(Episode e) e.SetSeriesSeason(ser, airedSeason,dvdSeason); } - - public bool DoWeForceReloadFor(int code) { return this.ForceReloadOn.Contains(code) || !this.Series.ContainsKey(code); @@ -1243,14 +1240,14 @@ private SeriesInfo DownloadSeriesNow(int code, bool episodesToo, bool bannersToo this.Say(txt); - String uri = APIRoot + "/series/" + code; - JObject jsonResponse = new JObject(); + string uri = APIRoot + "/series/" + code; + JObject jsonResponse; JObject jsonDefaultLangResponse = new JObject(); try { jsonResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, TVSettings.Instance.PreferredLanguage); - if (inForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, DefaultLanguage ); + if (InForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, DefaultLanguage ); } catch (WebException ex) { @@ -1264,7 +1261,7 @@ private SeriesInfo DownloadSeriesNow(int code, bool episodesToo, bool bannersToo SeriesInfo si; JObject seriesData = (JObject)jsonResponse["data"]; - if (inForeignLanguage()) { + if (InForeignLanguage()) { JObject seriesDataDefaultLang = (JObject)jsonDefaultLangResponse["data"]; si = new SeriesInfo(seriesData,seriesDataDefaultLang, getLanguageId()); } @@ -1293,7 +1290,7 @@ private SeriesInfo DownloadSeriesNow(int code, bool episodesToo, bool bannersToo while (morePages) { String episodeUri = APIRoot + "/series/" + code + "/episodes"; - JObject jsonEpisodeResponse = new JObject(); + JObject jsonEpisodeResponse; try { jsonEpisodeResponse = HTTPHelper.JsonHTTPGETRequest(episodeUri, new Dictionary { { "page", pageNumber.ToString() } }, this.authenticationToken); @@ -1372,7 +1369,7 @@ private SeriesInfo DownloadSeriesNow(int code, bool episodesToo, bool bannersToo } } - if (inForeignLanguage()) + if (InForeignLanguage()) { List imageDefaultLangTypes = new List(); @@ -1480,7 +1477,7 @@ private SeriesInfo DownloadSeriesNow(int code, bool episodesToo, bool bannersToo } - private bool inForeignLanguage() => DefaultLanguage != this.RequestLanguage; + private bool InForeignLanguage() => DefaultLanguage != this.RequestLanguage; private bool DownloadEpisodeNow(int seriesID, int episodeID, bool dvdOrder = false) { @@ -1514,7 +1511,7 @@ private bool DownloadEpisodeNow(int seriesID, int episodeID, bool dvdOrder = fal try { jsonResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, TVSettings.Instance.PreferredLanguage); - if (inForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, DefaultLanguage); + if (InForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, null, this.authenticationToken, DefaultLanguage); } catch (WebException ex) { @@ -1533,7 +1530,7 @@ private bool DownloadEpisodeNow(int seriesID, int episodeID, bool dvdOrder = fal Episode e; JObject jsonResponseData = (JObject)jsonResponse["data"]; - if (inForeignLanguage()) + if (InForeignLanguage()) { JObject seriesDataDefaultLang = (JObject)jsonDefaultLangResponse["data"]; e = new Episode(seriesID, jsonResponseData, seriesDataDefaultLang); @@ -1632,7 +1629,7 @@ public void Search(string text) try { jsonResponse = HTTPHelper.JsonHTTPGETRequest(uri, new Dictionary { { "name", text } }, this.authenticationToken, TVSettings.Instance.PreferredLanguage); - if (inForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, new Dictionary { { "name", text } }, this.authenticationToken, DefaultLanguage); + if (InForeignLanguage()) jsonDefaultLangResponse = HTTPHelper.JsonHTTPGETRequest(uri, new Dictionary { { "name", text } }, this.authenticationToken, DefaultLanguage); } catch (WebException ex) { @@ -1677,7 +1674,7 @@ public void Search(string text) } - if (inForeignLanguage()) + if (InForeignLanguage()) { //we also want to search for search terms that match in default language try { @@ -1713,26 +1710,23 @@ public void Search(string text) } - public string WebsiteURL(int code, int seasid, bool summaryPage) + public string WebsiteURL(int seriesId, int seasonId, bool summaryPage) { // Summary: http://www.thetvdb.com/?tab=series&id=75340&lid=7 // Season 3: http://www.thetvdb.com/?tab=season&seriesid=75340&seasonid=28289&lid=7 - if (summaryPage || (seasid <= 0) || !this.Series.ContainsKey(code)) - return this.WebsiteRoot + "/?tab=series&id=" + code; + if (summaryPage || (seasonId <= 0) || !this.Series.ContainsKey(seriesId)) + return WebsiteRoot + "/?tab=series&id=" + seriesId; else - return this.WebsiteRoot + "/?tab=season&seriesid=" + code + "&seasonid=" + seasid; + return WebsiteRoot + "/?tab=season&seriesid=" + seriesId + "&seasonid=" + seasonId; } - public string WebsiteURL(int SeriesID, int SeasonID, int EpisodeID) + public string WebsiteURL(int seriesId, int seasonId, int episodeId) { // http://www.thetvdb.com/?tab=episode&seriesid=73141&seasonid=5356&id=108303&lid=7 - return this.WebsiteRoot + "/?tab=episode&seriesid=" + SeriesID + "&seasonid=" + SeasonID + "&id=" + EpisodeID; + return WebsiteRoot + "/?tab=episode&seriesid=" + seriesId + "&seasonid=" + seasonId + "&id=" + episodeId; } - - - // Next episode to air of a given show public Episode NextAiring(int code) { @@ -1765,6 +1759,15 @@ public Episode NextAiring(int code) return next; } + + public static string GetBannerURL(string bannerPath) + { + return WebsiteRoot + "/banners/" + bannerPath; + } + public static string GetThumbnailURL(string filename) + { + return WebsiteRoot + "/banners/_cache/" + filename; + } } } diff --git a/TVRename#/Utility/Helpers.cs b/TVRename#/Utility/Helpers.cs index ba620cfce..c0b307f06 100644 --- a/TVRename#/Utility/Helpers.cs +++ b/TVRename#/Utility/Helpers.cs @@ -36,6 +36,14 @@ namespace TVRename { + internal static partial class NativeMethods + { + [return: MarshalAs(UnmanagedType.Bool)] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); + } + + public delegate void SetProgressDelegate(int percent); public static class XMLHelper @@ -294,10 +302,6 @@ public static string GBMB(this long value, int decimalPlaces = 2) } - [return: MarshalAs(UnmanagedType.Bool)] - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); - /// /// Gets the properties for this file system. /// @@ -305,10 +309,7 @@ public static string GBMB(this long value, int decimalPlaces = 2) /// A containing the properties for the specified file system. public static FileSystemProperties GetProperties(string volumeIdentifier) { - ulong available; - ulong total; - ulong free; - if (GetDiskFreeSpaceEx(volumeIdentifier, out available, out total, out free)) + if (NativeMethods.GetDiskFreeSpaceEx(volumeIdentifier, out ulong available, out ulong total, out ulong free)) { return new FileSystemProperties((long)total, (long)free, (long)available); } @@ -379,6 +380,7 @@ public static bool SimplifyAndCheckFilename(string filename, string showname) public static string MakeValidPath(string input) { + if (string.IsNullOrWhiteSpace(input)) return ""; string directoryName = input; string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); @@ -416,7 +418,6 @@ public static String HTTPRequest(String method, String url,String json, String c { streamWriter.Write(json); streamWriter.Flush(); - streamWriter.Close(); } } @@ -890,8 +891,8 @@ public static string TrimEnd(this string root, string ending) public static string RemoveAfter(this string root, string ending) { - if (root.IndexOf(ending) !=-1) - return root.Substring(0, root.IndexOf(ending)); + if (root.IndexOf(ending, StringComparison.OrdinalIgnoreCase) !=-1) + return root.Substring(0, root.IndexOf(ending,StringComparison.OrdinalIgnoreCase)); return root; }