Skip to content

Commit

Permalink
Merge pull request #450 from TV-Rename/code-tidy
Browse files Browse the repository at this point in the history
Many Updates
  • Loading branch information
SirSparkles authored Aug 4, 2018
2 parents b7d55d9 + 6b4a5aa commit ece9cb5
Show file tree
Hide file tree
Showing 43 changed files with 2,511 additions and 1,644 deletions.
5 changes: 4 additions & 1 deletion TVRename.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/Highlighting/AnalysisEnabled/@EntryValue">SOLUTION</s:String></wpf:ResourceDictionary>
<s:String x:Key="/Default/CodeInspection/Highlighting/AnalysisEnabled/@EntryValue">SOLUTION</s:String>
<s:String x:Key="/Default/Profiling/Configurations/=0/@EntryIndexedValue">&lt;data&gt;&lt;HostParameters type="LocalHostParameters" /&gt;&lt;Argument type="AttachArgument"&gt;&lt;DisplayName&gt;C:\Users\Mark\source\repos\TV-Rename\tvrename-master\TVRename\bin\Debug\TVRename.exe&lt;/DisplayName&gt;&lt;ProcessId&gt;30360&lt;/ProcessId&gt;&lt;RuntimeVersion&gt;4.0.30319&lt;/RuntimeVersion&gt;&lt;/Argument&gt;&lt;Info type="TimelineInfo" /&gt;&lt;CoreOptions type="CoreOptions"&gt;&lt;CoreTempPath IsNull="False"&gt;&lt;/CoreTempPath&gt;&lt;RemoteEndPoint IsNull="False"&gt;&lt;/RemoteEndPoint&gt;&lt;AdditionalEnvironmentVariables /&gt;&lt;/CoreOptions&gt;&lt;HostOptions type="HostOptions"&gt;&lt;HostTempPath IsNull="False"&gt;&lt;/HostTempPath&gt;&lt;/HostOptions&gt;&lt;/data&gt;</s:String>
<s:String x:Key="/Default/Profiling/Configurations/=1/@EntryIndexedValue">&lt;data&gt;&lt;HostParameters type="LocalHostParameters" /&gt;&lt;Argument type="StandaloneArgument"&gt;&lt;Arguments IsNull="False"&gt;&lt;/Arguments&gt;&lt;FileName IsNull="False"&gt;&lt;/FileName&gt;&lt;WorkingDirectory IsNull="False"&gt;&lt;/WorkingDirectory&gt;&lt;Scope&gt;&lt;ProcessFilters /&gt;&lt;/Scope&gt;&lt;/Argument&gt;&lt;Info type="TimelineInfo" /&gt;&lt;CoreOptions type="CoreOptions"&gt;&lt;CoreTempPath IsNull="False"&gt;&lt;/CoreTempPath&gt;&lt;RemoteEndPoint IsNull="False"&gt;&lt;/RemoteEndPoint&gt;&lt;AdditionalEnvironmentVariables /&gt;&lt;/CoreOptions&gt;&lt;HostOptions type="HostOptions"&gt;&lt;HostTempPath IsNull="False"&gt;&lt;/HostTempPath&gt;&lt;/HostOptions&gt;&lt;/data&gt;</s:String>
</wpf:ResourceDictionary>
4 changes: 2 additions & 2 deletions TVRename/App/ApplicationBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ protected override void OnCreateMainForm()
doc = new TVDoc(settingsFile, clargs);

if (recover) doc.SetDirty();
recover = !doc.LoadOK;
recover = !doc.LoadOk;

// Continue if correctly loaded
if (!recover) continue;

// Set recover message
recoverText = string.Empty;
if (!doc.LoadOK && !string.IsNullOrEmpty(doc.LoadErr)) recoverText = doc.LoadErr;
if (!doc.LoadOk && !string.IsNullOrEmpty(doc.LoadErr)) recoverText = doc.LoadErr;
if (!TheTVDB.Instance.LoadOk && !string.IsNullOrEmpty(TheTVDB.Instance.LoadErr)) recoverText += $"{Environment.NewLine}{TheTVDB.Instance.LoadErr}";
} while (recover);

Expand Down
23 changes: 10 additions & 13 deletions TVRename/DownloadIdentifers/DownloadXBMCImages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public override ItemList ProcessSeason(ShowItem si, string folder, int snum, boo

string filenamePrefix = "";

if (!si.AutoAdd_FolderPerSeason)
if (si.InOneFolder())
{ // We have multiple seasons in the same folder
// We need to do slightly more work to come up with the filenamePrefix

Expand Down Expand Up @@ -175,19 +175,16 @@ public override ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo, bo
private ActionDownloadImage DoEpisode(ShowItem si, Episode ep, FileInfo filo,string extension, bool forceRefresh)
{
string ban = ep.Filename;
if (!string.IsNullOrEmpty(ban))
{
string basefn = filo.RemoveExtension();
FileInfo imgtbn = FileHelper.FileInFolder(filo.Directory, basefn + extension);
if (!imgtbn.Exists || forceRefresh)
if (!(doneTbn.Contains(imgtbn.FullName)))
{
doneTbn.Add(imgtbn.FullName);
if (string.IsNullOrEmpty(ban)) return null;

return new ActionDownloadImage(si, (ep is ProcessedEpisode) ? (ProcessedEpisode)ep : new ProcessedEpisode(ep,si ), imgtbn, ban);
}
}
return null;
string basefn = filo.RemoveExtension();
FileInfo imgtbn = FileHelper.FileInFolder(filo.Directory, basefn + extension);
if (imgtbn.Exists && !forceRefresh) return null;

if (doneTbn.Contains(imgtbn.FullName)) return null;

doneTbn.Add(imgtbn.FullName);
return new ActionDownloadImage(si, ep is ProcessedEpisode episode ? episode : new ProcessedEpisode(ep,si ), imgtbn, ban);
}

public sealed override void Reset()
Expand Down
1 change: 0 additions & 1 deletion TVRename/Exporter/ShowsHTML.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,5 @@ private static string CreateHtml(ShowItem si)
</div>
</div></div></div>";
}

}
}
64 changes: 64 additions & 0 deletions TVRename/Exporter/UpcomingiCAL.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Text;
using Ical.Net;
using Ical.Net.CalendarComponents;
using Ical.Net.DataTypes;
using Ical.Net.Serialization;

namespace TVRename
{
// ReSharper disable once InconsistentNaming
internal class UpcomingiCAL :UpcomingExporter
{
public UpcomingiCAL(TVDoc i) : base(i) { }
public override bool Active() =>TVSettings.Instance.ExportWTWICAL;
protected override string Location() => TVSettings.Instance.ExportWTWICALTo;

protected override bool Generate(System.IO.Stream str, List<ProcessedEpisode> elist)
{
if (elist == null)
return false;

try
{
Calendar calendar = new Calendar {ProductId = "Upcoming Shows Exported by TV Rename http://www.tvrename.com"};

foreach (ProcessedEpisode ei in elist)
{
string niceName = TVSettings.Instance.NamingStyle.NameFor(ei);
DateTime? stTime = ei.GetAirDateDT(true);

if (!stTime.HasValue) continue;

DateTime startTime = stTime.Value;
String s = ei.SI.TheSeries().GetRuntime();
DateTime endTime = stTime.Value.AddMinutes(int.Parse(s));

CalendarEvent e = new CalendarEvent
{
Start = new CalDateTime(startTime),
End = new CalDateTime(endTime),
Description = ei.Overview,
Comments = new List<string>{ei.Overview},
Summary = niceName,
Location=ei.TheSeries.GetNetwork(),
Url = new Uri(TheTVDB.Instance.WebsiteUrl(ei.TheSeries.TVDBCode, ei.SeasonId, false)),
Uid = ei.EpisodeId.ToString()
};
calendar.Events.Add(e);
}

CalendarSerializer serializer = new CalendarSerializer();
serializer.Serialize(calendar,str,Encoding.ASCII);

return true;
} // try
catch (Exception e)
{
Logger.Error(e);
return false;
}
}
}
}
2 changes: 1 addition & 1 deletion TVRename/Finders/FileFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ private bool ReviewFile(ItemMissing me, ItemList addTo, DirCacheEntry dce)
if (FileHelper.IgnoreFile(dce.TheFile))return false;

//do any of the possible names for the series match the filename?
matched = (me.Episode.SI.getSimplifiedPossibleShowNames()
matched = (me.Episode.SI.GetSimplifiedPossibleShowNames()
.Any(name => FileHelper.SimplifyAndCheckFilename(dce.SimplifiedFullName, name)));

if (matched)
Expand Down
29 changes: 15 additions & 14 deletions TVRename/Finders/SABnzbdFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace TVRename
{
// ReSharper disable once InconsistentNaming
class SABnzbdFinder :Finder
{
public SABnzbdFinder(TVDoc i) : base(i) { }
Expand All @@ -31,18 +32,18 @@ public override void Check(SetProgressDelegate prog, int startpct, int totPct)

// Something like:
// http://localhost:8080/sabnzbd/api?mode=queue&apikey=xxx&start=0&limit=8888&output=xml
string theURL = "http://" + TVSettings.Instance.SABHostPort +
string theUrl = "http://" + TVSettings.Instance.SABHostPort +
"/sabnzbd/api?mode=queue&start=0&limit=8888&output=xml&apikey=" + TVSettings.Instance.SABAPIKey;

WebClient wc = new WebClient();
byte[] r = null;
try
{
r = wc.DownloadData(theURL);
r = wc.DownloadData(theUrl);
}
catch (WebException)
{
Logger.Warn("Failed to obtain SABnzbd, please recheck settings: " + theURL);
Logger.Warn("Failed to obtain SABnzbd, please recheck settings: " + theUrl);
}

if (r == null)
Expand All @@ -66,7 +67,7 @@ public override void Check(SetProgressDelegate prog, int startpct, int totPct)
// wasn't a result/error combo. this is good!
}

SAB.Queue sq = null;
SAB.Queue sq;
try
{
sq = SAB.Queue.Deserialize(r);
Expand All @@ -87,20 +88,20 @@ public override void Check(SetProgressDelegate prog, int startpct, int totPct)
int c = ActionList.Count + 2;
int n = 1;

foreach (Item Action1 in ActionList)
foreach (Item action1 in ActionList)
{
if (ActionCancel)
return;

prog.Invoke(startpct + (totPct - startpct) * (++n) / (c));


if (!(Action1 is ItemMissing))
if (!(action1 is ItemMissing))
continue;

ItemMissing Action = (ItemMissing)(Action1);
ItemMissing action = (ItemMissing)(action1);

string showname = Helpers.SimplifyName(Action.Episode.SI.ShowName);
string showname = Helpers.SimplifyName(action.Episode.SI.ShowName);

foreach (SAB.QueueSlotsSlot te in sq.slots)
{
Expand All @@ -111,10 +112,10 @@ public override void Check(SetProgressDelegate prog, int startpct, int totPct)
// continue;

if (!FileHelper.SimplifyAndCheckFilename(file.FullName, showname, true, false)) continue;
if (!TVDoc.FindSeasEp(file, out int seasF, out int epF, out int maxEp, Action.Episode.SI) ||
(seasF != Action.Episode.AppropriateSeasonNumber) || (epF != Action.Episode.AppropriateEpNum )) continue;
toRemove.Add(Action1);
newList.Add(new ItemSABnzbd(te, Action.Episode, Action.TheFileNoExt));
if (!TVDoc.FindSeasEp(file, out int seasF, out int epF, out int _, action.Episode.SI) ||
(seasF != action.Episode.AppropriateSeasonNumber) || (epF != action.Episode.AppropriateEpNum )) continue;
toRemove.Add(action1);
newList.Add(new ItemSABnzbd(te, action.Episode, action.TheFileNoExt));
break;
}
}
Expand All @@ -123,8 +124,8 @@ public override void Check(SetProgressDelegate prog, int startpct, int totPct)
foreach (Item i in toRemove)
ActionList.Remove(i);

foreach (Item Action in newList)
ActionList.Add(Action);
foreach (Item action in newList)
ActionList.Add(action);

prog.Invoke(totPct);
}
Expand Down
61 changes: 61 additions & 0 deletions TVRename/Finders/TorrentFinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Collections.Generic;
using System.Linq;
using Alphaleonis.Win32.Filesystem;

namespace TVRename
{
internal abstract class TorrentFinder : Finder
{
public override FinderDisplayType DisplayType() => FinderDisplayType.downloading;

protected void SearchForAppropriateDownloads(SetProgressDelegate prog, int startpct, int totPct, List<TorrentEntry> downloading)
{
ItemList newList = new ItemList();
ItemList toRemove = new ItemList();
int c = ActionList.Count + 2;
int n = 1;
prog.Invoke(startpct);
foreach (Item action1 in ActionList)
{
if (ActionCancel)
return;

prog.Invoke(startpct + ((totPct - startpct) * (++n) / (c)));

if (!(action1 is ItemMissing action))
continue;

foreach (TorrentEntry te in downloading)
{
FileInfo file = new FileInfo(te.DownloadingTo);
if (!TVSettings.Instance.UsefulExtension(file.Extension, false)) // not a usefile file extension
continue;

//do any of the possible names for the series match the filename?
bool matched = (action.Episode.SI.GetSimplifiedPossibleShowNames().Any(name => FileHelper.SimplifyAndCheckFilename(file.FullName, name)));

if (!matched) continue;

if (TVDoc.FindSeasEp(file, out int seasF, out int epF, out int _, action.Episode.SI) && (seasF == action.Episode.AppropriateSeasonNumber) && (epF == action.Episode.AppropriateEpNum))
{
toRemove.Add(action1);
newList.Add(new ItemuTorrenting(te, action.Episode, action.TheFileNoExt));
break;
}
}
}

foreach (Item i in toRemove)
ActionList.Remove(i);

foreach (Item action in newList)
ActionList.Add(action);

prog.Invoke(totPct);
}

protected TorrentFinder(TVDoc doc) : base(doc)
{
}
}
}
52 changes: 52 additions & 0 deletions TVRename/Finders/qBitTorrentFinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

namespace TVRename
{
// ReSharper disable once InconsistentNaming
internal class qBitTorrentFinder : TorrentFinder
{
public qBitTorrentFinder(TVDoc i) : base(i) { }
public override bool Active() => TVSettings.Instance.CheckqBitTorrent;

public override void Check(SetProgressDelegate prog, int startpct, int totPct)
{
List<TorrentEntry> downloading = GetqBitTorrentDownloads();
SearchForAppropriateDownloads(prog, startpct, totPct, downloading);
}

private static List<TorrentEntry> GetqBitTorrentDownloads()
{
List < TorrentEntry > ret = new List<TorrentEntry>();

// get list of files being downloaded by qBitTorrentFinder
string host = TVSettings.Instance.qBitTorrentHost;
string port = TVSettings.Instance.qBitTorrentPort;
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(port))
return ret;

string url = $"http://{host}:{port}/query/";

JToken settings = JsonHelper.ObtainToken(url + "preferences");
JArray currentDownloads = JsonHelper.ObtainArray(url + "torrents?filter=all");

foreach (JToken torrent in currentDownloads.Children())
{
JArray stuff2 = JsonHelper.ObtainArray(url + "propertiesFiles/" + torrent["hash"]);

foreach (JToken file in stuff2.Children())
{
ret.Add(new TorrentEntry(torrent["name"].ToString(), settings["save_path"] + file["name"].ToString(), (int)(100 * file["progress"].ToObject<float>())));
}

if (!stuff2.Children().Any())
{
ret.Add(new TorrentEntry(torrent["name"].ToString(), settings["save_path"] + torrent["name"].ToString() + TVSettings.Instance.VideoExtensionsArray[0], 0));
}
}

return ret;
}
}
}
Loading

0 comments on commit ece9cb5

Please sign in to comment.