diff --git a/.editorconfig b/.editorconfig index 5e19cc2d6..624514a98 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,6 +9,35 @@ insert_final_newline = true indent_style = space indent_size = 4 +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:refactoring +dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_method = false:refactoring +dotnet_style_qualification_for_event = false:refactoring + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + [*.{js,html,js,hbs,less,css}] charset = utf-8 trim_trailing_whitespace = true diff --git a/.gitignore b/.gitignore index 304f3c8e2..eacdd16c7 100644 --- a/.gitignore +++ b/.gitignore @@ -85,7 +85,6 @@ TestResults [Tt]est[Rr]esult* *.Cache ClientBin -[Ss]tyle[Cc]op.* ~$* *.dbmdl Generated_Code #added for RIA/Silverlight projects diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 9ae001f81..16461f0e9 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ $(SolutionDir)Stylecop.ruleset - + true AnyCPU true @@ -94,7 +94,7 @@ - + all diff --git a/src/Marr.Data/Converters/BooleanYNConverter.cs b/src/Marr.Data/Converters/BooleanYNConverter.cs index 38003939c..56d047b06 100644 --- a/src/Marr.Data/Converters/BooleanYNConverter.cs +++ b/src/Marr.Data/Converters/BooleanYNConverter.cs @@ -45,7 +45,7 @@ namespace Marr.Data.Converters public object FromDB(ColumnMap map, object dbValue) { - return FromDB(new ConverterContext {ColumnMap = map, DbValue = dbValue}); + return FromDB(new ConverterContext { ColumnMap = map, DbValue = dbValue }); } public object ToDB(object clrValue) diff --git a/src/Marr.Data/Converters/CastConverter.cs b/src/Marr.Data/Converters/CastConverter.cs index 2fa3b8eca..1be77da45 100644 --- a/src/Marr.Data/Converters/CastConverter.cs +++ b/src/Marr.Data/Converters/CastConverter.cs @@ -50,4 +50,3 @@ namespace Marr.Data.Converters #endregion } } - diff --git a/src/Marr.Data/DataHelper.cs b/src/Marr.Data/DataHelper.cs index 20b5bcfe6..39113ba68 100644 --- a/src/Marr.Data/DataHelper.cs +++ b/src/Marr.Data/DataHelper.cs @@ -29,7 +29,7 @@ namespace Marr.Data { public static bool HasColumn(this IDataReader dr, string columnName) { - for (int i=0; i < dr.FieldCount; i++) + for (int i = 0; i < dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; diff --git a/src/Marr.Data/Mapping/IColumnInfo.cs b/src/Marr.Data/Mapping/IColumnInfo.cs index c8058743b..c22949c46 100644 --- a/src/Marr.Data/Mapping/IColumnInfo.cs +++ b/src/Marr.Data/Mapping/IColumnInfo.cs @@ -19,9 +19,9 @@ namespace Marr.Data.Mapping { public interface IColumnInfo { - string Name { get; set; } + string Name { get; set; } string AltName { get; set; } - int Size { get; set; } + int Size { get; set; } bool IsPrimaryKey { get; set; } bool IsAutoIncrement { get; set; } bool ReturnValue { get; set; } diff --git a/src/Marr.Data/QGen/WhereBuilder.cs b/src/Marr.Data/QGen/WhereBuilder.cs index b2573a26d..ab7ba2bec 100644 --- a/src/Marr.Data/QGen/WhereBuilder.cs +++ b/src/Marr.Data/QGen/WhereBuilder.cs @@ -167,7 +167,7 @@ namespace Marr.Data.QGen var methodExp = memberExp.Expression as MethodCallExpression; if (methodExp != null) { - var errMsg = string.Format("Function calls are not supported by the Where clause expression parser. Please evaluate your function call, '{0}', manually and then use the resulting paremeter value in your Where expression.", methodExp.Method.Name); + var errMsg = string.Format("Function calls are not supported by the Where clause expression parser. Please evaluate your function call, '{0}', manually and then use the resulting paremeter value in your Where expression.", methodExp.Method.Name); throw new NotSupportedException(errMsg); } diff --git a/src/MonoTorrent/BEncoding/BEncodedList.cs b/src/MonoTorrent/BEncoding/BEncodedList.cs index 2b1a3359a..8d59bb1ce 100644 --- a/src/MonoTorrent/BEncoding/BEncodedList.cs +++ b/src/MonoTorrent/BEncoding/BEncodedList.cs @@ -99,7 +99,7 @@ namespace MonoTorrent.BEncoding int length = 0; length += 1; // Lists start with 'l' - for (int i=0; i < this.list.Count; i++) + for (int i = 0; i < this.list.Count; i++) length += this.list[i].LengthInBytes(); length += 1; // Lists end with 'e' @@ -147,9 +147,9 @@ namespace MonoTorrent.BEncoding this.list.Add(item); } - public void AddRange (IEnumerable collection) + public void AddRange(IEnumerable collection) { - list.AddRange (collection); + list.AddRange(collection); } public void Clear() diff --git a/src/MonoTorrent/BEncoding/BEncodedNumber.cs b/src/MonoTorrent/BEncoding/BEncodedNumber.cs index 087be5aa0..6226d9f2f 100644 --- a/src/MonoTorrent/BEncoding/BEncodedNumber.cs +++ b/src/MonoTorrent/BEncoding/BEncodedNumber.cs @@ -101,16 +101,16 @@ namespace MonoTorrent.BEncoding if (reader.PeekByte() == '-') { sign = -1; - reader.ReadByte (); + reader.ReadByte(); } int letter; while (((letter = reader.PeekByte()) != -1) && letter != 'e') { - if(letter < '0' || letter > '9') + if (letter < '0' || letter > '9') throw new BEncodingException("Invalid number found."); number = number * 10 + (letter - '0'); - reader.ReadByte (); + reader.ReadByte(); } if (reader.ReadByte() != 'e') //remove the trailing 'e' throw new BEncodingException("Invalid data found. Aborting."); diff --git a/src/MonoTorrent/BEncoding/BEncodedString.cs b/src/MonoTorrent/BEncoding/BEncodedString.cs index 80958e5db..47d11b37d 100644 --- a/src/MonoTorrent/BEncoding/BEncodedString.cs +++ b/src/MonoTorrent/BEncoding/BEncodedString.cs @@ -97,7 +97,7 @@ namespace MonoTorrent.BEncoding public override int Encode(byte[] buffer, int offset) { int written = offset; - written += Message.WriteAscii(buffer, written, textBytes.Length.ToString ()); + written += Message.WriteAscii(buffer, written, textBytes.Length.ToString()); written += Message.WriteAscii(buffer, written, ":"); written += Message.Write(buffer, written, textBytes); return written - offset; @@ -144,7 +144,7 @@ namespace MonoTorrent.BEncoding int prefix = 1; // Account for ':' // Count the number of characters needed for the length prefix - for (int i = textBytes.Length; i != 0; i = i/10) + for (int i = textBytes.Length; i != 0; i = i / 10) prefix += 1; if (textBytes.Length == 0) @@ -164,7 +164,7 @@ namespace MonoTorrent.BEncoding if (other == null) return 1; - int difference=0; + int difference = 0; int length = this.textBytes.Length > other.textBytes.Length ? other.textBytes.Length : this.textBytes.Length; for (int i = 0; i < length; i++) diff --git a/src/MonoTorrent/BEncoding/IBEncodedValue.cs b/src/MonoTorrent/BEncoding/IBEncodedValue.cs index 21dfdf86a..fb05eeef9 100644 --- a/src/MonoTorrent/BEncoding/IBEncodedValue.cs +++ b/src/MonoTorrent/BEncoding/IBEncodedValue.cs @@ -32,11 +32,11 @@ namespace MonoTorrent.BEncoding /// public abstract int Encode(byte[] buffer, int offset); - public static T Clone (T value) + public static T Clone(T value) where T : BEncodedValue { - Check.Value (value); - return (T) BEncodedValue.Decode (value.Encode ()); + Check.Value(value); + return (T)BEncodedValue.Decode(value.Encode()); } /// diff --git a/src/MonoTorrent/BitField.cs b/src/MonoTorrent/BitField.cs index dc23bc626..e2e3edfce 100644 --- a/src/MonoTorrent/BitField.cs +++ b/src/MonoTorrent/BitField.cs @@ -394,7 +394,7 @@ namespace MonoTorrent v = (v & 0x33333333) + ((v >> 2) & 0x33333333); count += (((v + (v >> 4) & 0xF0F0F0F) * 0x1010101)) >> 24; } - this.trueCount = (int)count ; + this.trueCount = (int)count; } void ZeroUnusedBits() diff --git a/src/MonoTorrent/Check.cs b/src/MonoTorrent/Check.cs index c6a14fd59..3a4ded6ff 100644 --- a/src/MonoTorrent/Check.cs +++ b/src/MonoTorrent/Check.cs @@ -62,9 +62,9 @@ namespace MonoTorrent DoCheck(data, "data"); } - public static void Destination (object destination) + public static void Destination(object destination) { - DoCheck (destination, "destination"); + DoCheck(destination, "destination"); } public static void Endpoint(object endpoint) @@ -92,9 +92,9 @@ namespace MonoTorrent DoCheck(infoHash, "infoHash"); } - public static void Key (object key) + public static void Key(object key) { - DoCheck (key, "key"); + DoCheck(key, "key"); } public static void Limiter(object limiter) @@ -122,9 +122,9 @@ namespace MonoTorrent DoCheck(manager, "manager"); } - public static void Mappings (object mappings) + public static void Mappings(object mappings) { - DoCheck (mappings, "mappings"); + DoCheck(mappings, "mappings"); } public static void Metadata(object metadata) @@ -132,9 +132,9 @@ namespace MonoTorrent DoCheck(metadata, "metadata"); } - public static void Name (object name) + public static void Name(object name) { - DoCheck (name, "name"); + DoCheck(name, "name"); } public static void Path(object path) @@ -142,9 +142,9 @@ namespace MonoTorrent DoCheck(path, "path"); } - public static void Paths (object paths) + public static void Paths(object paths) { - DoCheck (paths, "paths"); + DoCheck(paths, "paths"); } public static void PathNotEmpty(string path) @@ -152,14 +152,14 @@ namespace MonoTorrent IsNullOrEmpty(path, "path"); } - public static void Peer (object peer) + public static void Peer(object peer) { - DoCheck (peer, "peer"); + DoCheck(peer, "peer"); } - public static void Peers (object peers) + public static void Peers(object peers) { - DoCheck (peers, "peers"); + DoCheck(peers, "peers"); } public static void Picker(object picker) diff --git a/src/MonoTorrent/InfoHash.cs b/src/MonoTorrent/InfoHash.cs index e87101909..c44076ccb 100644 --- a/src/MonoTorrent/InfoHash.cs +++ b/src/MonoTorrent/InfoHash.cs @@ -4,7 +4,7 @@ using System.Text; namespace MonoTorrent { - public class InfoHash : IEquatable + public class InfoHash : IEquatable { static Dictionary base32DecodeTable; @@ -97,24 +97,25 @@ namespace MonoTorrent public static InfoHash FromBase32(string infoHash) { - Check.InfoHash (infoHash); + Check.InfoHash(infoHash); if (infoHash.Length != 32) throw new ArgumentException("Infohash must be a base32 encoded 32 character string"); infoHash = infoHash.ToLower(); - int infohashOffset =0 ; + int infohashOffset = 0; byte[] hash = new byte[20]; var temp = new byte[8]; - for (int i = 0; i < hash.Length; ) { - for (int j=0; j < 8; j++) + for (int i = 0; i < hash.Length;) + { + for (int j = 0; j < 8; j++) if (!base32DecodeTable.TryGetValue(infoHash[infohashOffset++], out temp[j])) - throw new ArgumentException ("infoHash", "Value is not a valid base32 encoded string"); + throw new ArgumentException("infoHash", "Value is not a valid base32 encoded string"); //8 * 5bits = 40 bits = 5 bytes - hash[i++] = (byte)((temp[0] << 3) | (temp [1]>> 2)); + hash[i++] = (byte)((temp[0] << 3) | (temp[1] >> 2)); hash[i++] = (byte)((temp[1] << 6) | (temp[2] << 1) | (temp[3] >> 4)); - hash[i++] = (byte)((temp[3] << 4) | (temp [4]>> 1)); - hash[i++] = (byte)((temp[4] << 7) | (temp[5] << 2) | (temp [6]>> 3)); + hash[i++] = (byte)((temp[3] << 4) | (temp[4] >> 1)); + hash[i++] = (byte)((temp[4] << 7) | (temp[5] << 2) | (temp[6] >> 3)); hash[i++] = (byte)((temp[6] << 5) | temp[7]); } @@ -123,7 +124,7 @@ namespace MonoTorrent public static InfoHash FromHex(string infoHash) { - Check.InfoHash (infoHash); + Check.InfoHash(infoHash); if (infoHash.Length != 40) throw new ArgumentException("Infohash must be 40 characters long"); diff --git a/src/MonoTorrent/MagnetLink.cs b/src/MonoTorrent/MagnetLink.cs index 1ee56c4c8..f5a6ea5c7 100644 --- a/src/MonoTorrent/MagnetLink.cs +++ b/src/MonoTorrent/MagnetLink.cs @@ -7,87 +7,91 @@ namespace MonoTorrent { public class MagnetLink { - public RawTrackerTier AnnounceUrls { - get; private set; - } - - public InfoHash InfoHash { - get; private set; - } - - public string Name { - get; private set; - } - - public List Webseeds { - get; private set; - } - - public MagnetLink (string url) + public RawTrackerTier AnnounceUrls { - Check.Url (url); - AnnounceUrls = new RawTrackerTier (); - Webseeds = new List (); - - ParseMagnetLink (url); + get; private set; } - void ParseMagnetLink (string url) + public InfoHash InfoHash { - string[] splitStr = url.Split ('?'); + get; private set; + } + + public string Name + { + get; private set; + } + + public List Webseeds + { + get; private set; + } + + public MagnetLink(string url) + { + Check.Url(url); + AnnounceUrls = new RawTrackerTier(); + Webseeds = new List(); + + ParseMagnetLink(url); + } + + void ParseMagnetLink(string url) + { + string[] splitStr = url.Split('?'); if (splitStr.Length == 0 || splitStr[0] != "magnet:") - throw new FormatException ("The magnet link must start with 'magnet:?'."); + throw new FormatException("The magnet link must start with 'magnet:?'."); if (splitStr.Length == 1) return;//no parametter - string[] parameters = splitStr[1].Split ('&', ';'); + string[] parameters = splitStr[1].Split('&', ';'); - for (int i = 0; i < parameters.Length ; i++) + for (int i = 0; i < parameters.Length; i++) { - string[] keyval = parameters[i].Split ('='); + string[] keyval = parameters[i].Split('='); if (keyval.Length != 2) - throw new FormatException ("A field-value pair of the magnet link contain more than one equal'."); + throw new FormatException("A field-value pair of the magnet link contain more than one equal'."); switch (keyval[0].Substring(0, 2)) { case "xt"://exact topic if (InfoHash != null) - throw new FormatException ("More than one infohash in magnet link is not allowed."); + throw new FormatException("More than one infohash in magnet link is not allowed."); string val = keyval[1].Substring(9); switch (keyval[1].Substring(0, 9)) { case "urn:sha1:"://base32 hash case "urn:btih:": - if (val.Length == 32) - InfoHash = InfoHash.FromBase32 (val); - else if (val.Length == 40) - InfoHash = InfoHash.FromHex (val); - else - throw new FormatException("Infohash must be base32 or hex encoded."); - break; + if (val.Length == 32) + InfoHash = InfoHash.FromBase32(val); + else if (val.Length == 40) + InfoHash = InfoHash.FromHex(val); + else + throw new FormatException("Infohash must be base32 or hex encoded."); + break; } - break; - case "tr" ://address tracker + break; + case "tr"://address tracker var bytes = UriHelper.UrlDecode(keyval[1]); AnnounceUrls.Add(Encoding.UTF8.GetString(bytes)); - break; + break; case "as"://Acceptable Source - Webseeds.Add (keyval[1]); - break; + Webseeds.Add(keyval[1]); + break; case "dn"://display name var name = UriHelper.UrlDecode(keyval[1]); Name = Encoding.UTF8.GetString(name); - break; + break; case "xl"://exact length case "xs":// eXact Source - P2P link. case "kt"://keyword topic case "mt"://manifest topic - //not supported for moment - break; + //not supported for moment + break; default: //not supported - break; + break; } } } diff --git a/src/MonoTorrent/Messages/IMessage.cs b/src/MonoTorrent/Messages/IMessage.cs index 62512b6c7..e1363cdd5 100644 --- a/src/MonoTorrent/Messages/IMessage.cs +++ b/src/MonoTorrent/Messages/IMessage.cs @@ -2,7 +2,7 @@ namespace MonoTorrent.Messages { interface IMessage { - int ByteLength { get;} + int ByteLength { get; } byte[] Encode(); int Encode(byte[] buffer, int offset); diff --git a/src/MonoTorrent/RawTrackerTier.cs b/src/MonoTorrent/RawTrackerTier.cs index c8efaba74..db024efc9 100644 --- a/src/MonoTorrent/RawTrackerTier.cs +++ b/src/MonoTorrent/RawTrackerTier.cs @@ -7,90 +7,94 @@ namespace MonoTorrent { public class RawTrackerTier : IList { - public string this[int index] { - get { return ((BEncodedString) Tier [index]).Text; } - set { Tier [index] = new BEncodedString (value );} + public string this[int index] + { + get { return ((BEncodedString)Tier[index]).Text; } + set { Tier[index] = new BEncodedString(value); } } - internal BEncodedList Tier { + internal BEncodedList Tier + { get; set; } - public RawTrackerTier () - : this (new BEncodedList ()) + public RawTrackerTier() + : this(new BEncodedList()) { } - public RawTrackerTier (BEncodedList tier) + public RawTrackerTier(BEncodedList tier) { Tier = tier; } - public RawTrackerTier (IEnumerable announces) - : this () + public RawTrackerTier(IEnumerable announces) + : this() { foreach (var v in announces) - Add (v); + Add(v); } - public int IndexOf (string item) + public int IndexOf(string item) { - return Tier.IndexOf ((BEncodedString) item); + return Tier.IndexOf((BEncodedString)item); } - public void Insert (int index, string item) + public void Insert(int index, string item) { - Tier.Insert (index, (BEncodedString) item); + Tier.Insert(index, (BEncodedString)item); } - public void RemoveAt (int index) + public void RemoveAt(int index) { - Tier.RemoveAt (index); + Tier.RemoveAt(index); } - public void Add (string item) + public void Add(string item) { - Tier.Add ((BEncodedString) item); + Tier.Add((BEncodedString)item); } - public void Clear () + public void Clear() { - Tier.Clear (); + Tier.Clear(); } - public bool Contains (string item) + public bool Contains(string item) { - return Tier.Contains ((BEncodedString) item); + return Tier.Contains((BEncodedString)item); } - public void CopyTo (string[] array, int arrayIndex) + public void CopyTo(string[] array, int arrayIndex) { foreach (var s in this) - array [arrayIndex ++] = s; + array[arrayIndex++] = s; } - public bool Remove (string item) + public bool Remove(string item) { - return Tier.Remove ((BEncodedString) item); + return Tier.Remove((BEncodedString)item); } - public int Count { + public int Count + { get { return Tier.Count; } } - public bool IsReadOnly { + public bool IsReadOnly + { get { return Tier.IsReadOnly; } } - public IEnumerator GetEnumerator () + public IEnumerator GetEnumerator() { foreach (BEncodedString v in Tier) yield return v.Text; } - IEnumerator IEnumerable.GetEnumerator () + IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator (); + return GetEnumerator(); } } } diff --git a/src/MonoTorrent/RawTrackerTiers.cs b/src/MonoTorrent/RawTrackerTiers.cs index a393318c0..af5120faa 100644 --- a/src/MonoTorrent/RawTrackerTiers.cs +++ b/src/MonoTorrent/RawTrackerTiers.cs @@ -7,98 +7,103 @@ namespace MonoTorrent { public class RawTrackerTiers : IList { - BEncodedList Tiers { + BEncodedList Tiers + { get; set; } - public RawTrackerTiers () - : this (new BEncodedList ()) + public RawTrackerTiers() + : this(new BEncodedList()) { } - public RawTrackerTiers (BEncodedList tiers) + public RawTrackerTiers(BEncodedList tiers) { Tiers = tiers; } - public int IndexOf (RawTrackerTier item) + public int IndexOf(RawTrackerTier item) { - if (item != null) { + if (item != null) + { for (int i = 0; i < Tiers.Count; i++) - if (item.Tier == Tiers [i]) + if (item.Tier == Tiers[i]) return i; } return -1; } - public void Insert (int index, RawTrackerTier item) + public void Insert(int index, RawTrackerTier item) { - Tiers.Insert (index, item.Tier); + Tiers.Insert(index, item.Tier); } - public void RemoveAt (int index) + public void RemoveAt(int index) { - Tiers.RemoveAt (index); + Tiers.RemoveAt(index); } - public RawTrackerTier this[int index] { - get { return new RawTrackerTier ((BEncodedList) Tiers [index]); } - set { Tiers [index] = value.Tier; } - } - - public void Add (RawTrackerTier item) + public RawTrackerTier this[int index] { - Tiers.Add (item.Tier); + get { return new RawTrackerTier((BEncodedList)Tiers[index]); } + set { Tiers[index] = value.Tier; } } - public void AddRange (IEnumerable tiers) + public void Add(RawTrackerTier item) + { + Tiers.Add(item.Tier); + } + + public void AddRange(IEnumerable tiers) { foreach (var v in tiers) - Add (v); + Add(v); } - public void Clear () + public void Clear() { - Tiers.Clear (); + Tiers.Clear(); } - public bool Contains (RawTrackerTier item) + public bool Contains(RawTrackerTier item) { - return IndexOf (item) != -1; + return IndexOf(item) != -1; } - public void CopyTo (RawTrackerTier[] array, int arrayIndex) + public void CopyTo(RawTrackerTier[] array, int arrayIndex) { foreach (var v in this) - array [arrayIndex ++] = v; + array[arrayIndex++] = v; } - public bool Remove (RawTrackerTier item) + public bool Remove(RawTrackerTier item) { - int index = IndexOf (item); + int index = IndexOf(item); if (index != -1) - RemoveAt (index); + RemoveAt(index); return index != -1; } - public int Count { + public int Count + { get { return Tiers.Count; } } - public bool IsReadOnly { + public bool IsReadOnly + { get { return Tiers.IsReadOnly; } } - public IEnumerator GetEnumerator () + public IEnumerator GetEnumerator() { foreach (var v in Tiers) - yield return new RawTrackerTier ((BEncodedList) v); + yield return new RawTrackerTier((BEncodedList)v); } - IEnumerator IEnumerable.GetEnumerator () + IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator (); + return GetEnumerator(); } } } diff --git a/src/MonoTorrent/ToolBox.cs b/src/MonoTorrent/ToolBox.cs index 390f1e5bf..2dfe261ba 100644 --- a/src/MonoTorrent/ToolBox.cs +++ b/src/MonoTorrent/ToolBox.cs @@ -36,7 +36,8 @@ namespace MonoTorrent if (e == null) return; - ThreadPool.QueueUserWorkItem(delegate { + ThreadPool.QueueUserWorkItem(delegate + { if (e != null) e(o, args); }); diff --git a/src/MonoTorrent/Torrent.cs b/src/MonoTorrent/Torrent.cs index 481051cfb..35f4ba1bd 100644 --- a/src/MonoTorrent/Torrent.cs +++ b/src/MonoTorrent/Torrent.cs @@ -263,7 +263,7 @@ namespace MonoTorrent protected Torrent() { - this.announceUrls = new RawTrackerTiers (); + this.announceUrls = new RawTrackerTiers(); this.comment = string.Empty; this.createdBy = string.Empty; this.creationDate = new DateTime(1970, 1, 1, 0, 0, 0); @@ -298,15 +298,15 @@ namespace MonoTorrent return this.infoHash.GetHashCode(); } - internal byte [] ToBytes () + internal byte[] ToBytes() { - return this.originalDictionary.Encode (); + return this.originalDictionary.Encode(); } - internal BEncodedDictionary ToDictionary () + internal BEncodedDictionary ToDictionary() { // Give the user a copy of the original dictionary. - return BEncodedValue.Clone (this.originalDictionary); + return BEncodedValue.Clone(this.originalDictionary); } public override string ToString() @@ -423,7 +423,7 @@ namespace MonoTorrent else { startIndex = (int)(this.size / this.pieceLength); - endIndex = (int)((this.size + length) / this.pieceLength); + endIndex = (int)((this.size + length) / this.pieceLength); if ((this.size + length) % this.pieceLength == 0) endIndex--; } @@ -702,7 +702,7 @@ namespace MonoTorrent try { - Torrent t = Torrent.LoadCore ((BEncodedDictionary) BEncodedDictionary.Decode(stream)); + Torrent t = Torrent.LoadCore((BEncodedDictionary)BEncodedDictionary.Decode(stream)); t.torrentPath = path; return t; } @@ -714,7 +714,7 @@ namespace MonoTorrent public static Torrent Load(BEncodedDictionary torrentInformation) { - return LoadCore ((BEncodedDictionary)BEncodedValue.Decode (torrentInformation.Encode ())); + return LoadCore((BEncodedDictionary)BEncodedValue.Decode(torrentInformation.Encode())); } internal static Torrent LoadCore(BEncodedDictionary torrentInformation) @@ -743,7 +743,7 @@ namespace MonoTorrent // Ignore this if we have an announce-list if (torrentInformation.ContainsKey("announce-list")) break; - this.announceUrls.Add(new RawTrackerTier ()); + this.announceUrls.Add(new RawTrackerTier()); this.announceUrls[0].Add(keypair.Value.ToString()); break; @@ -811,7 +811,7 @@ namespace MonoTorrent case ("info"): using (SHA1 s = HashAlgoFactory.Create()) - this.infoHash = new InfoHash (s.ComputeHash(keypair.Value.Encode())); + this.infoHash = new InfoHash(s.ComputeHash(keypair.Value.Encode())); this.ProcessInfo(((BEncodedDictionary)keypair.Value)); break; @@ -835,7 +835,7 @@ namespace MonoTorrent Toolbox.Randomize(tier); - RawTrackerTier collection = new RawTrackerTier (); + RawTrackerTier collection = new RawTrackerTier(); for (int k = 0; k < tier.Count; k++) collection.Add(tier[k]); diff --git a/src/MonoTorrent/TorrentFile.cs b/src/MonoTorrent/TorrentFile.cs index 27fc00613..b6deb91a7 100644 --- a/src/MonoTorrent/TorrentFile.cs +++ b/src/MonoTorrent/TorrentFile.cs @@ -125,14 +125,14 @@ namespace MonoTorrent } - public TorrentFile (string path, long length, string fullPath) - : this (path, length, fullPath, 0, 0) + public TorrentFile(string path, long length, string fullPath) + : this(path, length, fullPath, 0, 0) { } - public TorrentFile (string path, long length, int startIndex, int endIndex) - : this (path, length, path, startIndex, endIndex) + public TorrentFile(string path, long length, int startIndex, int endIndex) + : this(path, length, path, startIndex, endIndex) { } diff --git a/src/MonoTorrent/UriHelper.cs b/src/MonoTorrent/UriHelper.cs index d806e596a..b4cced9ec 100644 --- a/src/MonoTorrent/UriHelper.cs +++ b/src/MonoTorrent/UriHelper.cs @@ -14,105 +14,121 @@ namespace MonoTorrent { static class UriHelper { - static readonly char [] hexChars = "0123456789abcdef".ToCharArray (); + static readonly char[] hexChars = "0123456789abcdef".ToCharArray(); - public static string UrlEncode (byte[] bytes) + public static string UrlEncode(byte[] bytes) { if (bytes == null) - throw new ArgumentNullException ("bytes"); + throw new ArgumentNullException("bytes"); - var result = new MemoryStream (bytes.Length); + var result = new MemoryStream(bytes.Length); for (int i = 0; i < bytes.Length; i++) - UrlEncodeChar ((char)bytes [i], result, false); + UrlEncodeChar((char)bytes[i], result, false); - return Encoding.ASCII.GetString (result.ToArray()); + return Encoding.ASCII.GetString(result.ToArray()); } - public static byte [] UrlDecode (string s) + public static byte[] UrlDecode(string s) { if (null == s) return null; var e = Encoding.UTF8; - if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1) - return e.GetBytes (s); + if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) + return e.GetBytes(s); long len = s.Length; - var bytes = new List (); + var bytes = new List(); int xchar; char ch; - for (int i = 0; i < len; i++) { - ch = s [i]; - if (ch == '%' && i + 2 < len && s [i + 1] != '%') { - if (s [i + 1] == 'u' && i + 5 < len) { + for (int i = 0; i < len; i++) + { + ch = s[i]; + if (ch == '%' && i + 2 < len && s[i + 1] != '%') + { + if (s[i + 1] == 'u' && i + 5 < len) + { // unicode hex sequence - xchar = GetChar (s, i + 2, 4); - if (xchar != -1) { - WriteCharBytes (bytes, (char)xchar, e); + xchar = GetChar(s, i + 2, 4); + if (xchar != -1) + { + WriteCharBytes(bytes, (char)xchar, e); i += 5; - } else - WriteCharBytes (bytes, '%', e); - } else if ((xchar = GetChar (s, i + 1, 2)) != -1) { - WriteCharBytes (bytes, (char)xchar, e); + } + else + WriteCharBytes(bytes, '%', e); + } + else if ((xchar = GetChar(s, i + 1, 2)) != -1) + { + WriteCharBytes(bytes, (char)xchar, e); i += 2; - } else { - WriteCharBytes (bytes, '%', e); + } + else + { + WriteCharBytes(bytes, '%', e); } continue; } if (ch == '+') - WriteCharBytes (bytes, ' ', e); + WriteCharBytes(bytes, ' ', e); else - WriteCharBytes (bytes, ch, e); + WriteCharBytes(bytes, ch, e); } - return bytes.ToArray (); + return bytes.ToArray(); } - static void UrlEncodeChar (char c, Stream result, bool isUnicode) { - if (c > ' ' && NotEncoded (c)) { - result.WriteByte ((byte)c); + static void UrlEncodeChar(char c, Stream result, bool isUnicode) + { + if (c > ' ' && NotEncoded(c)) + { + result.WriteByte((byte)c); return; } - if (c==' ') { - result.WriteByte ((byte)'+'); + if (c == ' ') + { + result.WriteByte((byte)'+'); return; } - if ( (c < '0') || + if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || - (c > 'z')) { - if (isUnicode && c > 127) { - result.WriteByte ((byte)'%'); - result.WriteByte ((byte)'u'); - result.WriteByte ((byte)'0'); - result.WriteByte ((byte)'0'); + (c > 'z')) + { + if (isUnicode && c > 127) + { + result.WriteByte((byte)'%'); + result.WriteByte((byte)'u'); + result.WriteByte((byte)'0'); + result.WriteByte((byte)'0'); } else - result.WriteByte ((byte)'%'); + result.WriteByte((byte)'%'); - int idx = ((int) c) >> 4; - result.WriteByte ((byte)hexChars [idx]); - idx = ((int) c) & 0x0F; - result.WriteByte ((byte)hexChars [idx]); + int idx = ((int)c) >> 4; + result.WriteByte((byte)hexChars[idx]); + idx = ((int)c) & 0x0F; + result.WriteByte((byte)hexChars[idx]); } - else { - result.WriteByte ((byte)c); + else + { + result.WriteByte((byte)c); } } - static int GetChar (string str, int offset, int length) + static int GetChar(string str, int offset, int length) { int val = 0; int end = length + offset; - for (int i = offset; i < end; i++) { - char c = str [i]; + for (int i = offset; i < end; i++) + { + char c = str[i]; if (c > 127) return -1; - int current = GetInt ((byte) c); + int current = GetInt((byte)c); if (current == -1) return -1; val = (val << 4) + current; @@ -121,9 +137,9 @@ namespace MonoTorrent return val; } - static int GetInt (byte b) + static int GetInt(byte b) { - char c = (char) b; + char c = (char)b; if (c >= '0' && c <= '9') return c - '0'; @@ -136,18 +152,20 @@ namespace MonoTorrent return -1; } - static bool NotEncoded (char c) + static bool NotEncoded(char c) { return c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_' || c == '\''; } - static void WriteCharBytes (List buf, char ch, Encoding e) + static void WriteCharBytes(List buf, char ch, Encoding e) { - if (ch > 255) { - foreach (byte b in e.GetBytes (new char[] { ch })) - buf.Add (b); - } else - buf.Add ((byte)ch); + if (ch > 255) + { + foreach (byte b in e.GetBytes(new char[] { ch })) + buf.Add(b); + } + else + buf.Add((byte)ch); } } } diff --git a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs index 24aee8f5e..5122239b3 100644 --- a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs +++ b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs @@ -1,8 +1,8 @@ using FluentAssertions; using NUnit.Framework; -using Radarr.Http.ClientSchema; using NzbDrone.Core.Annotations; using NzbDrone.Test.Common; +using Radarr.Http.ClientSchema; namespace NzbDrone.Api.Test.ClientSchemaTests { @@ -16,25 +16,22 @@ namespace NzbDrone.Api.Test.ClientSchemaTests schema.Should().HaveCount(2); } - [Test] public void schema_should_have_proper_fields() { var model = new TestModel - { - FirstName = "Bob", - LastName = "Poop" - }; + { + FirstName = "Bob", + LastName = "Poop" + }; var schema = SchemaBuilder.ToSchema(model); - schema.Should().Contain(c => c.Order == 1 && c.Name == "lastName" && c.Label == "Last Name" && c.HelpText == "Your Last Name" && (string) c.Value == "Poop"); - schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string) c.Value == "Bob"); + schema.Should().Contain(c => c.Order == 1 && c.Name == "lastName" && c.Label == "Last Name" && c.HelpText == "Your Last Name" && (string)c.Value == "Poop"); + schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string)c.Value == "Bob"); } - } - public class TestModel { [FieldDefinition(0, Label = "First Name", HelpText = "Your First Name")] diff --git a/src/NzbDrone.Api/Blacklist/BlacklistResource.cs b/src/NzbDrone.Api/Blacklist/BlacklistResource.cs index acb6484e6..b17e140fe 100644 --- a/src/NzbDrone.Api/Blacklist/BlacklistResource.cs +++ b/src/NzbDrone.Api/Blacklist/BlacklistResource.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using NzbDrone.Api.Movies; -using Radarr.Http.REST; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Blacklist { @@ -25,7 +25,10 @@ namespace NzbDrone.Api.Blacklist { public static BlacklistResource MapToResource(this Core.Blacklisting.Blacklist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new BlacklistResource { diff --git a/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs b/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs index 5342fdaee..7e05403f6 100644 --- a/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs +++ b/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs @@ -1,4 +1,3 @@ -using Nancy; using System; using System.Collections.Generic; using System.Linq; @@ -6,10 +5,11 @@ using Ical.Net; using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; -using NzbDrone.Core.Movies; +using Nancy; using Nancy.Responses; -using NzbDrone.Core.Tags; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Tags; namespace NzbDrone.Api.Calendar { @@ -24,9 +24,9 @@ namespace NzbDrone.Api.Calendar _movieService = movieService; _tagService = tagService; - Get("/NzbDrone.ics", options => GetCalendarFeed()); - Get("/Sonarr.ics", options => GetCalendarFeed()); - Get("/Radarr.ics", options => GetCalendarFeed()); + Get("/NzbDrone.ics", options => GetCalendarFeed()); + Get("/Sonarr.ics", options => GetCalendarFeed()); + Get("/Radarr.ics", options => GetCalendarFeed()); } private object GetCalendarFeed() @@ -36,6 +36,7 @@ namespace NzbDrone.Api.Calendar var start = DateTime.Today.AddDays(-pastDays); var end = DateTime.Today.AddDays(futureDays); var unmonitored = false; + //var premiersOnly = false; var tags = new List(); @@ -45,11 +46,19 @@ namespace NzbDrone.Api.Calendar var queryPastDays = Request.Query.PastDays; var queryFutureDays = Request.Query.FutureDays; var queryUnmonitored = Request.Query.Unmonitored; + // var queryPremiersOnly = Request.Query.PremiersOnly; var queryTags = Request.Query.Tags; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } if (queryPastDays.HasValue) { @@ -72,7 +81,6 @@ namespace NzbDrone.Api.Calendar //{ // premiersOnly = bool.Parse(queryPremiersOnly.Value); //} - if (queryTags.HasValue) { var tagInput = (string)queryTags.Value.ToString(); @@ -98,10 +106,9 @@ namespace NzbDrone.Api.Calendar CreateEvent(calendar, movie, true); CreateEvent(calendar, movie, false); - } - var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); + var serializer = (IStringSerializer)new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); var icalendar = serializer.SerializeToString(calendar); return new TextResponse(icalendar, "text/calendar"); diff --git a/src/NzbDrone.Api/Calendar/CalendarModule.cs b/src/NzbDrone.Api/Calendar/CalendarModule.cs index a0d12195f..db3e46e8e 100644 --- a/src/NzbDrone.Api/Calendar/CalendarModule.cs +++ b/src/NzbDrone.Api/Calendar/CalendarModule.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Api.Calendar IMapCoversToLocal coverMapper) : base(signalR, "calendar") { - _moviesService = moviesService; _coverMapper = coverMapper; @@ -37,9 +36,20 @@ namespace NzbDrone.Api.Calendar var queryEnd = Request.Query.End; var queryIncludeUnmonitored = Request.Query.Unmonitored; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); - if (queryIncludeUnmonitored.HasValue) includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } + + if (queryIncludeUnmonitored.HasValue) + { + includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + } var resources = _moviesService.GetMoviesBetweenDates(start, end, includeUnmonitored).Select(MapToResource); @@ -48,7 +58,10 @@ namespace NzbDrone.Api.Calendar protected MovieResource MapToResource(Movie movie) { - if (movie == null) return null; + if (movie == null) + { + return null; + } var resource = movie.ToResource(); diff --git a/src/NzbDrone.Api/Commands/CommandModule.cs b/src/NzbDrone.Api/Commands/CommandModule.cs index 1fb7781e5..6a81fbf14 100644 --- a/src/NzbDrone.Api/Commands/CommandModule.cs +++ b/src/NzbDrone.Api/Commands/CommandModule.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; using NLog; -using Radarr.Http.Extensions; -using Radarr.Http.Validation; using NzbDrone.Common; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Messaging.Commands; @@ -11,7 +9,8 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ProgressMessaging; using NzbDrone.SignalR; using Radarr.Http; - +using Radarr.Http.Extensions; +using Radarr.Http.Validation; namespace NzbDrone.Api.Commands { diff --git a/src/NzbDrone.Api/Commands/CommandResource.cs b/src/NzbDrone.Api/Commands/CommandResource.cs index 29a72ebe4..82d97ae7a 100644 --- a/src/NzbDrone.Api/Commands/CommandResource.cs +++ b/src/NzbDrone.Api/Commands/CommandResource.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; using NzbDrone.Core.Messaging.Commands; +using Radarr.Http.REST; namespace NzbDrone.Api.Commands { @@ -27,30 +27,21 @@ namespace NzbDrone.Api.Commands //Legacy public CommandStatus State { - get - { - return Status; - } + get { return Status; } set { } } public bool Manual { - get - { - return Trigger == CommandTrigger.Manual; - } + get { return Trigger == CommandTrigger.Manual; } set { } } public DateTime StartedOn { - get - { - return Queued; - } + get { return Queued; } set { } } @@ -59,37 +50,51 @@ namespace NzbDrone.Api.Commands { get { - - if (Started.HasValue) return Started.Value; + if (Started.HasValue) + { + return Started.Value; + } return Ended; } - set { } + set + { + } } public bool SendUpdatesToClient { get { - if (Body != null) return (Body as Command).SendUpdatesToClient; + if (Body != null) + { + return (Body as Command).SendUpdatesToClient; + } return false; } - set { } + set + { + } } public bool UpdateScheduledTask { get { - if (Body != null) return (Body as Command).UpdateScheduledTask; + if (Body != null) + { + return (Body as Command).UpdateScheduledTask; + } return false; } - set { } + set + { + } } public DateTime? LastExecutionTime { get; set; } @@ -99,7 +104,10 @@ namespace NzbDrone.Api.Commands { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs b/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs index 93afc5dd5..416242950 100644 --- a/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs +++ b/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Api.Config public DownloadClientConfigModule(IConfigService configService) : base(configService) { - } protected override DownloadClientConfigResource ToResource(IConfigService model) diff --git a/src/NzbDrone.Api/Config/DownloadClientConfigResource.cs b/src/NzbDrone.Api/Config/DownloadClientConfigResource.cs index cd7430817..32e7ec67c 100644 --- a/src/NzbDrone.Api/Config/DownloadClientConfigResource.cs +++ b/src/NzbDrone.Api/Config/DownloadClientConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/HostConfigResource.cs b/src/NzbDrone.Api/Config/HostConfigResource.cs index 048dd4ad8..32b72473f 100644 --- a/src/NzbDrone.Api/Config/HostConfigResource.cs +++ b/src/NzbDrone.Api/Config/HostConfigResource.cs @@ -1,8 +1,8 @@ -using Radarr.Http.REST; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; using NzbDrone.Core.Update; -using NzbDrone.Common.Http.Proxy; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { @@ -54,6 +54,7 @@ namespace NzbDrone.Api.Config LaunchBrowser = model.LaunchBrowser, AuthenticationMethod = model.AuthenticationMethod, AnalyticsEnabled = model.AnalyticsEnabled, + //Username //Password LogLevel = model.LogLevel, diff --git a/src/NzbDrone.Api/Config/IndexerConfigModule.cs b/src/NzbDrone.Api/Config/IndexerConfigModule.cs index 7c80ef1a9..44df715db 100644 --- a/src/NzbDrone.Api/Config/IndexerConfigModule.cs +++ b/src/NzbDrone.Api/Config/IndexerConfigModule.cs @@ -1,12 +1,11 @@ using FluentValidation; -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace NzbDrone.Api.Config { public class IndexerConfigModule : NzbDroneConfigModule { - public IndexerConfigModule(IConfigService configService) : base(configService) { diff --git a/src/NzbDrone.Api/Config/IndexerConfigResource.cs b/src/NzbDrone.Api/Config/IndexerConfigResource.cs index 71264e988..80d9f4758 100644 --- a/src/NzbDrone.Api/Config/IndexerConfigResource.cs +++ b/src/NzbDrone.Api/Config/IndexerConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs b/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs index 53e03e87e..534cda2d6 100644 --- a/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs +++ b/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/NamingConfigModule.cs b/src/NzbDrone.Api/Config/NamingConfigModule.cs index 8047eed0f..60b486d63 100644 --- a/src/NzbDrone.Api/Config/NamingConfigModule.cs +++ b/src/NzbDrone.Api/Config/NamingConfigModule.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; +using Nancy.ModelBinding; using NzbDrone.Common.Extensions; using NzbDrone.Core.Organizer; -using Nancy.ModelBinding; using Radarr.Http; namespace NzbDrone.Api.Config @@ -30,7 +30,7 @@ namespace NzbDrone.Api.Config GetResourceById = GetNamingConfig; UpdateResource = UpdateNamingConfig; - Get("/samples", x => GetExamples(this.Bind())); + Get("/samples", x => GetExamples(this.Bind())); SharedValidator.RuleFor(c => c.MultiEpisodeStyle).InclusiveBetween(0, 5); SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat(); @@ -87,11 +87,9 @@ namespace NzbDrone.Api.Config var movieSampleResult = _filenameSampleService.GetMovieSample(nameSpec); //var standardMovieValidationResult = _filenameValidationService.ValidateMovieFilename(movieSampleResult); For now, let's hope the user is not stupid enough :/ - var validationFailures = new List(); //validationFailures.AddIfNotNull(standardMovieValidationResult); - if (validationFailures.Any()) { throw new ValidationException(validationFailures.DistinctBy(v => v.PropertyName).ToArray()); diff --git a/src/NzbDrone.Api/Config/NamingConfigResource.cs b/src/NzbDrone.Api/Config/NamingConfigResource.cs index 131f6459c..b6e4a5352 100644 --- a/src/NzbDrone.Api/Config/NamingConfigResource.cs +++ b/src/NzbDrone.Api/Config/NamingConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Organizer; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { @@ -33,6 +33,7 @@ namespace NzbDrone.Api.Config MultiEpisodeStyle = model.MultiEpisodeStyle, StandardMovieFormat = model.StandardMovieFormat, MovieFolderFormat = model.MovieFolderFormat + //IncludeSeriesTitle //IncludeEpisodeTitle //IncludeQuality diff --git a/src/NzbDrone.Api/Config/NetImportConfigModule.cs b/src/NzbDrone.Api/Config/NetImportConfigModule.cs index 5925595e8..3c1ce926c 100644 --- a/src/NzbDrone.Api/Config/NetImportConfigModule.cs +++ b/src/NzbDrone.Api/Config/NetImportConfigModule.cs @@ -1,11 +1,10 @@ -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace NzbDrone.Api.Config { public class NetImportConfigModule : NzbDroneConfigModule { - public NetImportConfigModule(IConfigService configService) : base(configService) { diff --git a/src/NzbDrone.Api/Config/NetImportConfigResource.cs b/src/NzbDrone.Api/Config/NetImportConfigResource.cs index 6a5dc48da..dba6ec52f 100644 --- a/src/NzbDrone.Api/Config/NetImportConfigResource.cs +++ b/src/NzbDrone.Api/Config/NetImportConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs b/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs index acc29f8bf..c17e5e72a 100644 --- a/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs +++ b/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs @@ -1,12 +1,13 @@ using System.Linq; using System.Reflection; +using NzbDrone.Core.Configuration; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Configuration; namespace NzbDrone.Api.Config { - public abstract class NzbDroneConfigModule : RadarrRestModule where TResource : RestResource, new() + public abstract class NzbDroneConfigModule : RadarrRestModule + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ namespace NzbDrone.Api.Config { } - protected NzbDroneConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected NzbDroneConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/NzbDrone.Api/Config/UiConfigModule.cs b/src/NzbDrone.Api/Config/UiConfigModule.cs index 9beadc091..1c4021782 100644 --- a/src/NzbDrone.Api/Config/UiConfigModule.cs +++ b/src/NzbDrone.Api/Config/UiConfigModule.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Api.Config public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) diff --git a/src/NzbDrone.Api/Config/UiConfigResource.cs b/src/NzbDrone.Api/Config/UiConfigResource.cs index d6b1b7dc3..559787e38 100644 --- a/src/NzbDrone.Api/Config/UiConfigResource.cs +++ b/src/NzbDrone.Api/Config/UiConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs b/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs index 0a43fad9b..83f54b4b8 100644 --- a/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs +++ b/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs @@ -4,7 +4,7 @@ using Radarr.Http; namespace NzbDrone.Api.DiskSpace { - public class DiskSpaceModule :RadarrRestModule + public class DiskSpaceModule : RadarrRestModule { private readonly IDiskSpaceService _diskSpaceService; @@ -15,7 +15,6 @@ namespace NzbDrone.Api.DiskSpace GetResourceAll = GetFreeSpace; } - public List GetFreeSpace() { return _diskSpaceService.GetFreeSpace().ConvertAll(DiskSpaceResourceMapper.MapToResource); diff --git a/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs b/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs index f95c2d2a4..5847a7a9c 100644 --- a/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs +++ b/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ namespace NzbDrone.Api.DiskSpace { public static DiskSpaceResource MapToResource(this Core.DiskSpace.DiskSpace model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DiskSpaceResource { diff --git a/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs b/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs index 24ffc4f03..d569b5de8 100644 --- a/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs +++ b/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs @@ -29,7 +29,11 @@ namespace NzbDrone.Api.DownloadClient protected override void Validate(DownloadClientDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs b/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs index 040aae79a..f83292b18 100644 --- a/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs +++ b/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.ExtraFiles { diff --git a/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs b/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs index b37ec6ade..b082c62db 100644 --- a/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs +++ b/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; +using Radarr.Http.REST; namespace NzbDrone.Api.ExtraFiles { @@ -21,7 +21,10 @@ namespace NzbDrone.Api.ExtraFiles { public static ExtraFileResource ToResource(this MetadataFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -36,7 +39,10 @@ namespace NzbDrone.Api.ExtraFiles public static ExtraFileResource ToResource(this SubtitleFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -51,7 +57,10 @@ namespace NzbDrone.Api.ExtraFiles public static ExtraFileResource ToResource(this OtherExtraFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -78,6 +87,5 @@ namespace NzbDrone.Api.ExtraFiles { return movies.Select(ToResource).ToList(); } - } } diff --git a/src/NzbDrone.Api/FileSystem/FileSystemModule.cs b/src/NzbDrone.Api/FileSystem/FileSystemModule.cs index 475719d6b..5b2e854d5 100644 --- a/src/NzbDrone.Api/FileSystem/FileSystemModule.cs +++ b/src/NzbDrone.Api/FileSystem/FileSystemModule.cs @@ -1,10 +1,10 @@ using System.IO; using System.Linq; using Nancy; -using Radarr.Http.Extensions; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; +using Radarr.Http.Extensions; namespace NzbDrone.Api.FileSystem { @@ -22,9 +22,9 @@ namespace NzbDrone.Api.FileSystem _fileSystemLookupService = fileSystemLookupService; _diskProvider = diskProvider; _diskScanService = diskScanService; - Get("/", x => GetContents()); - Get("/type", x => GetEntityType()); - Get("/mediafiles", x => GetMediaFiles()); + Get("/", x => GetContents()); + Get("/type", x => GetEntityType()); + Get("/mediafiles", x => GetMediaFiles()); } private object GetContents() @@ -60,7 +60,8 @@ namespace NzbDrone.Api.FileSystem return new string[0]; } - return _diskScanService.GetVideoFiles(path).Select(f => new { + return _diskScanService.GetVideoFiles(path).Select(f => new + { Path = f, RelativePath = path.GetRelativePath(f), Name = Path.GetFileName(f) diff --git a/src/NzbDrone.Api/Health/HealthResource.cs b/src/NzbDrone.Api/Health/HealthResource.cs index 8be8a5899..b3ed47264 100644 --- a/src/NzbDrone.Api/Health/HealthResource.cs +++ b/src/NzbDrone.Api/Health/HealthResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Http; using NzbDrone.Core.HealthCheck; +using Radarr.Http.REST; namespace NzbDrone.Api.Health { @@ -17,7 +17,10 @@ namespace NzbDrone.Api.Health { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/NzbDrone.Api/History/HistoryModule.cs b/src/NzbDrone.Api/History/HistoryModule.cs index 93c02201e..6c09582d8 100644 --- a/src/NzbDrone.Api/History/HistoryModule.cs +++ b/src/NzbDrone.Api/History/HistoryModule.cs @@ -3,10 +3,10 @@ using System.Linq; using Nancy; using NzbDrone.Api.Movies; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Download; using NzbDrone.Core.History; using Radarr.Http; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Api.History { @@ -25,7 +25,7 @@ namespace NzbDrone.Api.History _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; - Post("/failed", x => MarkAsFailed()); + Post("/failed", x => MarkAsFailed()); } protected HistoryResource MapToResource(Core.History.History model) diff --git a/src/NzbDrone.Api/History/HistoryResource.cs b/src/NzbDrone.Api/History/HistoryResource.cs index c976a9d2d..699e7083f 100644 --- a/src/NzbDrone.Api/History/HistoryResource.cs +++ b/src/NzbDrone.Api/History/HistoryResource.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Api.Movies; using NzbDrone.Core.History; using NzbDrone.Core.Qualities; - +using Radarr.Http.REST; namespace NzbDrone.Api.History { @@ -27,7 +26,10 @@ namespace NzbDrone.Api.History { public static HistoryResource ToResource(this Core.History.History model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -35,13 +37,14 @@ namespace NzbDrone.Api.History MovieId = model.MovieId, SourceTitle = model.SourceTitle, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, EventType = model.EventType, - Data = model.Data + Data = model.Data }; } } diff --git a/src/NzbDrone.Api/Indexers/IndexerModule.cs b/src/NzbDrone.Api/Indexers/IndexerModule.cs index 53166381e..b22c8a7e1 100644 --- a/src/NzbDrone.Api/Indexers/IndexerModule.cs +++ b/src/NzbDrone.Api/Indexers/IndexerModule.cs @@ -31,7 +31,11 @@ namespace NzbDrone.Api.Indexers protected override void Validate(IndexerDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Indexers/ReleaseModule.cs b/src/NzbDrone.Api/Indexers/ReleaseModule.cs index 359e8e79c..693ba93e3 100644 --- a/src/NzbDrone.Api/Indexers/ReleaseModule.cs +++ b/src/NzbDrone.Api/Indexers/ReleaseModule.cs @@ -2,15 +2,15 @@ using System; using System.Collections.Generic; using FluentValidation; using Nancy; +using Nancy.ModelBinding; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Parser.Model; -using Nancy.ModelBinding; -using NzbDrone.Common.Cache; using HttpStatusCode = System.Net.HttpStatusCode; namespace NzbDrone.Api.Indexers @@ -42,7 +42,7 @@ namespace NzbDrone.Api.Indexers _logger = logger; GetResourceAll = GetReleases; - Post("/", x => DownloadRelease(this.Bind())); + Post("/", x => DownloadRelease(this.Bind())); //PostValidator.RuleFor(s => s.DownloadAllowed).Equal(true); PostValidator.RuleFor(s => s.Guid).NotEmpty(); @@ -60,6 +60,7 @@ namespace NzbDrone.Api.Indexers return new NotFoundResponse(); } + try { _downloadService.DownloadReport(remoteMovie); @@ -115,10 +116,9 @@ namespace NzbDrone.Api.Indexers protected override ReleaseResource MapDecision(DownloadDecision decision, int initialWeight) { + _remoteMovieCache.Set(decision.RemoteMovie.Release.Guid, decision.RemoteMovie, TimeSpan.FromMinutes(30)); - _remoteMovieCache.Set(decision.RemoteMovie.Release.Guid, decision.RemoteMovie, TimeSpan.FromMinutes(30)); - - return base.MapDecision(decision, initialWeight); + return base.MapDecision(decision, initialWeight); } } } diff --git a/src/NzbDrone.Api/Indexers/ReleasePushModule.cs b/src/NzbDrone.Api/Indexers/ReleasePushModule.cs index 57c8240e0..a51a40c21 100644 --- a/src/NzbDrone.Api/Indexers/ReleasePushModule.cs +++ b/src/NzbDrone.Api/Indexers/ReleasePushModule.cs @@ -1,17 +1,17 @@ -using FluentValidation; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Download; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Parser.Model; +using FluentValidation; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Api.Indexers { - class ReleasePushModule : ReleaseModuleBase + public class ReleasePushModule : ReleaseModuleBase { private readonly IMakeDownloadDecision _downloadDecisionMaker; private readonly IProcessDownloadDecisions _downloadDecisionProcessor; @@ -28,7 +28,7 @@ namespace NzbDrone.Api.Indexers _indexerFactory = indexerFactory; _logger = logger; - Post("/push", x => ProcessRelease(ReadResourceFromRequest())); + Post("/push", x => ProcessRelease(ReadResourceFromRequest())); PostValidator.RuleFor(s => s.Title).NotEmpty(); PostValidator.RuleFor(s => s.DownloadUrl).NotEmpty(); diff --git a/src/NzbDrone.Api/Indexers/ReleaseResource.cs b/src/NzbDrone.Api/Indexers/ReleaseResource.cs index 2a826ea25..145df5011 100644 --- a/src/NzbDrone.Api/Indexers/ReleaseResource.cs +++ b/src/NzbDrone.Api/Indexers/ReleaseResource.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; +using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; using NzbDrone.Core.Parser; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using System.Linq; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Indexers { @@ -56,7 +56,6 @@ namespace NzbDrone.Api.Indexers public int? Leechers { get; set; } public DownloadProtocol Protocol { get; set; } - // TODO: Remove in v3 // Used to support the original Release Push implementation // JsonIgnore so we don't serialize it, but can still parse it @@ -122,8 +121,8 @@ namespace NzbDrone.Api.Indexers DownloadUrl = releaseInfo.DownloadUrl, InfoUrl = releaseInfo.InfoUrl, MappingResult = mappingResult, - //ReleaseWeight + //ReleaseWeight SuspectedMovieId = movieId, MagnetUrl = torrentInfo.MagnetUrl, @@ -136,7 +135,6 @@ namespace NzbDrone.Api.Indexers //Special = parsedMovieInfo.Special, }; - } public static ReleaseInfo ToModel(this ReleaseResource resource) diff --git a/src/NzbDrone.Api/Logs/LogFileModuleBase.cs b/src/NzbDrone.Api/Logs/LogFileModuleBase.cs index fa1de297e..7acf4fdf2 100644 --- a/src/NzbDrone.Api/Logs/LogFileModuleBase.cs +++ b/src/NzbDrone.Api/Logs/LogFileModuleBase.cs @@ -26,7 +26,7 @@ namespace NzbDrone.Api.Logs _configFileProvider = configFileProvider; GetResourceAll = GetLogFilesResponse; - Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); + Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); } private List GetLogFilesResponse() @@ -60,7 +60,9 @@ namespace NzbDrone.Api.Logs var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); diff --git a/src/NzbDrone.Api/Logs/LogResource.cs b/src/NzbDrone.Api/Logs/LogResource.cs index 53d9a947a..675eb033a 100644 --- a/src/NzbDrone.Api/Logs/LogResource.cs +++ b/src/NzbDrone.Api/Logs/LogResource.cs @@ -17,7 +17,10 @@ namespace NzbDrone.Api.Logs { public static LogResource ToResource(this Core.Instrumentation.Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs b/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs index d4e19415d..a8b9ff1b0 100644 --- a/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs +++ b/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ namespace NzbDrone.Api.Logs protected override IEnumerable GetLogFiles() { - if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) return Enumerable.Empty(); + if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) + { + return Enumerable.Empty(); + } return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly) .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase)) diff --git a/src/NzbDrone.Api/ManualImport/ManualImportResource.cs b/src/NzbDrone.Api/ManualImport/ManualImportResource.cs index fea7987b8..ecd8ef5db 100644 --- a/src/NzbDrone.Api/ManualImport/ManualImportResource.cs +++ b/src/NzbDrone.Api/ManualImport/ManualImportResource.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; using NzbDrone.Api.Movies; -using Radarr.Http.REST; using NzbDrone.Common.Crypto; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.ManualImport { @@ -25,7 +25,10 @@ namespace NzbDrone.Api.ManualImport { public static ManualImportResource ToResource(this Core.MediaFiles.MovieImport.Manual.ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { @@ -37,6 +40,7 @@ namespace NzbDrone.Api.ManualImport Size = model.Size, Movie = model.Movie.ToResource(), Quality = model.Quality, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections diff --git a/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs b/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs index 26391be9a..246bbdd4f 100644 --- a/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs +++ b/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs @@ -10,19 +10,19 @@ namespace NzbDrone.Api.MediaCovers { public class MediaCoverModule : NzbDroneApiModule { + private const string MEDIA_COVER_ROUTE = @"/(?\d+)/(?(.+)\.(jpg|png|gif))"; private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private const string MEDIA_COVER_ROUTE = @"/(?\d+)/(?(.+)\.(jpg|png|gif))"; - private readonly IAppFolderInfo _appFolderInfo; private readonly IDiskProvider _diskProvider; - public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) : base("MediaCover") + public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) + : base("MediaCover") { _appFolderInfo = appFolderInfo; _diskProvider = diskProvider; - Get(MEDIA_COVER_ROUTE, options => GetMediaCover(options.seriesId, options.filename)); + Get(MEDIA_COVER_ROUTE, options => GetMediaCover(options.seriesId, options.filename)); } private object GetMediaCover(int seriesId, string filename) @@ -38,6 +38,7 @@ namespace NzbDrone.Api.MediaCovers { return new NotFoundResponse(); } + filePath = basefilePath; } diff --git a/src/NzbDrone.Api/Metadata/MetadataModule.cs b/src/NzbDrone.Api/Metadata/MetadataModule.cs index e24c38862..1f941fa1c 100644 --- a/src/NzbDrone.Api/Metadata/MetadataModule.cs +++ b/src/NzbDrone.Api/Metadata/MetadataModule.cs @@ -25,7 +25,11 @@ namespace NzbDrone.Api.Metadata protected override void Validate(MetadataDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs b/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs index 1115bbb74..89ff86a9f 100644 --- a/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs +++ b/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs @@ -1,13 +1,13 @@ using System.IO; using NLog; -using Radarr.Http; using NzbDrone.Core.Datastore.Events; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.SignalR; -using NzbDrone.Core.DecisionEngine.Specifications; +using Radarr.Http; namespace NzbDrone.Api.MovieFiles { @@ -44,7 +44,6 @@ namespace NzbDrone.Api.MovieFiles return movie.ToResource(); } - private void SetQuality(MovieFileResource movieFileResource) { var movieFile = _mediaFileService.GetMovie(movieFileResource.Id); diff --git a/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs b/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs index 711013e7d..78990cdf1 100644 --- a/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs +++ b/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Api.Movies; -using NzbDrone.Core.Qualities; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.MovieFiles { @@ -12,13 +12,11 @@ namespace NzbDrone.Api.MovieFiles { public MovieFileResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public string RelativePath { get; set; } public string Path { get; set; } @@ -38,7 +36,10 @@ namespace NzbDrone.Api.MovieFiles { public static MovieFileResource ToResource(this MovieFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } MovieResource movie = null; @@ -69,11 +70,13 @@ namespace NzbDrone.Api.MovieFiles public static MovieFile ToModel(this MovieFileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new MovieFile { - }; } diff --git a/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs b/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs index ca18bdecb..9be6f6da7 100644 --- a/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs +++ b/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs @@ -1,7 +1,7 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies.Events; using Radarr.Http; diff --git a/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs b/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs index 021761907..412495ad1 100644 --- a/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs +++ b/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies.AlternativeTitles; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -10,13 +10,11 @@ namespace NzbDrone.Api.Movies { public AlternativeTitleResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public SourceType SourceType { get; set; } public int MovieId { get; set; } public string Title { get; set; } @@ -33,7 +31,10 @@ namespace NzbDrone.Api.Movies { public static AlternativeTitleResource ToResource(this AlternativeTitle model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new AlternativeTitleResource { @@ -50,7 +51,10 @@ namespace NzbDrone.Api.Movies public static AlternativeTitle ToModel(this AlternativeTitleResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new AlternativeTitle { diff --git a/src/NzbDrone.Api/Movies/AlternativeYearResource.cs b/src/NzbDrone.Api/Movies/AlternativeYearResource.cs index d7ee8bd9b..039bbd9b0 100644 --- a/src/NzbDrone.Api/Movies/AlternativeYearResource.cs +++ b/src/NzbDrone.Api/Movies/AlternativeYearResource.cs @@ -6,13 +6,11 @@ namespace NzbDrone.Api.Movies { public AlternativeYearResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public int Year { get; set; } diff --git a/src/NzbDrone.Api/Movies/FetchMovieListModule.cs b/src/NzbDrone.Api/Movies/FetchMovieListModule.cs index fce917505..8e12f1c8b 100644 --- a/src/NzbDrone.Api/Movies/FetchMovieListModule.cs +++ b/src/NzbDrone.Api/Movies/FetchMovieListModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; using NzbDrone.Core.NetImport; using Radarr.Http; @@ -18,13 +18,12 @@ namespace NzbDrone.Api.Movies { _fetchNetImport = netImport; _movieSearch = movieSearch; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { - var results = _fetchNetImport.FetchAndFilter((int) Request.Query.listId, false); + var results = _fetchNetImport.FetchAndFilter((int)Request.Query.listId, false); List realResults = new List(); @@ -41,7 +40,6 @@ namespace NzbDrone.Api.Movies return MapToResource(results); } - private static IEnumerable MapToResource(IEnumerable movies) { foreach (var currentSeries in movies) diff --git a/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs b/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs index c56aa8579..8bdbd0ba6 100644 --- a/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs +++ b/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs @@ -1,23 +1,22 @@ -using System.Collections.Generic; -using Nancy; -using NzbDrone.Core.MediaCover; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Parser; -using System.Linq; using System; +using System.Collections.Generic; +using System.Linq; +using Nancy; +using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; +using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.RootFolders; -using NzbDrone.Common.Cache; +using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; using NzbDrone.Core.Profiles; +using NzbDrone.Core.RootFolders; using Radarr.Http; namespace NzbDrone.Api.Movies { - public class UnmappedComparer : IComparer { public int Compare(UnmappedFolder a, UnmappedFolder b) @@ -37,10 +36,14 @@ namespace NzbDrone.Api.Movies private readonly IProfileService _profileService; private readonly IMovieService _movieService; - public MovieBulkImportModule(ISearchForNewMovie searchProxy, IRootFolderService rootFolderService, + public MovieBulkImportModule(ISearchForNewMovie searchProxy, + IRootFolderService rootFolderService, IMakeImportDecision importDecisionMaker, - IDiskScanService diskScanService, ICacheManager cacheManager, - IParsingService parsingService, IProfileService profileService, IMovieService movieService) + IDiskScanService diskScanService, + ICacheManager cacheManager, + IParsingService parsingService, + IProfileService profileService, + IMovieService movieService) : base("/movies/bulkimport") { _searchProxy = searchProxy; @@ -51,10 +54,9 @@ namespace NzbDrone.Api.Movies _movieService = movieService; _profileService = profileService; _parsingService = parsingService; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { if (Request.Query.Id == 0) @@ -84,7 +86,7 @@ namespace NzbDrone.Api.Movies max = total_count >= max ? max : total_count; - var paged = unmapped.GetRange(min, max-min); + var paged = unmapped.GetRange(min, max - min); var mapped = paged.Select(f => { @@ -167,7 +169,6 @@ namespace NzbDrone.Api.Movies }; } - private static IEnumerable MapToResource(IEnumerable movies) { foreach (var currentMovie in movies) diff --git a/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs b/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs index b9335aaa0..2d2294113 100644 --- a/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs +++ b/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; +using System.Linq; +using NzbDrone.Api.NetImport; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using Radarr.Http; using NzbDrone.Core.NetImport; -using NzbDrone.Api.NetImport; +using Radarr.Http; namespace NzbDrone.Api.Movies { @@ -18,8 +18,8 @@ namespace NzbDrone.Api.Movies { _searchProxy = searchProxy; _netImportFactory = netImportFactory; - Get("/lists", x => GetLists()); - Get("/{action?recommendations}", x => Search(x.action)); + Get("/lists", x => GetLists()); + Get("/{action?recommendations}", x => Search(x.action)); } private object Search(string action) @@ -32,7 +32,8 @@ namespace NzbDrone.Api.Movies { var lists = _netImportFactory.Discoverable(); - return lists.Select(definition => { + return lists.Select(definition => + { var resource = new NetImportResource(); resource.Id = definition.Definition.Id; diff --git a/src/NzbDrone.Api/Movies/MovieEditorModule.cs b/src/NzbDrone.Api/Movies/MovieEditorModule.cs index c8c50d094..31c184a40 100644 --- a/src/NzbDrone.Api/Movies/MovieEditorModule.cs +++ b/src/NzbDrone.Api/Movies/MovieEditorModule.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Http.Extensions; using NzbDrone.Core.Movies; +using Radarr.Http.Extensions; namespace NzbDrone.Api.Movies { @@ -15,19 +15,19 @@ namespace NzbDrone.Api.Movies : base("/movie/editor") { _movieService = movieService; - Put("/", Movie => SaveAll()); - Put("/delete", Movie => DeleteSelected()); + Put("/", movie => SaveAll()); + Put("/delete", movie => DeleteSelected()); } private object SaveAll() { var resources = Request.Body.FromJson>(); - var Movie = resources.Select(MovieResource => MovieResource.ToModel(_movieService.GetMovie(MovieResource.Id))).ToList(); + var movie = resources.Select(movieResource => movieResource.ToModel(_movieService.GetMovie(movieResource.Id))).ToList(); - return ResponseWithCode(_movieService.UpdateMovie(Movie) - .ToResource() - , HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.UpdateMovie(movie) + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteSelected() @@ -41,10 +41,12 @@ namespace NzbDrone.Api.Movies { deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value); } + if (addExclusionQuery.HasValue) { addExclusion = Convert.ToBoolean(addExclusionQuery.Value); } + var ids = Request.Body.FromJson>(); foreach (var id in ids) diff --git a/src/NzbDrone.Api/Movies/MovieLookupModule.cs b/src/NzbDrone.Api/Movies/MovieLookupModule.cs index 9a45c2414..2ee8ea965 100644 --- a/src/NzbDrone.Api/Movies/MovieLookupModule.cs +++ b/src/NzbDrone.Api/Movies/MovieLookupModule.cs @@ -1,9 +1,9 @@ +using System; using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using System; using Radarr.Http; using Radarr.Http.REST; @@ -19,15 +19,15 @@ namespace NzbDrone.Api.Movies { _movieInfo = movieInfo; _searchProxy = searchProxy; - Get("/", x => Search()); - Get("/tmdb", x => SearchByTmdbId()); - Get("/imdb", x => SearchByImdbId()); + Get("/", x => Search()); + Get("/tmdb", x => SearchByTmdbId()); + Get("/imdb", x => SearchByImdbId()); } private object SearchByTmdbId() { int tmdbId = -1; - if(Int32.TryParse(Request.Query.tmdbId, out tmdbId)) + if (int.TryParse(Request.Query.tmdbId, out tmdbId)) { var result = _movieInfo.GetMovieInfo(tmdbId, null, true); return result.ToResource(); diff --git a/src/NzbDrone.Api/Movies/MovieModule.cs b/src/NzbDrone.Api/Movies/MovieModule.cs index 5d69f8944..e579f87cb 100644 --- a/src/NzbDrone.Api/Movies/MovieModule.cs +++ b/src/NzbDrone.Api/Movies/MovieModule.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using FluentValidation; +using Nancy; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.MediaCover; @@ -9,10 +10,9 @@ using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Validation.Paths; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; using NzbDrone.SignalR; -using Nancy; using Radarr.Http; namespace NzbDrone.Api.Movies @@ -25,24 +25,22 @@ namespace NzbDrone.Api.Movies IHandle, IHandle, IHandle - { + private const string TITLE_SLUG_ROUTE = "/titleslug/(?[^/]+)"; + protected readonly IMovieService _moviesService; private readonly IMapCoversToLocal _coverMapper; - private const string TITLE_SLUG_ROUTE = "/titleslug/(?[^/]+)"; - public MovieModule(IBroadcastSignalRMessage signalRBroadcaster, - IMovieService moviesService, - IMapCoversToLocal coverMapper, - RootFolderValidator rootFolderValidator, - MoviePathValidator moviesPathValidator, - MovieExistsValidator moviesExistsValidator, - MovieAncestorValidator moviesAncestorValidator, - SystemFolderValidator systemFolderValidator, - ProfileExistsValidator profileExistsValidator - ) - : base(signalRBroadcaster) + IMovieService moviesService, + IMapCoversToLocal coverMapper, + RootFolderValidator rootFolderValidator, + MoviePathValidator moviesPathValidator, + MovieExistsValidator moviesExistsValidator, + MovieAncestorValidator moviesAncestorValidator, + SystemFolderValidator systemFolderValidator, + ProfileExistsValidator profileExistsValidator) + : base(signalRBroadcaster) { _moviesService = moviesService; @@ -84,7 +82,10 @@ namespace NzbDrone.Api.Movies protected MovieResource MapToResource(Movie movies) { - if (movies == null) return null; + if (movies == null) + { + return null; + } var resource = movies.ToResource(); MapCoversToLocal(resource); @@ -128,6 +129,7 @@ namespace NzbDrone.Api.Movies { deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value); } + if (addExclusionQuery.HasValue) { addExclusion = Convert.ToBoolean(addExclusionQuery.Value); @@ -151,7 +153,10 @@ namespace NzbDrone.Api.Movies public void Handle(MovieFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId); } diff --git a/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs b/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs index 4faa585b5..820518306 100644 --- a/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs +++ b/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs @@ -65,7 +65,6 @@ namespace NzbDrone.Api.Movies //add a grabbed field in MovieResource? //resource.Grabbed = true; - BroadcastResourceChange(ModelAction.Updated, resource); } diff --git a/src/NzbDrone.Api/Movies/MovieResource.cs b/src/NzbDrone.Api/Movies/MovieResource.cs index 3afb1d302..7dc9f40b4 100644 --- a/src/NzbDrone.Api/Movies/MovieResource.cs +++ b/src/NzbDrone.Api/Movies/MovieResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; +using NzbDrone.Api.MovieFiles; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Movies; -using NzbDrone.Api.MovieFiles; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -64,6 +64,7 @@ namespace NzbDrone.Api.Movies public DateTime Added { get; set; } public AddMovieOptions AddOptions { get; set; } public Ratings Ratings { get; set; } + //public List AlternativeTitles { get; set; } public MovieFileResource MovieFile { get; set; } @@ -90,15 +91,15 @@ namespace NzbDrone.Api.Movies { public static MovieResource ToResource(this Core.Movies.Movie model) { - if (model == null) return null; - + if (model == null) + { + return null; + } long size = model.MovieFile?.Size ?? 0; bool downloaded = model.MovieFile != null; MovieFileResource movieFile = model.MovieFile?.ToResource(); - - /*if(model.MovieFile != null) { model.MovieFile.LazyLoad(); @@ -112,12 +113,12 @@ namespace NzbDrone.Api.Movies }*/ //model.AlternativeTitles.LazyLoad(); - return new MovieResource { Id = model.Id, TmdbId = model.TmdbId, Title = model.Title, + //AlternateTitles SortTitle = model.SortTitle, InCinemas = model.InCinemas, @@ -125,12 +126,14 @@ namespace NzbDrone.Api.Movies PhysicalReleaseNote = model.PhysicalReleaseNote, HasFile = model.HasFile, Downloaded = downloaded, + //TotalEpisodeCount //EpisodeCount //EpisodeFileCount SizeOnDisk = size, Status = model.Status, Overview = model.Overview, + //NextAiring //PreviousAiring Images = model.Images, @@ -150,7 +153,6 @@ namespace NzbDrone.Api.Movies FolderName = model.FolderName(), //SizeOnDisk = size, - Runtime = model.Runtime, LastInfoSync = model.LastInfoSync, CleanTitle = model.CleanTitle, @@ -173,7 +175,10 @@ namespace NzbDrone.Api.Movies public static Core.Movies.Movie ToModel(this MovieResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Core.Movies.Movie { @@ -181,16 +186,19 @@ namespace NzbDrone.Api.Movies TmdbId = resource.TmdbId, Title = resource.Title, + //AlternateTitles SortTitle = resource.SortTitle, InCinemas = resource.InCinemas, PhysicalRelease = resource.PhysicalRelease, PhysicalReleaseNote = resource.PhysicalReleaseNote, + //TotalEpisodeCount //EpisodeCount //EpisodeFileCount //SizeOnDisk Overview = resource.Overview, + //NextAiring //PreviousAiring Images = resource.Images, @@ -218,6 +226,7 @@ namespace NzbDrone.Api.Movies Tags = resource.Tags, Added = resource.Added, AddOptions = resource.AddOptions, + //AlternativeTitles = resource.AlternativeTitles, Ratings = resource.Ratings, YouTubeTrailerId = resource.YouTubeTrailerId, diff --git a/src/NzbDrone.Api/Movies/RenameMovieModule.cs b/src/NzbDrone.Api/Movies/RenameMovieModule.cs index d34f5b3a6..44a158125 100644 --- a/src/NzbDrone.Api/Movies/RenameMovieModule.cs +++ b/src/NzbDrone.Api/Movies/RenameMovieModule.cs @@ -1,7 +1,7 @@ -using Radarr.Http.REST; -using NzbDrone.Core.MediaFiles; using System.Collections.Generic; +using NzbDrone.Core.MediaFiles; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -19,7 +19,7 @@ namespace NzbDrone.Api.Movies private List GetMovies() { - if(!Request.Query.MovieId.HasValue) + if (!Request.Query.MovieId.HasValue) { throw new BadRequestException("movieId is missing"); } @@ -28,6 +28,5 @@ namespace NzbDrone.Api.Movies return _renameMovieFileService.GetRenamePreviews(movieId).ToResource(); } - } } diff --git a/src/NzbDrone.Api/Movies/RenameMovieResource.cs b/src/NzbDrone.Api/Movies/RenameMovieResource.cs index a95b58fa4..62feb1010 100644 --- a/src/NzbDrone.Api/Movies/RenameMovieResource.cs +++ b/src/NzbDrone.Api/Movies/RenameMovieResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using System.Collections.Generic; using System.Linq; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -16,7 +16,10 @@ namespace NzbDrone.Api.Movies { public static RenameMovieResource ToResource(this Core.MediaFiles.RenameMovieFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameMovieResource { diff --git a/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs b/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs index eca4696a2..7ecc04c06 100644 --- a/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs +++ b/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs @@ -9,7 +9,8 @@ namespace NzbDrone.Api.NetImport { private readonly IImportExclusionsService _exclusionService; - public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) : base("exclusions") + public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) + : base("exclusions") { _exclusionService = exclusionService; GetResourceAll = GetAll; @@ -35,7 +36,7 @@ namespace NzbDrone.Api.NetImport return _exclusionService.AddExclusion(model).Id; } - public void RemoveExclusion (int id) + public void RemoveExclusion(int id) { _exclusionService.RemoveExclusion(new ImportExclusion { Id = id }); } diff --git a/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs b/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs index 0ced434f6..e2a3eff22 100644 --- a/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs +++ b/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs @@ -15,7 +15,10 @@ namespace NzbDrone.Api.NetImport { public static ImportExclusionsResource ToResource(this Core.NetImport.ImportExclusions.ImportExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportExclusionsResource { diff --git a/src/NzbDrone.Api/NetImport/ListImportModule.cs b/src/NzbDrone.Api/NetImport/ListImportModule.cs index a8d2eca3c..d2c7ea0d4 100644 --- a/src/NzbDrone.Api/NetImport/ListImportModule.cs +++ b/src/NzbDrone.Api/NetImport/ListImportModule.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using Nancy; using Nancy.Extensions; -using Radarr.Http.Extensions; using NzbDrone.Api.Movies; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using Radarr.Http.Extensions; namespace NzbDrone.Api.NetImport { @@ -19,16 +19,16 @@ namespace NzbDrone.Api.NetImport { _movieService = movieService; _movieSearch = movieSearch; - Put("/", Movie => SaveAll()); + Put("/", movie => SaveAll()); } private object SaveAll() { var resources = Request.Body.FromJson>(); - var Movies = resources.Select(MovieResource => _movieSearch.MapMovieToTmdbMovie(MovieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); + var movies = resources.Select(movieResource => _movieSearch.MapMovieToTmdbMovie(movieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); - return ResponseWithCode(_movieService.AddMovies(Movies).ToResource(), HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.AddMovies(movies).ToResource(), HttpStatusCode.Accepted); } } } diff --git a/src/NzbDrone.Api/NetImport/NetImportModule.cs b/src/NzbDrone.Api/NetImport/NetImportModule.cs index 845ee4819..760a64ee9 100644 --- a/src/NzbDrone.Api/NetImport/NetImportModule.cs +++ b/src/NzbDrone.Api/NetImport/NetImportModule.cs @@ -6,7 +6,8 @@ namespace NzbDrone.Api.NetImport { public class NetImportModule : ProviderModuleBase { - public NetImportModule(NetImportFactory netImportFactory) : base(netImportFactory, "netimport") + public NetImportModule(NetImportFactory netImportFactory) + : base(netImportFactory, "netimport") { PostValidator.RuleFor(c => c.RootFolderPath).IsValidPath(); PostValidator.RuleFor(c => c.MinimumAvailability).NotNull(); @@ -41,7 +42,11 @@ namespace NzbDrone.Api.NetImport protected override void Validate(NetImportDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Notifications/NotificationModule.cs b/src/NzbDrone.Api/Notifications/NotificationModule.cs index 6403f02f4..d86855f1c 100644 --- a/src/NzbDrone.Api/Notifications/NotificationModule.cs +++ b/src/NzbDrone.Api/Notifications/NotificationModule.cs @@ -41,7 +41,11 @@ namespace NzbDrone.Api.Notifications protected override void Validate(NotificationDefinition definition, bool includeWarnings) { - if (!definition.OnGrab && !definition.OnDownload) return; + if (!definition.OnGrab && !definition.OnDownload) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Parse/ParseModule.cs b/src/NzbDrone.Api/Parse/ParseModule.cs index 6b96c9f75..e08bb1c8f 100644 --- a/src/NzbDrone.Api/Parse/ParseModule.cs +++ b/src/NzbDrone.Api/Parse/ParseModule.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Api.Parse var title = Request.Query.Title.Value as string; var parsedMovieInfo = _parsingService.ParseMovieInfo(title, new List()); - if (parsedMovieInfo == null) { return null; diff --git a/src/NzbDrone.Api/Parse/ParseResource.cs b/src/NzbDrone.Api/Parse/ParseResource.cs index ec6e4854a..451f9c95d 100644 --- a/src/NzbDrone.Api/Parse/ParseResource.cs +++ b/src/NzbDrone.Api/Parse/ParseResource.cs @@ -1,6 +1,6 @@ using NzbDrone.Api.Movies; -using Radarr.Http.REST; using NzbDrone.Core.Parser.Model; +using Radarr.Http.REST; namespace NzbDrone.Api.Parse { diff --git a/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs b/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs index a478edd94..ba8baed77 100644 --- a/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs +++ b/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using FluentValidation; -using Radarr.Http.REST; -using Radarr.Http.Validation; using NzbDrone.Core.Profiles.Delay; using Radarr.Http; +using Radarr.Http.REST; +using Radarr.Http.Validation; namespace NzbDrone.Api.Profiles.Delay { diff --git a/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs b/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs index a626c220a..802b793fb 100644 --- a/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs +++ b/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Indexers; using NzbDrone.Core.Profiles.Delay; +using Radarr.Http.REST; namespace NzbDrone.Api.Profiles.Delay { @@ -21,7 +21,10 @@ namespace NzbDrone.Api.Profiles.Delay { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -39,7 +42,10 @@ namespace NzbDrone.Api.Profiles.Delay public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs b/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs index 11f457280..2c340454c 100644 --- a/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs +++ b/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs @@ -27,12 +27,12 @@ namespace NzbDrone.Api.Profiles.Languages private List GetAll() { - return ((Language[])Enum.GetValues(typeof (Language))) + return ((Language[])Enum.GetValues(typeof(Language))) .Select(l => new LanguageResource - { - Id = (int) l, - Name = l.ToString() - }) + { + Id = (int)l, + Name = l.ToString() + }) .OrderBy(l => l.Name) .ToList(); } diff --git a/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs b/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs index 0e704aa43..043ee4665 100644 --- a/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs +++ b/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs @@ -3,7 +3,7 @@ using Nancy; namespace NzbDrone.Api.Profiles { - class LegacyProfileModule : NzbDroneApiModule + public class LegacyProfileModule : NzbDroneApiModule { public LegacyProfileModule() : base("qualityprofile") diff --git a/src/NzbDrone.Api/Profiles/ProfileResource.cs b/src/NzbDrone.Api/Profiles/ProfileResource.cs index 2f4df4f39..c950083b5 100644 --- a/src/NzbDrone.Api/Profiles/ProfileResource.cs +++ b/src/NzbDrone.Api/Profiles/ProfileResource.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Common.Extensions; using NzbDrone.Api.Qualities; -using Radarr.Http.REST; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Profiles { @@ -36,13 +36,22 @@ namespace NzbDrone.Api.Profiles { public static ProfileResource ToResource(this Profile model) { - if (model == null) return null; + if (model == null) + { + return null; + } var cutoffItem = model.Items.First(q => { - if (q.Id == model.Cutoff) return true; + if (q.Id == model.Cutoff) + { + return true; + } - if (q.Quality == null) return false; + if (q.Quality == null) + { + return false; + } return q.Quality.Id == model.Cutoff; }); @@ -53,9 +62,15 @@ namespace NzbDrone.Api.Profiles var formatCutoffItem = model.FormatItems.First(q => { - if (q.Id == model.FormatCutoff) return true; + if (q.Id == model.FormatCutoff) + { + return true; + } - if (q.Format == null) return false; + if (q.Format == null) + { + return false; + } return q.Format.Id == model.FormatCutoff; }); @@ -93,7 +108,10 @@ namespace NzbDrone.Api.Profiles public static ProfileQualityItemResource ToResource(this ProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ProfileQualityItemResource { @@ -113,7 +131,10 @@ namespace NzbDrone.Api.Profiles public static Profile ToModel(this ProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Profile { @@ -131,7 +152,10 @@ namespace NzbDrone.Api.Profiles public static ProfileQualityItem ToModel(this ProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileQualityItem { diff --git a/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs b/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs index a1babd804..25f863427 100644 --- a/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs +++ b/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs @@ -31,7 +31,8 @@ namespace NzbDrone.Api.Profiles var formatItems = _formatService.All().Select(v => new ProfileFormatItem { - Format = v, Allowed = true + Format = v, + Allowed = true }).ToList(); formatItems.Insert(0, new ProfileFormatItem diff --git a/src/NzbDrone.Api/Profiles/ProfileValidation.cs b/src/NzbDrone.Api/Profiles/ProfileValidation.cs index 003c96f39..d70d716ba 100644 --- a/src/NzbDrone.Api/Profiles/ProfileValidation.cs +++ b/src/NzbDrone.Api/Profiles/ProfileValidation.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Api.Profiles public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) diff --git a/src/NzbDrone.Api/ProviderModuleBase.cs b/src/NzbDrone.Api/ProviderModuleBase.cs index 96cc568ca..b842d832e 100644 --- a/src/NzbDrone.Api/ProviderModuleBase.cs +++ b/src/NzbDrone.Api/ProviderModuleBase.cs @@ -3,10 +3,10 @@ using System.Linq; using FluentValidation; using FluentValidation.Results; using Nancy; +using Newtonsoft.Json; using NzbDrone.Common.Reflection; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using Newtonsoft.Json; using Radarr.Http; using Radarr.Http.ClientSchema; @@ -24,9 +24,9 @@ namespace NzbDrone.Api { _providerFactory = providerFactory; - Get("schema", x => GetTemplates()); - Post("test", x => Test(ReadResourceFromRequest(true))); - Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); + Get("schema", x => GetTemplates()); + Post("test", x => Test(ReadResourceFromRequest(true))); + Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); GetResourceAll = GetAll; GetResourceById = GetProviderById; @@ -35,7 +35,7 @@ namespace NzbDrone.Api DeleteResource = DeleteProvider; SharedValidator.RuleFor(c => c.Name).NotEmpty(); - SharedValidator.RuleFor(c => c.Name).Must((v,c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); + SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); SharedValidator.RuleFor(c => c.Implementation).NotEmpty(); SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty(); @@ -181,7 +181,6 @@ namespace NzbDrone.Api return "{}"; } - private object RequestAction(string action, TProviderResource providerResource) { var providerDefinition = GetDefinition(providerResource, true, false); diff --git a/src/NzbDrone.Api/ProviderResource.cs b/src/NzbDrone.Api/ProviderResource.cs index cfa016b55..910709706 100644 --- a/src/NzbDrone.Api/ProviderResource.cs +++ b/src/NzbDrone.Api/ProviderResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using NzbDrone.Core.ThingiProvider; using Radarr.Http.ClientSchema; using Radarr.Http.REST; -using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Api { diff --git a/src/NzbDrone.Api/Qualities/CustomFormatModule.cs b/src/NzbDrone.Api/Qualities/CustomFormatModule.cs index 6791f9077..c14bfa4a2 100644 --- a/src/NzbDrone.Api/Qualities/CustomFormatModule.cs +++ b/src/NzbDrone.Api/Qualities/CustomFormatModule.cs @@ -31,7 +31,7 @@ namespace NzbDrone.Api.Qualities var allNewTags = c.Select(t => t.ToLower()); var enumerable = allTags.ToList(); var newTags = allNewTags.ToList(); - return (enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count()); + return enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count(); }); }) .WithMessage("Should be unique."); @@ -46,11 +46,11 @@ namespace NzbDrone.Api.Qualities DeleteResource = DeleteFormat; - Get("/test", x => Test()); + Get("/test", x => Test()); - Post("/test", x => TestWithNewModel()); + Post("/test", x => TestWithNewModel()); - Get("schema", x => GetTemplates()); + Get("schema", x => GetTemplates()); } private int Create(CustomFormatResource customFormatResource) @@ -95,11 +95,12 @@ namespace NzbDrone.Api.Qualities private CustomFormatTestResource Test() { - var parsed = _parsingService.ParseMovieInfo((string) Request.Query.title, new List()); + var parsed = _parsingService.ParseMovieInfo((string)Request.Query.title, new List()); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), @@ -109,18 +110,19 @@ namespace NzbDrone.Api.Qualities private CustomFormatTestResource TestWithNewModel() { - var queryTitle = (string) Request.Query.title; + var queryTitle = (string)Request.Query.title; var resource = ReadResourceFromRequest(); var model = resource.ToModel(); model.Name = model.Name += " (New)"; - var parsed = _parsingService.ParseMovieInfo(queryTitle, new List{model}); + var parsed = _parsingService.ParseMovieInfo(queryTitle, new List { model }); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), diff --git a/src/NzbDrone.Api/Qualities/CustomFormatResource.cs b/src/NzbDrone.Api/Qualities/CustomFormatResource.cs index 1d0511d47..b4c658723 100644 --- a/src/NzbDrone.Api/Qualities/CustomFormatResource.cs +++ b/src/NzbDrone.Api/Qualities/CustomFormatResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { diff --git a/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs b/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs index b6f5d671a..c8209c2b3 100644 --- a/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs +++ b/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Extensions; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { @@ -29,7 +29,10 @@ namespace NzbDrone.Api.Qualities { public static FormatTagMatchResultResource ToResource(this FormatTagMatchResult model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new FormatTagMatchResultResource { diff --git a/src/NzbDrone.Api/Qualities/FormatTagValidator.cs b/src/NzbDrone.Api/Qualities/FormatTagValidator.cs index 53efbea21..7f1eee36a 100644 --- a/src/NzbDrone.Api/Qualities/FormatTagValidator.cs +++ b/src/NzbDrone.Api/Qualities/FormatTagValidator.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Api.Qualities { public class FormatTagValidator : PropertyValidator { - public FormatTagValidator() : base("{ValidationMessage}") + public FormatTagValidator() + : base("{ValidationMessage}") { } @@ -19,11 +20,14 @@ namespace NzbDrone.Api.Qualities return false; } - var tags = (IEnumerable) context.PropertyValue; + var tags = (IEnumerable)context.PropertyValue; var invalidTags = tags.Where(t => !FormatTag.QualityTagRegex.IsMatch(t)); - if (invalidTags.Count() == 0) return true; + if (invalidTags.Count() == 0) + { + return true; + } var formatMessage = $"Format Tags ({string.Join(", ", invalidTags)}) are in an invalid format! Check the Wiki to learn how they should look."; diff --git a/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs b/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs index 9a402f895..67af695a6 100644 --- a/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs +++ b/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Core.Parser; using NzbDrone.Core.Qualities; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { diff --git a/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs b/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs index a795e7697..6365ec58a 100644 --- a/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs +++ b/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { @@ -21,7 +21,10 @@ namespace NzbDrone.Api.Qualities { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -40,7 +43,10 @@ namespace NzbDrone.Api.Qualities public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { diff --git a/src/NzbDrone.Api/Queue/QueueActionModule.cs b/src/NzbDrone.Api/Queue/QueueActionModule.cs index ed306dc6b..287e5eeca 100644 --- a/src/NzbDrone.Api/Queue/QueueActionModule.cs +++ b/src/NzbDrone.Api/Queue/QueueActionModule.cs @@ -1,12 +1,12 @@ using System; using Nancy; -using Radarr.Http.Extensions; -using Radarr.Http.REST; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Queue; using Radarr.Http; +using Radarr.Http.Extensions; +using Radarr.Http.REST; namespace NzbDrone.Api.Queue { @@ -36,9 +36,9 @@ namespace NzbDrone.Api.Queue _pendingReleaseService = pendingReleaseService; _downloadService = downloadService; - Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); - Post("/import", x => Import()); - Post("/grab", x => Grab()); + Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); + Post("/import", x => Import()); + Post("/grab", x => Grab()); } private object Remove(int id) diff --git a/src/NzbDrone.Api/Queue/QueueResource.cs b/src/NzbDrone.Api/Queue/QueueResource.cs index eafe50794..99640a540 100644 --- a/src/NzbDrone.Api/Queue/QueueResource.cs +++ b/src/NzbDrone.Api/Queue/QueueResource.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; -using Radarr.Http.REST; -using NzbDrone.Core.Qualities; +using System.Linq; using NzbDrone.Api.Movies; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; -using System.Linq; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Queue { @@ -29,7 +29,10 @@ namespace NzbDrone.Api.Queue { public static QueueResource ToResource(this Core.Queue.Queue model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs b/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs index c52774bae..f6a2172d3 100644 --- a/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.RemotePathMappings; +using Radarr.Http.REST; namespace NzbDrone.Api.RemotePathMappings { @@ -16,7 +16,10 @@ namespace NzbDrone.Api.RemotePathMappings { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ namespace NzbDrone.Api.RemotePathMappings public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/NzbDrone.Api/Restrictions/RestrictionModule.cs b/src/NzbDrone.Api/Restrictions/RestrictionModule.cs index 92759332d..b3ce2dd2c 100644 --- a/src/NzbDrone.Api/Restrictions/RestrictionModule.cs +++ b/src/NzbDrone.Api/Restrictions/RestrictionModule.cs @@ -9,7 +9,6 @@ namespace Radarr.Http.RESTrictions { private readonly IRestrictionService _restrictionService; - public RestrictionModule(IRestrictionService restrictionService) { _restrictionService = restrictionService; diff --git a/src/NzbDrone.Api/Restrictions/RestrictionResource.cs b/src/NzbDrone.Api/Restrictions/RestrictionResource.cs index a2d9d9424..2060c4cb2 100644 --- a/src/NzbDrone.Api/Restrictions/RestrictionResource.cs +++ b/src/NzbDrone.Api/Restrictions/RestrictionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Restrictions; +using Radarr.Http.REST; namespace Radarr.Http.RESTrictions { @@ -22,7 +22,10 @@ namespace Radarr.Http.RESTrictions { public static RestrictionResource ToResource(this Restriction model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RestrictionResource { @@ -37,7 +40,10 @@ namespace Radarr.Http.RESTrictions public static Restriction ToModel(this RestrictionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Restriction { diff --git a/src/NzbDrone.Api/RootFolders/RootFolderModule.cs b/src/NzbDrone.Api/RootFolders/RootFolderModule.cs index 2f87df9b3..0239c4d65 100644 --- a/src/NzbDrone.Api/RootFolders/RootFolderModule.cs +++ b/src/NzbDrone.Api/RootFolders/RootFolderModule.cs @@ -18,9 +18,8 @@ namespace NzbDrone.Api.RootFolders MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) - : base(signalRBroadcaster) + FolderWritableValidator folderWritableValidator) + : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/NzbDrone.Api/RootFolders/RootFolderResource.cs b/src/NzbDrone.Api/RootFolders/RootFolderResource.cs index 4c19a23fa..0f4dc80b3 100644 --- a/src/NzbDrone.Api/RootFolders/RootFolderResource.cs +++ b/src/NzbDrone.Api/RootFolders/RootFolderResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.RootFolders; +using Radarr.Http.REST; namespace NzbDrone.Api.RootFolders { @@ -18,7 +18,10 @@ namespace NzbDrone.Api.RootFolders { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -33,7 +36,10 @@ namespace NzbDrone.Api.RootFolders public static RootFolder ToModel(this RootFolderResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RootFolder { diff --git a/src/NzbDrone.Api/System/Backup/BackupModule.cs b/src/NzbDrone.Api/System/Backup/BackupModule.cs index 7fb99402e..c92e12d2a 100644 --- a/src/NzbDrone.Api/System/Backup/BackupModule.cs +++ b/src/NzbDrone.Api/System/Backup/BackupModule.cs @@ -9,7 +9,8 @@ namespace NzbDrone.Api.System.Backup { private readonly IBackupService _backupService; - public BackupModule(IBackupService backupService) : base("system/backup") + public BackupModule(IBackupService backupService) + : base("system/backup") { _backupService = backupService; GetResourceAll = GetBackupFiles; @@ -20,13 +21,13 @@ namespace NzbDrone.Api.System.Backup var backups = _backupService.GetBackups(); return backups.Select(b => new BackupResource - { - Id = b.Name.GetHashCode(), - Name = b.Name, - Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", - Type = b.Type, - Time = b.Time - }).ToList(); + { + Id = b.Name.GetHashCode(), + Name = b.Name, + Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", + Type = b.Type, + Time = b.Time + }).ToList(); } } } diff --git a/src/NzbDrone.Api/System/Backup/BackupResource.cs b/src/NzbDrone.Api/System/Backup/BackupResource.cs index f94ca56e8..08f84a646 100644 --- a/src/NzbDrone.Api/System/Backup/BackupResource.cs +++ b/src/NzbDrone.Api/System/Backup/BackupResource.cs @@ -1,6 +1,6 @@ using System; -using Radarr.Http.REST; using NzbDrone.Core.Backup; +using Radarr.Http.REST; namespace NzbDrone.Api.System.Backup { diff --git a/src/NzbDrone.Api/System/SystemModule.cs b/src/NzbDrone.Api/System/SystemModule.cs index 03678cb5a..137e7aecc 100644 --- a/src/NzbDrone.Api/System/SystemModule.cs +++ b/src/NzbDrone.Api/System/SystemModule.cs @@ -25,7 +25,8 @@ namespace NzbDrone.Api.System IRouteCacheProvider routeCacheProvider, IConfigFileProvider configFileProvider, IMainDatabase database, - ILifecycleService lifecycleService) : base("system") + ILifecycleService lifecycleService) + : base("system") { _appFolderInfo = appFolderInfo; _runtimeInfo = runtimeInfo; @@ -35,10 +36,10 @@ namespace NzbDrone.Api.System _configFileProvider = configFileProvider; _database = database; _lifecycleService = lifecycleService; - Get("/status", x => GetStatus()); - Get("/routes", x => GetRoutes()); - Post("/shutdown", x => Shutdown()); - Post("/restart", x => Restart()); + Get("/status", x => GetStatus()); + Get("/routes", x => GetRoutes()); + Post("/shutdown", x => Shutdown()); + Post("/restart", x => Restart()); } private object GetStatus() diff --git a/src/NzbDrone.Api/System/Tasks/TaskModule.cs b/src/NzbDrone.Api/System/Tasks/TaskModule.cs index 4b9667e89..af966e242 100644 --- a/src/NzbDrone.Api/System/Tasks/TaskModule.cs +++ b/src/NzbDrone.Api/System/Tasks/TaskModule.cs @@ -32,14 +32,14 @@ namespace NzbDrone.Api.System.Tasks var taskName = scheduledTask.TypeName.Split('.').Last().Replace("Command", ""); return new TaskResource - { - Id = scheduledTask.Id, - Name = NameRegex.Replace(taskName, match => " " + match.Value), - TaskName = taskName, - Interval = scheduledTask.Interval, - LastExecution = scheduledTask.LastExecution, - NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) - }; + { + Id = scheduledTask.Id, + Name = NameRegex.Replace(taskName, match => " " + match.Value), + TaskName = taskName, + Interval = scheduledTask.Interval, + LastExecution = scheduledTask.LastExecution, + NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) + }; } public void Handle(CommandExecutedEvent message) diff --git a/src/NzbDrone.Api/Tags/TagResource.cs b/src/NzbDrone.Api/Tags/TagResource.cs index c22b0e38a..bcc2c58d2 100644 --- a/src/NzbDrone.Api/Tags/TagResource.cs +++ b/src/NzbDrone.Api/Tags/TagResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Tags; +using Radarr.Http.REST; namespace NzbDrone.Api.Tags { @@ -14,7 +14,10 @@ namespace NzbDrone.Api.Tags { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -26,7 +29,10 @@ namespace NzbDrone.Api.Tags public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/NzbDrone.Api/Update/UpdateResource.cs b/src/NzbDrone.Api/Update/UpdateResource.cs index f07dd1853..dc7f60641 100644 --- a/src/NzbDrone.Api/Update/UpdateResource.cs +++ b/src/NzbDrone.Api/Update/UpdateResource.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; using NzbDrone.Core.Update; +using Radarr.Http.REST; namespace NzbDrone.Api.Update { @@ -27,7 +27,10 @@ namespace NzbDrone.Api.Update { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -37,6 +40,7 @@ namespace NzbDrone.Api.Update ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs b/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs index 002ecf179..51b7ba624 100644 --- a/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs +++ b/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs @@ -3,9 +3,10 @@ using Nancy; namespace NzbDrone.Api.Wanted { - class LegacyMissingModule : NzbDroneApiModule + public class LegacyMissingModule : NzbDroneApiModule { - public LegacyMissingModule() : base("missing") + public LegacyMissingModule() + : base("missing") { Get("/", x => { diff --git a/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs b/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs index d734fb645..c96b12f1a 100644 --- a/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs +++ b/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs @@ -1,10 +1,10 @@ using System.Linq; using NzbDrone.Api.Movies; -using NzbDrone.Core.Movies; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.SignalR; using Radarr.Http; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Api.Wanted { diff --git a/src/NzbDrone.Api/Wanted/MovieMissingModule.cs b/src/NzbDrone.Api/Wanted/MovieMissingModule.cs index 676b69da6..3fe30f1ac 100644 --- a/src/NzbDrone.Api/Wanted/MovieMissingModule.cs +++ b/src/NzbDrone.Api/Wanted/MovieMissingModule.cs @@ -1,14 +1,14 @@ using System.Linq; using NzbDrone.Api.Movies; +using NzbDrone.Core.Datastore; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Movies; -using NzbDrone.Core.Datastore; using NzbDrone.SignalR; using Radarr.Http; namespace NzbDrone.Api.Wanted { - class MovieMissingModule : MovieModuleWithSignalR + public class MovieMissingModule : MovieModuleWithSignalR { public MovieMissingModule(IMovieService movieService, IUpgradableSpecification qualityUpgradableSpecification, diff --git a/src/NzbDrone.Automation.Test/AutomationTest.cs b/src/NzbDrone.Automation.Test/AutomationTest.cs index f58988935..721d5eb82 100644 --- a/src/NzbDrone.Automation.Test/AutomationTest.cs +++ b/src/NzbDrone.Automation.Test/AutomationTest.cs @@ -37,8 +37,9 @@ namespace NzbDrone.Automation.Test var options = new FirefoxOptions(); options.AddArguments("--headless"); FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(); + // service.Host = "::1"; // Workaround netcore/selenium bug https://github.com/SeleniumHQ/selenium/issues/7840 - driver = new FirefoxDriver(service, options, new System.TimeSpan(0,3,0)); + driver = new FirefoxDriver(service, options, new System.TimeSpan(0, 3, 0)); _runner = new NzbDroneRunner(LogManager.GetCurrentClassLogger()); _runner.KillAll(); diff --git a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs index 041c0bddd..2ed2fac7e 100644 --- a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs +++ b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Automation.Test public AutomationTestAttribute() : base("AutomationTest") { - } } } diff --git a/src/NzbDrone.Automation.Test/MainPagesTest.cs b/src/NzbDrone.Automation.Test/MainPagesTest.cs index c3a48415c..acf8c2b05 100644 --- a/src/NzbDrone.Automation.Test/MainPagesTest.cs +++ b/src/NzbDrone.Automation.Test/MainPagesTest.cs @@ -8,62 +8,62 @@ namespace NzbDrone.Automation.Test [TestFixture] public class MainPagesTest : AutomationTest { - private PageBase page; + private PageBase _page; [SetUp] public void Setup() { - page = new PageBase(driver); + _page = new PageBase(driver); } [Test] public void movie_page() { - page.MovieNavIcon.Click(); - page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='MovieIndex']")).Should().NotBeNull(); + _page.MovieNavIcon.Click(); + _page.WaitForNoSpinner(); + _page.Find(By.CssSelector("div[class*='MovieIndex']")).Should().NotBeNull(); } [Test] public void calendar_page() { - page.CalendarNavIcon.Click(); - page.WaitForNoSpinner(); + _page.CalendarNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); + _page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); } [Test] public void activity_page() { - page.ActivityNavIcon.Click(); - page.WaitForNoSpinner(); + _page.ActivityNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Queue")).Should().NotBeNull(); - page.Find(By.LinkText("History")).Should().NotBeNull(); - page.Find(By.LinkText("Blacklist")).Should().NotBeNull(); + _page.Find(By.LinkText("Queue")).Should().NotBeNull(); + _page.Find(By.LinkText("History")).Should().NotBeNull(); + _page.Find(By.LinkText("Blacklist")).Should().NotBeNull(); } [Test] public void system_page() { - page.SystemNavIcon.Click(); - page.WaitForNoSpinner(); + _page.SystemNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); + _page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); } [Test] public void add_movie_page() { - page.MovieNavIcon.Click(); - page.WaitForNoSpinner(); + _page.MovieNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Add New")).Click(); + _page.Find(By.LinkText("Add New")).Click(); - page.WaitForNoSpinner(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("input[class*='AddNewMovie-searchInput']")).Should().NotBeNull(); + _page.Find(By.CssSelector("input[class*='AddNewMovie-searchInput']")).Should().NotBeNull(); } } } diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs index 082dd0f98..7c892047d 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.CacheTests _cachedString.Get("Test", _worker.GetString); _worker.HitCount.Should().Be(1); - } [Test] @@ -38,7 +37,6 @@ namespace NzbDrone.Common.Test.CacheTests first.Should().Be(second); } - [Test] public void should_be_able_to_update_key() { @@ -48,7 +46,6 @@ namespace NzbDrone.Common.Test.CacheTests _cachedString.Find("Key").Should().Be("New"); } - [Test] public void should_be_able_to_remove_key() { @@ -70,7 +67,6 @@ namespace NzbDrone.Common.Test.CacheTests { int hitCount = 0; - for (int i = 0; i < 10; i++) { _cachedString.Get("key", () => @@ -92,11 +88,13 @@ namespace NzbDrone.Common.Test.CacheTests for (int i = 0; i < 10; i++) { - _cachedString.Get("key", () => - { - hitCount++; - return null; - }, TimeSpan.FromMilliseconds(300)); + _cachedString.Get("key", + () => + { + hitCount++; + return null; + }, + TimeSpan.FromMilliseconds(300)); Thread.Sleep(100); } diff --git a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs index 4472c747d..82c2f854e 100644 --- a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs +++ b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs @@ -62,10 +62,8 @@ namespace NzbDrone.Common.Test const string key = "Port"; const int value = 7878; - var result = Subject.GetValueInt(key, value); - result.Should().Be(value); } @@ -75,20 +73,16 @@ namespace NzbDrone.Common.Test const string key = "LaunchBrowser"; const bool value = true; - var result = Subject.GetValueBoolean(key, value); - result.Should().BeTrue(); } [Test] public void GetLaunchBrowser_Success() { - var result = Subject.LaunchBrowser; - result.Should().Be(true); } @@ -97,10 +91,8 @@ namespace NzbDrone.Common.Test { const int value = 7878; - var result = Subject.Port; - result.Should().Be(value); } @@ -110,10 +102,8 @@ namespace NzbDrone.Common.Test const string key = "LaunchBrowser"; const bool value = false; - Subject.SetValue(key, value); - var result = Subject.LaunchBrowser; result.Should().Be(value); } @@ -124,10 +114,8 @@ namespace NzbDrone.Common.Test const string key = "Port"; const int value = 12345; - Subject.SetValue(key, value); - var result = Subject.Port; result.Should().Be(value); } @@ -138,10 +126,8 @@ namespace NzbDrone.Common.Test const string key = "Hello"; const string value = "World"; - var result = Subject.GetValue(key, value); - result.Should().Be(value); } @@ -178,7 +164,6 @@ namespace NzbDrone.Common.Test dic["SslPort"] = origSslPort; Subject.SaveConfigDictionary(dic); - dic = new Dictionary(); dic["SslPort"] = sslPort; Subject.SaveConfigDictionary(dic); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs index bdca59161..73df8d847 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs @@ -7,7 +7,8 @@ using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.DiskTests { - public abstract class DiskProviderFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class DiskProviderFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] [Retry(5)] @@ -171,7 +172,7 @@ namespace NzbDrone.Common.Test.DiskTests public void should_return_false_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.IsFileLocked(testFile).Should().BeFalse(); } @@ -180,7 +181,7 @@ namespace NzbDrone.Common.Test.DiskTests public void should_return_false_for_unlocked_and_readonly_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); File.SetAttributes(testFile, FileAttributes.ReadOnly); @@ -191,7 +192,7 @@ namespace NzbDrone.Common.Test.DiskTests public void should_return_true_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); using (var file = File.OpenWrite(testFile)) { @@ -203,7 +204,7 @@ namespace NzbDrone.Common.Test.DiskTests public void should_be_able_to_set_permission_from_parrent() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.InheritFolderPermissions(testFile); } @@ -212,7 +213,7 @@ namespace NzbDrone.Common.Test.DiskTests public void should_be_set_last_file_write() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); var lastWriteTime = DateTime.SpecifyKind(new DateTime(2012, 1, 2), DateTimeKind.Utc); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs index e0e2ddf98..8c1fab599 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs @@ -535,7 +535,10 @@ namespace NzbDrone.Common.Test.DiskTests .Callback(() => { WithExistingFile(_tempTargetPath, true, 900); - if (retry++ == 1) WithExistingFile(_tempTargetPath, true, 1000); + if (retry++ == 1) + { + WithExistingFile(_tempTargetPath, true, 1000); + } }); var result = Subject.TransferFile(_sourcePath, _targetPath, TransferMode.Copy); @@ -554,7 +557,10 @@ namespace NzbDrone.Common.Test.DiskTests .Callback(() => { WithExistingFile(_tempTargetPath, true, 900); - if (retry++ == 3) throw new Exception("Test Failed, retried too many times."); + if (retry++ == 3) + { + throw new Exception("Test Failed, retried too many times."); + } }); Assert.Throws(() => Subject.TransferFile(_sourcePath, _targetPath, TransferMode.Copy)); @@ -932,7 +938,9 @@ namespace NzbDrone.Common.Test.DiskTests { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FolderExists(path)) @@ -943,7 +951,9 @@ namespace NzbDrone.Common.Test.DiskTests { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FileExists(path)) @@ -997,7 +1007,6 @@ namespace NzbDrone.Common.Test.DiskTests WithExistingFile(v, false); }); - Mocker.GetMock() .Setup(v => v.FolderExists(It.IsAny())) .Returns(false); @@ -1015,6 +1024,7 @@ namespace NzbDrone.Common.Test.DiskTests { WithExistingFolder(s, false); WithExistingFolder(d); + // Note: Should also deal with the files. }); @@ -1023,6 +1033,7 @@ namespace NzbDrone.Common.Test.DiskTests .Callback((f, r) => { WithExistingFolder(f, false); + // Note: Should also deal with the files. }); @@ -1053,7 +1064,7 @@ namespace NzbDrone.Common.Test.DiskTests Mocker.GetMock() .Setup(v => v.DeleteFolder(It.IsAny(), It.IsAny())) - .Callback((v,r) => Directory.Delete(v, r)); + .Callback((v, r) => Directory.Delete(v, r)); Mocker.GetMock() .Setup(v => v.DeleteFile(It.IsAny())) @@ -1081,8 +1092,13 @@ namespace NzbDrone.Common.Test.DiskTests Mocker.GetMock() .Setup(v => v.MoveFile(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((s,d,o) => { - if (File.Exists(d) && o) File.Delete(d); + .Callback((s, d, o) => + { + if (File.Exists(d) && o) + { + File.Delete(d); + } + File.Move(s, d); }); diff --git a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs index efef3e1c9..63d973946 100644 --- a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs @@ -7,7 +7,8 @@ using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.DiskTests { - public abstract class FreeSpaceFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class FreeSpaceFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Ignore("Docker")] [Test] @@ -58,10 +59,12 @@ namespace NzbDrone.Common.Test.DiskTests WindowsOnly(); // Find a drive that doesn't exist. - for (char driveletter = 'Z'; driveletter > 'D' ; driveletter--) + for (char driveletter = 'Z'; driveletter > 'D'; driveletter--) { if (new DriveInfo(driveletter.ToString()).IsReady) + { continue; + } Assert.Throws(() => Subject.GetAvailableSpace(driveletter + @":\NOT_A_REAL_PATH\DOES_NOT_EXIST".AsOsAgnostic())); return; diff --git a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs index 641141358..53c1b42f4 100644 --- a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Common.Test.EnsureTest Ensure.That(path, () => path).IsValidPath(); } - [TestCase(@"/var/user/file with, comma.mkv")] public void EnsureLinuxPath(string path) { diff --git a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs index dd7e8fcf0..1d9936a8b 100644 --- a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs @@ -10,13 +10,11 @@ namespace NzbDrone.Common.Test [TestFixture] public class IAppDirectoryInfoTest : TestBase { - [Test] public void StartupPath_should_not_be_empty() { Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace(); Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted"); - } [Test] diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs index 826cf9520..a4f0bdc6d 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs @@ -9,13 +9,11 @@ namespace NzbDrone.Common.Test.EnvironmentTests [TestFixture] public class BuildInfoTest : TestBase { - [TestCase("0.0.0.0")] [TestCase("1.0.0.0")] public void Application_version_should_not_be_default(string version) { BuildInfo.Version.Should().NotBe(new Version(version)); } - } } diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs index dd7f858f8..07df9c79e 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests args.Flags.Contains("t").Should().BeTrue(); } - [TestCase("/key=value")] [TestCase("/KEY=value")] [TestCase(" /key=\"value\"")] @@ -37,7 +36,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests args.Args["key"].Should().Be("value"); } - [TestCase("/data=test", "/data=test")] [TestCase("/Data=/a/b/c", "/data=/a/b/c")] public void should_preserver_data(string arg, string preserved) @@ -55,7 +53,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests args.PreservedArguments.Should().Be(preserved); } - [Test] public void should_preserver_both() { diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs index 1688fd8c4..2b7ef935b 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs @@ -56,7 +56,7 @@ namespace NzbDrone.Common.Test.ExtensionTests.IEnumerableExtensionTests var result = first.ExceptBy(o => o.Prop1, second, o => o.Prop1, StringComparer.InvariantCultureIgnoreCase).ToList(); result.Should().HaveCount(1); - result.First().GetType().Should().Be(typeof (Object1)); + result.First().GetType().Should().Be(typeof(Object1)); result.First().Prop1.Should().Be("two"); } } diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs index 944f7417a..ff5d7383e 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs @@ -24,7 +24,6 @@ namespace NzbDrone.Common.Test.ExtensionTests public void should_return_false_for_public_ip_address(string ipAddress) { IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse(); - } } } diff --git a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs index 16c15a6f6..13b78e52d 100644 --- a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs @@ -22,7 +22,8 @@ namespace NzbDrone.Common.Test.Http { [IntegrationTest] [TestFixture(typeof(ManagedHttpDispatcher))] - public class HttpClientFixture : TestBase where TDispatcher : IHttpDispatcher + public class HttpClientFixture : TestBase + where TDispatcher : IHttpDispatcher { private string[] _httpBinHosts; private int _httpBinSleep; @@ -34,6 +35,7 @@ namespace NzbDrone.Common.Test.Http public void FixtureSetUp() { var candidates = new[] { "eu.httpbin.org", /*"httpbin.org",*/ "www.httpbin.org" }; + // httpbin.org is broken right now, occassionally redirecting to https if it's unavailable. _httpBinHosts = candidates.Where(IsTestSiteAvailable).ToArray(); @@ -48,7 +50,10 @@ namespace NzbDrone.Common.Test.Http { var req = WebRequest.Create($"http://{site}/get") as HttpWebRequest; var res = req.GetResponse() as HttpWebResponse; - if (res.StatusCode != HttpStatusCode.OK) return false; + if (res.StatusCode != HttpStatusCode.OK) + { + return false; + } try { @@ -60,7 +65,10 @@ namespace NzbDrone.Common.Test.Http res = ex.Response as HttpWebResponse; } - if (res == null || res.StatusCode != (HttpStatusCode)429) return false; + if (res == null || res.StatusCode != (HttpStatusCode)429) + { + return false; + } return true; } @@ -617,7 +625,7 @@ namespace NzbDrone.Common.Test.Http [Test] public void should_call_interceptor() { - Mocker.SetConstant>(new [] { Mocker.GetMock().Object }); + Mocker.SetConstant>(new[] { Mocker.GetMock().Object }); Mocker.GetMock() .Setup(v => v.PreRequest(It.IsAny())) diff --git a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs index e0a22072e..e5221e408 100644 --- a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs @@ -1,11 +1,11 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using System; -using System.Text; -using NzbDrone.Common.Http; +using System; using System.Collections.Specialized; using System.Linq; +using System.Text; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.Http { diff --git a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs index 2c2c718e6..4af9bb501 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs @@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test.Http var request = builder.Resource("/v1/").Build(); request.Url.FullUri.Should().Be("http://domain/v1/"); - } } } diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs index 0dcee3165..8a61ef050 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Instrumentation; -using FluentAssertions; namespace NzbDrone.Common.Test.InstrumentationTests { @@ -17,9 +17,11 @@ namespace NzbDrone.Common.Test.InstrumentationTests [TestCase(@"https://baconbits.org/feeds.php?feed=torrents_tv&user=12345&auth=2b51db35e1910123321025a12b9933d2&passkey=mySecret&authkey=2b51db35e1910123321025a12b9933d2")] [TestCase(@"http://127.0.0.1:9117/dl/indexername?jackett_apikey=flwjiefewklfjacketmySecretsdfldskjfsdlk&path=we0re9f0sdfbase64sfdkfjsdlfjk&file=The+Torrent+File+Name.torrent")] [TestCase(@"http://nzb.su/getnzb/2b51db35e1912ffc138825a12b9933d2.nzb&i=37292&r=2b51db35e1910123321025a12b9933d2")] + // NzbGet [TestCase(@"{ ""Name"" : ""ControlUsername"", ""Value"" : ""mySecret"" }, { ""Name"" : ""ControlPassword"", ""Value"" : ""mySecret"" }, ")] [TestCase(@"{ ""Name"" : ""Server1.Username"", ""Value"" : ""mySecret"" }, { ""Name"" : ""Server1.Password"", ""Value"" : ""mySecret"" }, ")] + // Sabnzbd [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&apikey=mySecret")] [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&ma_username=mySecret&ma_password=mySecret")] @@ -30,6 +32,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests [TestCase(@"""misc"":{""username"":""mySecret"",""api_key"":""mySecret"",""password"":""mySecret"",""nzb_key"":""mySecret""}")] [TestCase(@"""servers"":[{""username"":""mySecret"",""password"":""mySecret""}]")] [TestCase(@"""misc"":{""email_account"":""mySecret"",""email_to"":[],""email_from"":"""",""email_pwd"":""mySecret""}")] + // uTorrent [TestCase(@"http://localhost:9091/gui/?token=wThmph5l0ZXfH-a6WOA4lqiLvyjCP0FpMrMeXmySecret_VXBO11HoKL751MAAAAA&list=1")] [TestCase(@",[""boss_key"",0,""mySecret"",{""access"":""Y""}],[""boss_key_salt"",0,""mySecret"",{""access"":""W""}]")] @@ -37,10 +40,12 @@ namespace NzbDrone.Common.Test.InstrumentationTests [TestCase(@",[""webui.uconnect_username"",2,""mySecret"",{""access"":""Y""}],[""webui.uconnect_password"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.proxy"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.username"",2,""mySecret"",{""access"":""Y""}],[""proxy.password"",2,""mySecret"",{""access"":""Y""}]")] + // Deluge [TestCase(@",{""download_location"": ""C:\Users\\mySecret mySecret\\Downloads""}")] [TestCase(@",{""download_location"": ""/home/mySecret/Downloads""}")] [TestCase(@"auth.login(""mySecret"")")] + // BroadcastheNet [TestCase(@"method: ""getTorrents"", ""params"": [ ""mySecret"",")] [TestCase(@"getTorrents(""mySecret"", [asdfasdf], 100, 0)")] diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs index 1aec7ca88..0b8a6f15d 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs @@ -1,24 +1,25 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Instrumentation.Sentry; -using System; -using NLog; -using NzbDrone.Test.Common; +using System; using System.Globalization; using System.Linq; +using FluentAssertions; +using NLog; +using NUnit.Framework; +using NzbDrone.Common.Instrumentation.Sentry; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.InstrumentationTests { [TestFixture] public class SentryTargetFixture : TestBase { - private SentryTarget Subject; + private SentryTarget _subject; private static LogLevel[] AllLevels = LogLevel.AllLevels.ToArray(); private static LogLevel[] SentryLevels = LogLevel.AllLevels.Where(x => x >= LogLevel.Error).ToArray(); private static LogLevel[] OtherLevels = AllLevels.Except(SentryLevels).ToArray(); - private static Exception[] FilteredExceptions = new Exception[] { + private static Exception[] FilteredExceptions = new Exception[] + { new UnauthorizedAccessException(), new TinyIoC.TinyIoCResolutionException(typeof(string)) }; @@ -26,7 +27,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests [SetUp] public void Setup() { - Subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); + _subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); } private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) @@ -34,44 +35,50 @@ namespace NzbDrone.Common.Test.InstrumentationTests return LogEventInfo.Create(level, "SentryTest", ex, CultureInfo.InvariantCulture, message); } - [Test, TestCaseSource("AllLevels")] + [Test] + [TestCaseSource("AllLevels")] public void log_without_error_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); } - [Test, TestCaseSource("SentryLevels")] + [Test] + [TestCaseSource("SentryLevels")] public void error_or_worse_with_exception_is_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); } - [Test, TestCaseSource("OtherLevels")] + [Test] + [TestCaseSource("OtherLevels")] public void less_than_error_with_exception_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_filter_event_for_filtered_exception_types(Exception ex) { var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_not_filter_event_for_filtered_exception_types_if_filtering_disabled(Exception ex) { - Subject.FilterEvents = false; + _subject.FilterEvents = false; var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } - [Test, TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] + [Test] + [TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] public void should_filter_event_for_filtered_exception_messages(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception("aaaaaaa" + message + "bbbbbbb"), "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } [TestCase("A message that isn't filtered")] @@ -79,7 +86,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests public void should_not_filter_event_for_exception_messages_that_are_not_filtered(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception(message), "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } } } diff --git a/src/NzbDrone.Common.Test/OsPathFixture.cs b/src/NzbDrone.Common.Test/OsPathFixture.cs index a7c20f866..6d79e0cfc 100644 --- a/src/NzbDrone.Common.Test/OsPathFixture.cs +++ b/src/NzbDrone.Common.Test/OsPathFixture.cs @@ -1,7 +1,7 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test { diff --git a/src/NzbDrone.Common.Test/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/PathExtensionFixture.cs index 9b3efc264..e18a3d7b2 100644 --- a/src/NzbDrone.Common.Test/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/PathExtensionFixture.cs @@ -110,6 +110,7 @@ namespace NzbDrone.Common.Test _parent.IsParentPath(path).Should().BeTrue(); } + [TestCase(@"C:\Test\", @"C:\Test\mydir")] [TestCase(@"C:\Test\", @"C:\Test\mydir\")] [TestCase(@"C:\Test", @"C:\Test\30.Rock.S01E01.Pilot.avi")] @@ -163,8 +164,7 @@ namespace NzbDrone.Common.Test // This test will fail on Windows if long path support is not enabled: https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/ // It will also fail if the app isn't configured to use long path (such as resharper): https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/ - - var path = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories".AsOsAgnostic(); + var path = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories".AsOsAgnostic(); var parentPath = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing".AsOsAgnostic(); path.GetParentPath().Should().Be(parentPath); @@ -198,10 +198,9 @@ namespace NzbDrone.Common.Test public void get_actual_casing_for_none_existing_file_return_partially_fixed_result() { WindowsOnly(); - "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); + "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); } - [Test] public void get_actual_casing_for_none_existing_folder_return_partially_fixed_result() { @@ -218,12 +217,11 @@ namespace NzbDrone.Common.Test path.ToLower().GetActualCasing().Should().Be(path); } - [Test] public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows() { WindowsOnly(); - var path = Directory.GetCurrentDirectory().Replace("c:\\","C:\\").Replace("d:\\","D:\\").Replace("system32", "System32"); + var path = Directory.GetCurrentDirectory().Replace("c:\\", "C:\\").Replace("d:\\", "D:\\").Replace("system32", "System32"); path.ToUpper().GetActualCasing().Should().Be(path); path.ToLower().GetActualCasing().Should().Be(path); diff --git a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs index 2587d86ad..b81bbfa19 100644 --- a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Common.Test [TestFixture] public class ProcessProviderFixture : TestBase { - [SetUp] public void Setup() { @@ -43,7 +42,6 @@ namespace NzbDrone.Common.Test { TestLogger.Warn(ex, "{0} when killing process", ex.Message); } - }); } @@ -85,7 +83,7 @@ namespace NzbDrone.Common.Test } [Test] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] [Retry(3)] public void exists_should_find_running_process() { @@ -153,7 +151,7 @@ namespace NzbDrone.Common.Test [Test] [Retry(3)] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public void kill_all_should_kill_all_process_with_name() { var dummy1 = StartDummyProcess(); @@ -182,12 +180,13 @@ namespace NzbDrone.Common.Test } var path = Path.Combine(TestContext.CurrentContext.TestDirectory, DummyApp.DUMMY_PROCCESS_NAME + suffix); - var process = Subject.Start(path, onOutputDataReceived: (string data) => { - if (data.StartsWith("Dummy process. ID:")) - { - processStarted.Set(); - } - }); + var process = Subject.Start(path, onOutputDataReceived: (string data) => + { + if (data.StartsWith("Dummy process. ID:")) + { + processStarted.Set(); + } + }); if (!processStarted.Wait(5000)) { diff --git a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs index c1ec37ff1..830e2af44 100644 --- a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs @@ -5,8 +5,8 @@ using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Datastore; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.Common.Test { diff --git a/src/NzbDrone.Common.Test/ServiceProviderTests.cs b/src/NzbDrone.Common.Test/ServiceProviderTests.cs index 9b5bb7d63..99aafe627 100644 --- a/src/NzbDrone.Common.Test/ServiceProviderTests.cs +++ b/src/NzbDrone.Common.Test/ServiceProviderTests.cs @@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test } } - private void CleanupService() { if (Subject.ServiceExist(TEMP_SERVICE_NAME)) @@ -61,7 +60,6 @@ namespace NzbDrone.Common.Test Subject.ServiceExist("random_service_name").Should().BeFalse(); } - [Test] public void Service_should_be_installed_and_then_uninstalled() { @@ -121,7 +119,6 @@ namespace NzbDrone.Common.Test Subject.Start(ALWAYS_INSTALLED_SERVICE); Assert.Throws(() => Subject.Start(ALWAYS_INSTALLED_SERVICE)); - ExceptionVerification.ExpectedWarns(1); } @@ -131,15 +128,14 @@ namespace NzbDrone.Common.Test Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().NotBe(ServiceControllerStatus.Running); - Subject.Stop(ALWAYS_INSTALLED_SERVICE); - Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().Be(ServiceControllerStatus.Stopped); ExceptionVerification.ExpectedWarns(1); } + private static bool IsAnAdministrator() { var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); diff --git a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs index 7f47b337b..4b7349f4a 100644 --- a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Common.Test.TPLTests } } - [Test] [Retry(3)] public void should_hold_the_call_for_debounce_duration() @@ -34,11 +33,9 @@ namespace NzbDrone.Common.Test.TPLTests counter.Count.Should().Be(0); - Thread.Sleep(100); counter.Count.Should().Be(1); - } [Test] @@ -54,7 +51,6 @@ namespace NzbDrone.Common.Test.TPLTests counter.Count.Should().Be(0); - Thread.Sleep(200); debounceFunction.Execute(); @@ -64,7 +60,6 @@ namespace NzbDrone.Common.Test.TPLTests Thread.Sleep(200); counter.Count.Should().Be(2); - } [Test] diff --git a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs index 539e3a62a..919868458 100644 --- a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Concurrent; using System.Diagnostics; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Cache; using NzbDrone.Common.TPL; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test.TPLTests { diff --git a/src/NzbDrone.Common/ArchiveService.cs b/src/NzbDrone.Common/ArchiveService.cs index 2a45d7215..57335ae7c 100644 --- a/src/NzbDrone.Common/ArchiveService.cs +++ b/src/NzbDrone.Common/ArchiveService.cs @@ -73,11 +73,12 @@ namespace NzbDrone.Common { continue; // Ignore directories } + string entryFileName = zipEntry.Name; + // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. - byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zipFile.GetInputStream(zipEntry); @@ -85,7 +86,9 @@ namespace NzbDrone.Common string fullZipToPath = Path.Combine(destination, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) + { Directory.CreateDirectory(directoryName); + } // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. diff --git a/src/NzbDrone.Common/Cache/CacheManager.cs b/src/NzbDrone.Common/Cache/CacheManager.cs index 1b6c945e5..6c080a02e 100644 --- a/src/NzbDrone.Common/Cache/CacheManager.cs +++ b/src/NzbDrone.Common/Cache/CacheManager.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Common.Cache public CacheManager() { _cache = new Cached(); - } public void Clear() diff --git a/src/NzbDrone.Common/Cache/Cached.cs b/src/NzbDrone.Common/Cache/Cached.cs index d4e98be46..2285f548d 100644 --- a/src/NzbDrone.Common/Cache/Cached.cs +++ b/src/NzbDrone.Common/Cache/Cached.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.EnsureThat; namespace NzbDrone.Common.Cache { - public class Cached : ICached { private class CacheItem @@ -109,6 +108,5 @@ namespace NzbDrone.Common.Cache return _store.Values.Select(c => c.Object).ToList(); } } - } } diff --git a/src/NzbDrone.Common/Cache/CachedDictionary.cs b/src/NzbDrone.Common/Cache/CachedDictionary.cs index 7bbda022a..6332f5054 100644 --- a/src/NzbDrone.Common/Cache/CachedDictionary.cs +++ b/src/NzbDrone.Common/Cache/CachedDictionary.cs @@ -5,7 +5,6 @@ using System.Diagnostics; namespace NzbDrone.Common.Cache { - public class CachedDictionary : ICachedDictionary { private readonly Func> _fetchFunc; @@ -34,7 +33,7 @@ namespace NzbDrone.Common.Cache } public void RefreshIfExpired(TimeSpan ttl) - { + { if (IsExpired(ttl)) { Refresh(); diff --git a/src/NzbDrone.Common/Composition/Container.cs b/src/NzbDrone.Common/Composition/Container.cs index 1b8944a8d..d65d7d19b 100644 --- a/src/NzbDrone.Common/Composition/Container.cs +++ b/src/NzbDrone.Common/Composition/Container.cs @@ -24,12 +24,14 @@ namespace NzbDrone.Common.Composition _container.Register(); } - public void Register(T instance) where T : class + public void Register(T instance) + where T : class { _container.Register(instance); } - public T Resolve() where T : class + public T Resolve() + where T : class { return _container.Resolve(); } @@ -44,7 +46,8 @@ namespace NzbDrone.Common.Composition _container.Register(serviceType, implementationType); } - public void Register(Func factory) where TService : class + public void Register(Func factory) + where TService : class { _container.Register((c, n) => factory(this)); } @@ -57,7 +60,8 @@ namespace NzbDrone.Common.Composition _container.Register(service, factory, implementation.FullName); } - public IEnumerable ResolveAll() where T : class + public IEnumerable ResolveAll() + where T : class { return _container.ResolveAll(); } @@ -92,8 +96,7 @@ namespace NzbDrone.Common.Composition .Where(implementation => contractType.IsAssignableFrom(implementation) && !implementation.IsInterface && - !implementation.IsAbstract - ); + !implementation.IsAbstract); } } } diff --git a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs index 6575f9236..09f7ec8c3 100644 --- a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs +++ b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs @@ -8,8 +8,8 @@ using TinyIoC; #if NETCOREAPP using System.IO; -using System.Runtime.Loader; using System.Runtime.InteropServices; +using System.Runtime.Loader; #endif namespace NzbDrone.Common.Composition @@ -33,15 +33,15 @@ namespace NzbDrone.Common.Composition _loadedTypes.AddRange(Assembly.Load(assembly).GetTypes()); } #else - var _startupPath = AppDomain.CurrentDomain.BaseDirectory; + var startupPath = AppDomain.CurrentDomain.BaseDirectory; foreach (var assemblyName in assemblies) { - _loadedTypes.AddRange(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(_startupPath, $"{assemblyName}.dll")).GetTypes()); + _loadedTypes.AddRange(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(startupPath, $"{assemblyName}.dll")).GetTypes()); } var toRegisterResolver = new List { "System.Data.SQLite" }; - toRegisterResolver.AddRange(assemblies.Intersect(new [] { "Radarr.Core" })); + toRegisterResolver.AddRange(assemblies.Intersect(new[] { "Radarr.Core" })); RegisterNativeResolver(toRegisterResolver); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ContainerResolveEventHandler); #endif @@ -54,8 +54,8 @@ namespace NzbDrone.Common.Composition #if NETCOREAPP private static Assembly ContainerResolveEventHandler(object sender, ResolveEventArgs args) { - var _resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location); - var assemblyPath = _resolver.ResolveAssemblyToPath(new AssemblyName(args.Name)); + var resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location); + var assemblyPath = resolver.ResolveAssemblyToPath(new AssemblyName(args.Name)); if (assemblyPath == null) { @@ -72,8 +72,7 @@ namespace NzbDrone.Common.Composition foreach (var name in assemblyNames) { var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath( - Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll") - ); + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll")); try { @@ -134,6 +133,7 @@ namespace NzbDrone.Common.Composition { return; } + if (implementations.Count == 1) { var impl = implementations.Single(); diff --git a/src/NzbDrone.Common/Composition/IContainer.cs b/src/NzbDrone.Common/Composition/IContainer.cs index 1ba6c41f1..9e7402017 100644 --- a/src/NzbDrone.Common/Composition/IContainer.cs +++ b/src/NzbDrone.Common/Composition/IContainer.cs @@ -5,17 +5,21 @@ namespace NzbDrone.Common.Composition { public interface IContainer { - void Register(T instance) where T : class; + void Register(T instance) + where T : class; void Register() where TImplementation : class, TService where TService : class; - T Resolve() where T : class; + T Resolve() + where T : class; object Resolve(Type type); void Register(Type serviceType, Type implementationType); - void Register(Func factory) where TService : class; + void Register(Func factory) + where TService : class; void RegisterSingleton(Type service, Type implementation); - IEnumerable ResolveAll() where T : class; + IEnumerable ResolveAll() + where T : class; void RegisterAllAsSingleton(Type registrationType, IEnumerable implementationList); bool IsTypeRegistered(Type type); diff --git a/src/NzbDrone.Common/ConvertBase32.cs b/src/NzbDrone.Common/ConvertBase32.cs index 29cb3618e..3ee7803d5 100644 --- a/src/NzbDrone.Common/ConvertBase32.cs +++ b/src/NzbDrone.Common/ConvertBase32.cs @@ -16,7 +16,7 @@ int bitBufferCount = 0; int index = 0; - for (int i = 0; i < str.Length;i++ ) + for (int i = 0; i < str.Length; i++) { bitBuffer = (bitBuffer << 5) | ValidChars.IndexOf(str[i]); bitBufferCount += 5; diff --git a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs index 986413742..ffdc36e0e 100644 --- a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs +++ b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs @@ -10,19 +10,23 @@ namespace NzbDrone.Common.Disk { } - public DestinationAlreadyExistsException(string message) : base(message) + public DestinationAlreadyExistsException(string message) + : base(message) { } - public DestinationAlreadyExistsException(string message, int hresult) : base(message, hresult) + public DestinationAlreadyExistsException(string message, int hresult) + : base(message, hresult) { } - public DestinationAlreadyExistsException(string message, Exception innerException) : base(message, innerException) + public DestinationAlreadyExistsException(string message, Exception innerException) + : base(message, innerException) { } - protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) + protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/NzbDrone.Common/Disk/DiskProviderBase.cs b/src/NzbDrone.Common/Disk/DiskProviderBase.cs index 364a25824..81dccaa1c 100644 --- a/src/NzbDrone.Common/Disk/DiskProviderBase.cs +++ b/src/NzbDrone.Common/Disk/DiskProviderBase.cs @@ -114,10 +114,11 @@ namespace NzbDrone.Common.Disk { return File.Exists(path) && path == path.GetActualCasing(); } + default: - { - return File.Exists(path); - } + { + return File.Exists(path); + } } } @@ -362,9 +363,11 @@ namespace NzbDrone.Common.Disk return; } - var accessRule = new FileSystemAccessRule(sid, rights, + var accessRule = new FileSystemAccessRule(sid, + rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, - PropagationFlags.InheritOnly, controlType); + PropagationFlags.InheritOnly, + controlType); bool modified; directorySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out modified); @@ -379,7 +382,6 @@ namespace NzbDrone.Common.Disk Logger.Warn(e, "Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType); throw; } - } private static void RemoveReadOnly(string path) @@ -390,7 +392,7 @@ namespace NzbDrone.Common.Disk if (attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = attributes & ~(FileAttributes.ReadOnly); + var newAttributes = attributes & ~FileAttributes.ReadOnly; File.SetAttributes(path, newAttributes); } } @@ -404,7 +406,7 @@ namespace NzbDrone.Common.Disk if (dirInfo.Attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = dirInfo.Attributes & ~(FileAttributes.ReadOnly); + var newAttributes = dirInfo.Attributes & ~FileAttributes.ReadOnly; dirInfo.Attributes = newAttributes; } } diff --git a/src/NzbDrone.Common/Disk/DiskTransferService.cs b/src/NzbDrone.Common/Disk/DiskTransferService.cs index fac59ceb5..6c668e36b 100644 --- a/src/NzbDrone.Common/Disk/DiskTransferService.cs +++ b/src/NzbDrone.Common/Disk/DiskTransferService.cs @@ -81,14 +81,20 @@ namespace NzbDrone.Common.Disk foreach (var subDir in _diskProvider.GetDirectoryInfos(sourcePath)) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } result &= TransferFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name), mode, verificationMode); } foreach (var sourceFile in _diskProvider.GetFileInfos(sourcePath)) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var destFile = Path.Combine(targetPath, sourceFile.Name); @@ -122,14 +128,20 @@ namespace NzbDrone.Common.Disk foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } _diskProvider.DeleteFolder(subDir.FullName, true); } foreach (var subDir in sourceFolders) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name)); } @@ -139,14 +151,20 @@ namespace NzbDrone.Common.Disk foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(targetFile)) continue; + if (ShouldIgnore(targetFile)) + { + continue; + } _diskProvider.DeleteFile(targetFile.FullName); } foreach (var sourceFile in sourceFiles) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var targetFile = Path.Combine(targetPath, sourceFile.Name); @@ -279,6 +297,7 @@ namespace NzbDrone.Common.Disk { return TransferMode.HardLink; } + if (!mode.HasFlag(TransferMode.Copy)) { throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed."); @@ -291,7 +310,7 @@ namespace NzbDrone.Common.Disk var sourceMount = _diskProvider.GetMount(sourcePath); var targetMount = _diskProvider.GetMount(targetPath); - var isSameMount = (sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory); + var isSameMount = sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory; var sourceDriveFormat = sourceMount?.DriveFormat ?? string.Empty; var targetDriveFormat = targetMount?.DriveFormat ?? string.Empty; @@ -532,6 +551,7 @@ namespace NzbDrone.Common.Disk { throw new IOException(string.Format("Temporary file '{0}' still exists, aborting.", tempTargetPath)); } + _logger.Trace("Hardlink move succeeded, deleting source."); _diskProvider.DeleteFile(sourcePath); return true; diff --git a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs index a3aa8810d..e28a1c1cf 100644 --- a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs +++ b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs @@ -124,7 +124,6 @@ namespace NzbDrone.Common.Disk result.Files = GetFiles(path); } } - catch (DirectoryNotFoundException) { return new FileSystemResult { Parent = GetParent(path) }; diff --git a/src/NzbDrone.Common/Disk/NotParentException.cs b/src/NzbDrone.Common/Disk/NotParentException.cs index 0ae384722..4859c29be 100644 --- a/src/NzbDrone.Common/Disk/NotParentException.cs +++ b/src/NzbDrone.Common/Disk/NotParentException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Common.Disk { public class NotParentException : NzbDroneException { - public NotParentException(string message, params object[] args) : base(message, args) + public NotParentException(string message, params object[] args) + : base(message, args) { } - public NotParentException(string message) : base(message) + public NotParentException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Common/Disk/OsPath.cs b/src/NzbDrone.Common/Disk/OsPath.cs index 89bdb5073..02aaf6561 100644 --- a/src/NzbDrone.Common/Disk/OsPath.cs +++ b/src/NzbDrone.Common/Disk/OsPath.cs @@ -44,22 +44,36 @@ namespace NzbDrone.Common.Disk { return OsPathKind.Unix; } + if (HasWindowsDriveLetter(path) || path.Contains('\\')) { return OsPathKind.Windows; } + if (path.Contains('/')) { return OsPathKind.Unix; } + return OsPathKind.Unknown; } private static bool HasWindowsDriveLetter(string path) { - if (path.Length < 2) return false; - if (!char.IsLetter(path[0]) || path[1] != ':') return false; - if (path.Length > 2 && path[2] != '\\' && path[2] != '/') return false; + if (path.Length < 2) + { + return false; + } + + if (!char.IsLetter(path[0]) || path[1] != ':') + { + return false; + } + + if (path.Length > 2 && path[2] != '\\' && path[2] != '/') + { + return false; + } return true; } @@ -93,6 +107,7 @@ namespace NzbDrone.Common.Disk { return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path); } + if (IsUnixPath) { return _path.StartsWith("/"); @@ -191,10 +206,12 @@ namespace NzbDrone.Common.Disk { return Equals((OsPath)obj); } + if (obj is string) { return Equals(new OsPath(obj as string)); } + return false; } @@ -212,6 +229,7 @@ namespace NzbDrone.Common.Disk case OsPathKind.Unix: return new OsPath(_path.TrimEnd('/') + "/", _kind); } + return this; } @@ -245,7 +263,10 @@ namespace NzbDrone.Common.Disk public bool Equals(OsPath other) { - if (ReferenceEquals(other, null)) return false; + if (ReferenceEquals(other, null)) + { + return false; + } if (_path == other._path) { @@ -259,19 +280,26 @@ namespace NzbDrone.Common.Disk { return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); } + return string.Equals(left, right, StringComparison.InvariantCulture); } public static bool operator ==(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return ReferenceEquals(right, null); + } return left.Equals(right); } public static bool operator !=(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return !ReferenceEquals(right, null); + } return !left.Equals(right); } @@ -297,10 +325,12 @@ namespace NzbDrone.Common.Disk { return new OsPath(string.Join("\\", left._path.TrimEnd('\\'), right._path.TrimStart('\\')), OsPathKind.Windows); } + if (left.Kind == OsPathKind.Unix || right.Kind == OsPathKind.Unix) { return new OsPath(string.Join("/", left._path.TrimEnd('/'), right._path), OsPathKind.Unix); } + return new OsPath(string.Join("/", left._path, right._path), OsPathKind.Unknown); } @@ -356,6 +386,7 @@ namespace NzbDrone.Common.Disk { return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown); } + return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown); } } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs index 9cfb14cee..a393d556c 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs @@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsTrue(this Param param) { if (!param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue); + } return param; } @@ -18,7 +20,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsFalse(this Param param) { if (param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs index 2e2fecdf6..cf0392487 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs @@ -10,10 +10,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureCollectionExtensions { [DebuggerStepThrough] - public static Param HasItems(this Param param) where T : class, ICollection + public static Param HasItems(this Param param) + where T : class, ICollection { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -22,7 +25,9 @@ namespace NzbDrone.Common.EnsureThat public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -31,7 +36,9 @@ namespace NzbDrone.Common.EnsureThat public static Param> HasItems(this Param> param) { if (param.Value == null || !param.Value.Any()) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -40,7 +47,9 @@ namespace NzbDrone.Common.EnsureThat public static Param HasItems(this Param param) { if (param.Value == null || param.Value.Length < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -49,17 +58,20 @@ namespace NzbDrone.Common.EnsureThat public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } - [DebuggerStepThrough] public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs index 5c78b2371..97d9f58ee 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs @@ -7,14 +7,15 @@ namespace NzbDrone.Common.EnsureThat { public static class EnsureDateTimeExtensions { - private static readonly DateTime _minTime = new DateTime(1960, 1, 1); [DebuggerStepThrough] public static Param IsLt(this Param param, DateTime limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -23,7 +24,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLte(this Param param, DateTime limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -32,7 +35,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGt(this Param param, DateTime limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -41,7 +46,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGte(this Param param, DateTime limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -50,10 +57,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, DateTime min, DateTime max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } @@ -62,11 +73,13 @@ namespace NzbDrone.Common.EnsureThat public static Param IsUtc(this Param param) { if (param.Value.Kind != DateTimeKind.Utc) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "Excepted time to be in UTC but was [{0}]".Inject(param.Value.Kind)); + } + return param; } - [DebuggerStepThrough] public static Param IsValid(this Param param) { diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs index a36ba6697..e1bf3ba6d 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLt(this Param param, decimal limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLte(this Param param, decimal limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGt(this Param param, decimal limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGte(this Param param, decimal limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, decimal min, decimal max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs index ea614f667..d67abe512 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLt(this Param param, double limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLte(this Param param, double limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGt(this Param param, double limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGte(this Param param, double limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, double min, double max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs index 7f2b75442..a9d6190b3 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsNotEmpty(this Param param) { if (Guid.Empty.Equals(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs index 5979ec040..77ecaf669 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLessThan(this Param param, int limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLessThanOrEqualTo(this Param param, int limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGreaterThan(this Param param, int limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGreaterThanZero(this Param param) { if (param.Value <= 0) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0)); + } return param; } @@ -46,7 +54,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGreaterOrEqualTo(this Param param, int limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -55,10 +65,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, int min, int max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs index ef0b401c3..568fefb5a 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLt(this Param param, long limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLte(this Param param, long limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGt(this Param param, long limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGte(this Param param, long limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, long min, long max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs index 67e4863b5..3603da257 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs @@ -6,10 +6,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureNullableValueTypeExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : struct + public static Param IsNotNull(this Param param) + where T : struct { if (param.Value == null || !param.Value.HasValue) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs index a676d142a..7833d02e5 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs @@ -6,10 +6,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureObjectExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : class + public static Param IsNotNull(this Param param) + where T : class { if (param.Value == null) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs index 629527545..54f082b8f 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLt(this Param param, short limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLte(this Param param, short limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGt(this Param param, short limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsGte(this Param param, short limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsInRange(this Param param, short min, short max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs index 99f348667..1c10c9f28 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs @@ -13,7 +13,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsNotNullOrWhiteSpace(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } return param; } @@ -22,7 +24,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsNotNullOrEmpty(this Param param) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } return param; } @@ -31,15 +35,21 @@ namespace NzbDrone.Common.EnsureThat public static Param HasLengthBetween(this Param param, int minLength, int maxLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToShort.Inject(minLength, maxLength, length)); + } if (length > maxLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLong.Inject(minLength, maxLength, length)); + } return param; } @@ -48,12 +58,16 @@ namespace NzbDrone.Common.EnsureThat public static Param IsLongerThan(this Param param, int minLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "The string is not long enough. Must be at least '{0}' but was '{1}' characters long.".Inject(minLength, length)); + } return param; } @@ -71,6 +85,7 @@ namespace NzbDrone.Common.EnsureThat { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match)); } + return param; } @@ -78,7 +93,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsRelativePath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } if (!param.Value.EndsWith("\\")) { @@ -97,9 +114,14 @@ namespace NzbDrone.Common.EnsureThat public static Param IsValidPath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } - if (param.Value.IsPathValid()) return param; + if (param.Value.IsPathValid()) + { + return param; + } if (OsInfo.IsWindows) { diff --git a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs index e84c243d9..00c1b4dc2 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Common.EnsureThat { private static class Types { - internal static readonly Type IntType = typeof (int); + internal static readonly Type IntType = typeof(int); internal static readonly Type ShortType = typeof(short); @@ -78,8 +78,10 @@ namespace NzbDrone.Common.EnsureThat public static TypeParam IsOfType(this TypeParam param, Type type) { if (!param.Type.Equals(type)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotOfType.Inject(param.Type.FullName)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs index 838397f18..11e3598c5 100644 --- a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat var parent = e.Expression as MemberExpression; if (parent != null) + { path = parent.ToPath() + "."; + } return path + e.Member.Name; } @@ -23,17 +25,23 @@ namespace NzbDrone.Common.EnsureThat private static MemberExpression GetRightMostMember(Expression e) { if (e is LambdaExpression) + { return GetRightMostMember(((LambdaExpression)e).Body); + } if (e is MemberExpression) + { return (MemberExpression)e; + } if (e is MethodCallExpression) { var callExpression = (MethodCallExpression)e; if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression) + { return GetRightMostMember(callExpression.Object); + } var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; return GetRightMostMember(member); diff --git a/src/NzbDrone.Common/EnsureThat/Param.cs b/src/NzbDrone.Common/EnsureThat/Param.cs index 2149f74c2..1eea2851d 100644 --- a/src/NzbDrone.Common/EnsureThat/Param.cs +++ b/src/NzbDrone.Common/EnsureThat/Param.cs @@ -16,7 +16,8 @@ namespace NzbDrone.Common.EnsureThat { public readonly T Value; - internal Param(string name, T value) : base(name) + internal Param(string name, T value) + : base(name) { Value = value; } diff --git a/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs b/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs index a16516478..ed59c9fbe 100644 --- a/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs +++ b/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs @@ -8,7 +8,8 @@ // //------------------------------------------------------------------------------ -namespace NzbDrone.Common.EnsureThat.Resources { +namespace NzbDrone.Common.EnsureThat.Resources +{ /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -19,23 +20,28 @@ namespace NzbDrone.Common.EnsureThat.Resources { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ExceptionMessages { + internal class ExceptionMessages + { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ExceptionMessages() { + internal ExceptionMessages() + { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NzbDrone.Common.EnsureThat.Resources.ExceptionMessages", typeof(ExceptionMessages).Assembly); resourceMan = temp; } @@ -48,11 +54,14 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { + internal static global::System.Globalization.CultureInfo Culture + { + get + { return resourceCulture; } - set { + set + { resourceCulture = value; } } @@ -60,8 +69,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to Empty collection is not allowed.. /// - internal static string EnsureExtensions_IsEmptyCollection { - get { + internal static string EnsureExtensions_IsEmptyCollection + { + get + { return ResourceManager.GetString("EnsureExtensions_IsEmptyCollection", resourceCulture); } } @@ -69,8 +80,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to Empty Guid is not allowed.. /// - internal static string EnsureExtensions_IsEmptyGuid { - get { + internal static string EnsureExtensions_IsEmptyGuid + { + get + { return ResourceManager.GetString("EnsureExtensions_IsEmptyGuid", resourceCulture); } } @@ -78,8 +91,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to Expected an expression that evaluates to false.. /// - internal static string EnsureExtensions_IsNotFalse { - get { + internal static string EnsureExtensions_IsNotFalse + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotFalse", resourceCulture); } } @@ -87,8 +102,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is not greater than limit '{1}'.. /// - internal static string EnsureExtensions_IsNotGt { - get { + internal static string EnsureExtensions_IsNotGt + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotGt", resourceCulture); } } @@ -96,8 +113,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is not greater than or equal to limit '{1}'.. /// - internal static string EnsureExtensions_IsNotGte { - get { + internal static string EnsureExtensions_IsNotGte + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotGte", resourceCulture); } } @@ -105,8 +124,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is > max '{1}'.. /// - internal static string EnsureExtensions_IsNotInRange_ToHigh { - get { + internal static string EnsureExtensions_IsNotInRange_ToHigh + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToHigh", resourceCulture); } } @@ -114,8 +135,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to The string is too long. Must be between '{0}' and '{1}'. Must be between '{0}' and '{1}' but was '{2}' characters long.. /// - internal static string EnsureExtensions_IsNotInRange_ToLong { - get { + internal static string EnsureExtensions_IsNotInRange_ToLong + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToLong", resourceCulture); } } @@ -123,8 +146,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is < min '{1}'.. /// - internal static string EnsureExtensions_IsNotInRange_ToLow { - get { + internal static string EnsureExtensions_IsNotInRange_ToLow + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToLow", resourceCulture); } } @@ -132,8 +157,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to The string is not long enough. Must be between '{0}' and '{1}' but was '{2}' characters long.. /// - internal static string EnsureExtensions_IsNotInRange_ToShort { - get { + internal static string EnsureExtensions_IsNotInRange_ToShort + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToShort", resourceCulture); } } @@ -141,8 +168,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is not lower than limit '{1}'.. /// - internal static string EnsureExtensions_IsNotLt { - get { + internal static string EnsureExtensions_IsNotLt + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotLt", resourceCulture); } } @@ -150,8 +179,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' is not lower than or equal to limit '{1}'.. /// - internal static string EnsureExtensions_IsNotLte { - get { + internal static string EnsureExtensions_IsNotLte + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotLte", resourceCulture); } } @@ -159,8 +190,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to Value can not be null.. /// - internal static string EnsureExtensions_IsNotNull { - get { + internal static string EnsureExtensions_IsNotNull + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNull", resourceCulture); } } @@ -168,8 +201,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to The string can't be null or empty.. /// - internal static string EnsureExtensions_IsNotNullOrEmpty { - get { + internal static string EnsureExtensions_IsNotNullOrEmpty + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNullOrEmpty", resourceCulture); } } @@ -177,8 +212,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to The string can't be left empty, null or consist of only whitespaces.. /// - internal static string EnsureExtensions_IsNotNullOrWhiteSpace { - get { + internal static string EnsureExtensions_IsNotNullOrWhiteSpace + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNullOrWhiteSpace", resourceCulture); } } @@ -186,8 +223,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to The param is not of expected type: '{0}'.. /// - internal static string EnsureExtensions_IsNotOfType { - get { + internal static string EnsureExtensions_IsNotOfType + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotOfType", resourceCulture); } } @@ -195,8 +234,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to Expected an expression that evaluates to true.. /// - internal static string EnsureExtensions_IsNotTrue { - get { + internal static string EnsureExtensions_IsNotTrue + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotTrue", resourceCulture); } } @@ -204,8 +245,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to value '{0}' does not match '{1}'. /// - internal static string EnsureExtensions_NoMatch { - get { + internal static string EnsureExtensions_NoMatch + { + get + { return ResourceManager.GetString("EnsureExtensions_NoMatch", resourceCulture); } } @@ -213,8 +256,10 @@ namespace NzbDrone.Common.EnsureThat.Resources { /// /// Looks up a localized string similar to No MemberExpression found in expression: '{0}'.. /// - internal static string ExpressionUtils_GetRightMostMember_NoMemberFound { - get { + internal static string ExpressionUtils_GetRightMostMember_NoMemberFound + { + get + { return ResourceManager.GetString("ExpressionUtils_GetRightMostMember_NoMemberFound", resourceCulture); } } diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs index 591d029ce..3b66c02f8 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs @@ -48,7 +48,6 @@ namespace NzbDrone.Common.EnvironmentInfo throw new RadarrStartupException("Cannot create AppFolder, Access to the path {0} is denied", _appFolderInfo.AppDataFolder); } - if (OsInfo.IsWindows) { SetPermissions(); @@ -82,8 +81,15 @@ namespace NzbDrone.Common.EnvironmentInfo if (_startupContext.Args.ContainsKey(StartupContext.APPDATA)) { - if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) return; - if (!_diskProvider.FileExists(oldDbFile)) return; + if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) + { + return; + } + + if (!_diskProvider.FileExists(oldDbFile)) + { + return; + } _diskProvider.MoveFile(oldDbFile, _appFolderInfo.GetDatabase()); CleanupSqLiteRollbackFiles(); @@ -91,7 +97,10 @@ namespace NzbDrone.Common.EnvironmentInfo } // Exit if a radarr.db already exists - if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) return; + if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) + { + return; + } // Rename the DB file if (_diskProvider.FileExists(oldDbFile)) @@ -112,10 +121,12 @@ namespace NzbDrone.Common.EnvironmentInfo } } - private void InitializeMonoApplicationData() { - if (OsInfo.IsWindows) return; + if (OsInfo.IsWindows) + { + return; + } try { @@ -125,7 +136,7 @@ namespace NzbDrone.Common.EnvironmentInfo var configHome = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify); if (configHome.IsNullOrWhiteSpace() || configHome == "/.config" || - configHome.EndsWith("/.config") && !_diskProvider.FolderExists(configHome.GetParentPath()) || + (configHome.EndsWith("/.config") && !_diskProvider.FolderExists(configHome.GetParentPath())) || !_diskProvider.FolderExists(configHome)) { // Tell mono/netcore to use appData/.config as ApplicationData folder. @@ -135,7 +146,7 @@ namespace NzbDrone.Common.EnvironmentInfo var dataHome = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify); if (dataHome.IsNullOrWhiteSpace() || dataHome == "/.local/share" || - dataHome.EndsWith("/.local/share") && !_diskProvider.FolderExists(dataHome.GetParentPath().GetParentPath()) || + (dataHome.EndsWith("/.local/share") && !_diskProvider.FolderExists(dataHome.GetParentPath().GetParentPath())) || !_diskProvider.FolderExists(dataHome)) { // Tell mono/netcore to use appData/.config/share as LocalApplicationData folder. diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs index f03aaf59d..dbbd9e509 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Common.EnvironmentInfo public class AppFolderInfo : IAppFolderInfo { - private readonly Environment.SpecialFolder DATA_SPECIAL_FOLDER = Environment.SpecialFolder.CommonApplicationData; + private readonly Environment.SpecialFolder _dataSpecialFolder = Environment.SpecialFolder.CommonApplicationData; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(AppFolderInfo)); @@ -23,7 +23,7 @@ namespace NzbDrone.Common.EnvironmentInfo { if (OsInfo.IsNotWindows) { - DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData; + _dataSpecialFolder = Environment.SpecialFolder.ApplicationData; } if (startupContext.Args.ContainsKey(StartupContext.APPDATA)) @@ -33,7 +33,7 @@ namespace NzbDrone.Common.EnvironmentInfo } else { - AppDataFolder = Path.Combine(Environment.GetFolderPath(DATA_SPECIAL_FOLDER, Environment.SpecialFolderOption.DoNotVerify), "Radarr"); + AppDataFolder = Path.Combine(Environment.GetFolderPath(_dataSpecialFolder, Environment.SpecialFolderOption.DoNotVerify), "Radarr"); } StartUpFolder = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; diff --git a/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs index c9ba57bb0..1e87ba077 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs @@ -29,7 +29,7 @@ namespace NzbDrone.Common.EnvironmentInfo public static string AppName { get; } = "Radarr"; public static Version Version { get; } - public static String Branch { get; } + public static string Branch { get; } public static string Release { get; } public static DateTime BuildDateTime diff --git a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs index 25a3cbf1f..b844a29c2 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs @@ -1,6 +1,5 @@ namespace NzbDrone.Common.EnvironmentInfo { - public interface IOsVersionAdapter { bool Enabled { get; } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs index f109d304c..fddfdf00b 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs @@ -33,14 +33,14 @@ namespace NzbDrone.Common.EnvironmentInfo Os = Os.Windows; break; } + case PlatformID.MacOSX: case PlatformID.Unix: { // Sometimes Mac OS reports itself as Unix if (Directory.Exists("/System/Library/CoreServices/") && (File.Exists("/System/Library/CoreServices/SystemVersion.plist") || - File.Exists("/System/Library/CoreServices/ServerVersion.plist")) - ) + File.Exists("/System/Library/CoreServices/ServerVersion.plist"))) { Os = Os.Osx; } @@ -48,6 +48,7 @@ namespace NzbDrone.Common.EnvironmentInfo { Os = Os.Linux; } + break; } } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs index c20865813..f5e8074fc 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs @@ -2,8 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo { public class OsVersionModel { - - public OsVersionModel(string name, string version, string fullName = null) { Name = Trim(name); diff --git a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs index f13d6bbc3..0a0ac17c9 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs @@ -5,7 +5,6 @@ using Microsoft.Win32; namespace NzbDrone.Common.EnvironmentInfo { - public enum PlatformType { DotNet = 0, @@ -122,38 +121,47 @@ namespace NzbDrone.Common.EnvironmentInfo { return new Version(4, 8, 0); } + if (releaseKey >= 461808) { return new Version(4, 7, 2); } + if (releaseKey >= 461308) { return new Version(4, 7, 1); } + if (releaseKey >= 460798) { return new Version(4, 7); } + if (releaseKey >= 394802) { return new Version(4, 6, 2); } + if (releaseKey >= 394254) { return new Version(4, 6, 1); } + if (releaseKey >= 393295) { return new Version(4, 6); } + if (releaseKey >= 379893) { return new Version(4, 5, 2); } + if (releaseKey >= 378675) { return new Version(4, 5, 1); } + if (releaseKey >= 378389) { return new Version(4, 5); diff --git a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs index 91b62da30..51141ddec 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs @@ -131,46 +131,83 @@ namespace NzbDrone.Common.EnvironmentInfo public static bool IsProduction { get; } public static bool IsDevelopment { get; } - private static bool InternalIsTesting() { try { var lowerProcessName = Process.GetCurrentProcess().ProcessName.ToLower(); - if (lowerProcessName.Contains("vshost")) return true; - if (lowerProcessName.Contains("nunit")) return true; - if (lowerProcessName.Contains("jetbrain")) return true; - if (lowerProcessName.Contains("resharper")) return true; + if (lowerProcessName.Contains("vshost")) + { + return true; + } + + if (lowerProcessName.Contains("nunit")) + { + return true; + } + + if (lowerProcessName.Contains("jetbrain")) + { + return true; + } + + if (lowerProcessName.Contains("resharper")) + { + return true; + } } catch { - } try { var currentAssemblyLocation = typeof(RuntimeInfo).Assembly.Location; - if (currentAssemblyLocation.ToLower().Contains("_output")) return true; - if (currentAssemblyLocation.ToLower().Contains("_tests")) return true; + if (currentAssemblyLocation.ToLower().Contains("_output")) + { + return true; + } + + if (currentAssemblyLocation.ToLower().Contains("_tests")) + { + return true; + } } catch { - } var lowerCurrentDir = Directory.GetCurrentDirectory().ToLower(); - if (lowerCurrentDir.Contains("vsts")) return true; - if (lowerCurrentDir.Contains("buildagent")) return true; - if (lowerCurrentDir.Contains("_output")) return true; - if (lowerCurrentDir.Contains("_tests")) return true; + if (lowerCurrentDir.Contains("vsts")) + { + return true; + } + + if (lowerCurrentDir.Contains("buildagent")) + { + return true; + } + + if (lowerCurrentDir.Contains("_output")) + { + return true; + } + + if (lowerCurrentDir.Contains("_tests")) + { + return true; + } return false; } private static bool InternalIsDebug() { - if (BuildInfo.IsDebug || Debugger.IsAttached) return true; + if (BuildInfo.IsDebug || Debugger.IsAttached) + { + return true; + } return false; } @@ -178,7 +215,10 @@ namespace NzbDrone.Common.EnvironmentInfo private static bool InternalIsOfficialBuild() { //Official builds will never have such a high revision - if (BuildInfo.Version.Major >= 10 || BuildInfo.Version.Revision > 10000) return false; + if (BuildInfo.Version.Major >= 10 || BuildInfo.Version.Revision > 10000) + { + return false; + } return true; } diff --git a/src/NzbDrone.Common/Exceptions/NotParentException.cs b/src/NzbDrone.Common/Exceptions/NotParentException.cs index d9b78247e..59c4d1ea4 100644 --- a/src/NzbDrone.Common/Exceptions/NotParentException.cs +++ b/src/NzbDrone.Common/Exceptions/NotParentException.cs @@ -2,11 +2,13 @@ { public class NotParentException : NzbDroneException { - public NotParentException(string message, params object[] args) : base(message, args) + public NotParentException(string message, params object[] args) + : base(message, args) { } - public NotParentException(string message) : base(message) + public NotParentException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs index 7e0be7312..015ffc0b5 100644 --- a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs +++ b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs @@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions protected NzbDroneException(string message, params object[] args) : base(string.Format(message, args)) { - } protected NzbDroneException(string message) : base(message) { - } protected NzbDroneException(string message, Exception innerException, params object[] args) : base(string.Format(message, args), innerException) { - } protected NzbDroneException(string message, Exception innerException) diff --git a/src/NzbDrone.Common/Expansive/Expansive.cs b/src/NzbDrone.Common/Expansive/Expansive.cs index 8aad9545e..f6a2ff3c5 100644 --- a/src/NzbDrone.Common/Expansive/Expansive.cs +++ b/src/NzbDrone.Common/Expansive/Expansive.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Common.Expansive { private static PatternStyle _patternStyle; - public static bool RequireAllExpansions { get; set; } public static Func DefaultExpansionFactory { get; set; } @@ -26,7 +25,6 @@ namespace NzbDrone.Common.Expansive return source.Expand(DefaultExpansionFactory); } - public static string Expand(this string source, params string[] args) { var output = source; @@ -50,9 +48,11 @@ namespace NzbDrone.Common.Expansive { tokenIndex = tokens.IndexOf(token); } + output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}"); } } + var newArgs = new List(); foreach (var arg in args) { @@ -63,15 +63,20 @@ namespace NzbDrone.Common.Expansive foreach (Match match in tokenPattern.Matches(newArg)) { var token = _patternStyle.TokenReplaceFilter(match.Value); - if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) + { + throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + } + calls.Push(string.Format("{0}:{1}", callingToken, token)); callingToken = token; newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]); } - } + newArgs.Add(newArg); } + return string.Format(output, newArgs.ToArray()); } @@ -80,9 +85,6 @@ namespace NzbDrone.Common.Expansive return source.ExpandInternal(expansionFactory); } - - - public static string Expand(this string source, object model) { return source.ExpandInternal( @@ -106,17 +108,20 @@ namespace NzbDrone.Common.Expansive private static void Initialize() { _patternStyle = new PatternStyle - { - TokenMatchPattern = @"\{[a-zA-Z]\w*\}", - TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""), - OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"), - TokenFilter = tokens => "{(" + tokens + ")}" - }; + { + TokenMatchPattern = @"\{[a-zA-Z]\w*\}", + TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""), + OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"), + TokenFilter = tokens => "{(" + tokens + ")}" + }; } private static string ExpandInternal(this string source, Func expansionFactory) { - if (expansionFactory == null) throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + if (expansionFactory == null) + { + throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + } var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase); @@ -139,9 +144,12 @@ namespace NzbDrone.Common.Expansive // if we have already encountered this token in this call tree, we have a circular reference if (thisNode.CallTree.Contains(token)) + { throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}", token, - string.Join("->", thisNode.CallTree.ToArray().Reverse()), token)); + string.Join("->", thisNode.CallTree.ToArray().Reverse()), + token)); + } // expand this match var expandedValue = expansionFactory(token); @@ -156,6 +164,7 @@ namespace NzbDrone.Common.Expansive output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child); } } + return output; } @@ -171,7 +180,11 @@ namespace NzbDrone.Common.Expansive { var result = new ExpandoObject(); var d = result as IDictionary; //work with the Expando as a Dictionary - if (o is ExpandoObject) return o; //shouldn't have to... but just in case + if (o is ExpandoObject) + { + return o; //shouldn't have to... but just in case + } + if (o is NameValueCollection || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; @@ -185,8 +198,10 @@ namespace NzbDrone.Common.Expansive d.Add(item.Name, item.GetValue(o, null)); } } + return result; } + /// /// Turns the object into a Dictionary /// diff --git a/src/NzbDrone.Common/Expansive/TreeNode.cs b/src/NzbDrone.Common/Expansive/TreeNode.cs index 206836db5..4a61fa08e 100644 --- a/src/NzbDrone.Common/Expansive/TreeNode.cs +++ b/src/NzbDrone.Common/Expansive/TreeNode.cs @@ -7,25 +7,29 @@ namespace NzbDrone.Common.Expansive private List _CallTree; private TreeNode _Parent; - public TreeNode(T Value) + public TreeNode(T value) { - this.Value = Value; + Value = value; Parent = null; Children = new TreeNodeList(this); _CallTree = new List(); } - public TreeNode(T Value, TreeNode Parent) + public TreeNode(T value, TreeNode parent) { - this.Value = Value; - this.Parent = Parent; + Value = value; + Parent = parent; Children = new TreeNodeList(this); _CallTree = new List(); } public TreeNode Parent { - get { return _Parent; } + get + { + return _Parent; + } + set { if (value == _Parent) @@ -52,12 +56,12 @@ namespace NzbDrone.Common.Expansive get { //return (Parent == null) ? this : Parent.Root; - TreeNode node = this; while (node.Parent != null) { node = node.Parent; } + return node; } } @@ -75,9 +79,10 @@ namespace NzbDrone.Common.Expansive node = node.Parent; _CallTree.Add(node.Value); } + return _CallTree; } - private set { _CallTree = value; } + private set => _CallTree = value; } public T Value { get; set; } diff --git a/src/NzbDrone.Common/Expansive/TreeNodeList.cs b/src/NzbDrone.Common/Expansive/TreeNodeList.cs index 74bfd189f..a239a3b15 100644 --- a/src/NzbDrone.Common/Expansive/TreeNodeList.cs +++ b/src/NzbDrone.Common/Expansive/TreeNodeList.cs @@ -6,24 +6,23 @@ namespace NzbDrone.Common.Expansive { public TreeNode Parent; - public TreeNodeList(TreeNode Parent) + public TreeNodeList(TreeNode parent) { - this.Parent = Parent; + Parent = parent; } - public new TreeNode Add(TreeNode Node) + public new TreeNode Add(TreeNode node) { - base.Add(Node); - Node.Parent = Parent; - return Node; + base.Add(node); + node.Parent = Parent; + return node; } - public TreeNode Add(T Value) + public TreeNode Add(T value) { - return Add(new TreeNode(Value)); + return Add(new TreeNode(value)); } - public override string ToString() { return "Count=" + Count.ToString(); diff --git a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs index 59933243d..aa29245e3 100644 --- a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs +++ b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs @@ -16,8 +16,15 @@ namespace NzbDrone.Common.Extensions public static Dictionary Merge(this Dictionary first, Dictionary second) { - if (first == null) throw new ArgumentNullException("first"); - if (second == null) throw new ArgumentNullException("second"); + if (first == null) + { + throw new ArgumentNullException("first"); + } + + if (second == null) + { + throw new ArgumentNullException("second"); + } var merged = new Dictionary(); first.ToList().ForEach(kv => merged[kv.Key] = kv.Value); diff --git a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs index 8bcaea4e8..eb1bd3e21 100644 --- a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs @@ -4,30 +4,37 @@ namespace NzbDrone.Common.Extensions { public static class ExceptionExtensions { - public static T WithData(this T ex, string key, string value) where T : Exception + public static T WithData(this T ex, string key, string value) + where T : Exception { ex.AddData(key, value); return ex; } - public static T WithData(this T ex, string key, int value) where T : Exception + + public static T WithData(this T ex, string key, int value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - public static T WithData(this T ex, string key, Http.HttpUri value) where T : Exception + public static T WithData(this T ex, string key, Http.HttpUri value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - - public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) where T : Exception + public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) + where T : Exception { - if (response == null || response.Content == null) return ex; + if (response == null || response.Content == null) + { + return ex; + } var contentSample = response.Content.Substring(0, Math.Min(response.Content.Length, maxSampleLength)); @@ -47,16 +54,19 @@ namespace NzbDrone.Common.Extensions { ex.AddData("ContentType", response.Headers.ContentType ?? string.Empty); } + ex.AddData("ContentLength", response.Content.Length.ToString()); ex.AddData("ContentSample", contentSample); return ex; } - private static void AddData(this Exception ex, string key, string value) { - if (value.IsNullOrWhiteSpace()) return; + if (value.IsNullOrWhiteSpace()) + { + return; + } ex.Data[key] = value; } diff --git a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs index b06b6d736..627bfd583 100644 --- a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs +++ b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs @@ -13,8 +13,10 @@ namespace NzbDrone.Common.Extensions return source.Where(element => knownKeys.Add(keySelector(element))); } - public static IEnumerable IntersectBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, + public static IEnumerable IntersectBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); @@ -31,9 +33,11 @@ namespace NzbDrone.Common.Extensions } } - public static IEnumerable ExceptBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, - IEqualityComparer keyComparer) + public static IEnumerable ExceptBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, + IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); var matchedKeys = new HashSet(); @@ -62,6 +66,7 @@ namespace NzbDrone.Common.Extensions result[key] = item; } } + return result; } @@ -76,6 +81,7 @@ namespace NzbDrone.Common.Extensions result[key] = valueSelector(item); } } + return result; } @@ -112,11 +118,15 @@ namespace NzbDrone.Common.Extensions public static IEnumerable DropLast(this IEnumerable source, int n) { if (source == null) + { throw new ArgumentNullException("source"); + } if (n < 0) + { throw new ArgumentOutOfRangeException("n", "Argument n should be non-negative."); + } return InternalDropLast(source, n); } @@ -130,9 +140,12 @@ namespace NzbDrone.Common.Extensions buffer.Enqueue(x); if (buffer.Count == n + 1) + { yield return buffer.Dequeue(); + } } } + public static bool In(this T source, List list) { return list.Contains(source); diff --git a/src/NzbDrone.Common/Extensions/Int64Extensions.cs b/src/NzbDrone.Common/Extensions/Int64Extensions.cs index 911e3b296..bfca7f66c 100644 --- a/src/NzbDrone.Common/Extensions/Int64Extensions.cs +++ b/src/NzbDrone.Common/Extensions/Int64Extensions.cs @@ -11,8 +11,15 @@ namespace NzbDrone.Common.Extensions { const int bytesInKb = 1024; - if (bytes < 0) return "-" + SizeSuffix(-bytes); - if (bytes == 0) return "0 B"; + if (bytes < 0) + { + return "-" + SizeSuffix(-bytes); + } + + if (bytes == 0) + { + return "0 B"; + } var mag = (int)Math.Log(bytes, bytesInKb); var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag); diff --git a/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs b/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs index 9c3ba1653..825525457 100644 --- a/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs +++ b/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs @@ -6,9 +6,20 @@ namespace NzbDrone.Common.Extensions { public static int LevenshteinDistance(this string text, string other, int costInsert = 1, int costDelete = 1, int costSubstitute = 1) { - if (text == other) return 0; - if (text.Length == 0) return other.Length * costInsert; - if (other.Length == 0) return text.Length * costDelete; + if (text == other) + { + return 0; + } + + if (text.Length == 0) + { + return other.Length * costInsert; + } + + if (other.Length == 0) + { + return text.Length * costDelete; + } int[] matrix = new int[other.Length + 1]; diff --git a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs index 3937cf733..5182465e5 100644 --- a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Common.Extensions { public static class ObjectExtensions { - public static T JsonClone(this T source) where T : new() + public static T JsonClone(this T source) + where T : new() { var json = source.ToJson(); return Json.Deserialize(json); diff --git a/src/NzbDrone.Common/Extensions/PathExtensions.cs b/src/NzbDrone.Common/Extensions/PathExtensions.cs index 9f8c7cf77..4820f5dc8 100644 --- a/src/NzbDrone.Common/Extensions/PathExtensions.cs +++ b/src/NzbDrone.Common/Extensions/PathExtensions.cs @@ -33,7 +33,8 @@ namespace NzbDrone.Common.Extensions var info = new FileInfo(path.Trim()); - if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) //UNC + //UNC + if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) { return info.FullName.TrimEnd('/', '\\', ' '); } @@ -53,7 +54,11 @@ namespace NzbDrone.Common.Extensions comparison = DiskProviderBase.PathStringComparison; } - if (firstPath.Equals(secondPath, comparison.Value)) return true; + if (firstPath.Equals(secondPath, comparison.Value)) + { + return true; + } + return string.Equals(firstPath.CleanFilePath(), secondPath.CleanFilePath(), comparison.Value); } @@ -96,6 +101,7 @@ namespace NzbDrone.Common.Extensions { parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar); } + if (childPath != "/" && !parentPath.EndsWith(":\\")) { childPath = childPath.TrimEnd(Path.DirectorySeparatorChar); diff --git a/src/NzbDrone.Common/Extensions/StreamExtensions.cs b/src/NzbDrone.Common/Extensions/StreamExtensions.cs index 6283f5fc0..8f6036baa 100644 --- a/src/NzbDrone.Common/Extensions/StreamExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StreamExtensions.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Common.Extensions { ms.Write(buffer, 0, read); } + return ms.ToArray(); } } diff --git a/src/NzbDrone.Common/Extensions/StringExtensions.cs b/src/NzbDrone.Common/Extensions/StringExtensions.cs index b7d058657..246dc0561 100644 --- a/src/NzbDrone.Common/Extensions/StringExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StringExtensions.cs @@ -18,7 +18,11 @@ namespace NzbDrone.Common.Extensions public static object NullSafe(this object target) { - if (target != null) return target; + if (target != null) + { + return target; + } + return "[NULL]"; } @@ -76,7 +80,9 @@ namespace NzbDrone.Common.Extensions public static string TrimEnd(this string text, string postfix) { if (text.EndsWith(postfix)) + { text = text.Substring(0, text.Length - postfix.Length); + } return text; } @@ -134,7 +140,7 @@ namespace NzbDrone.Common.Extensions public static byte[] HexToByteArray(this string input) { return Enumerable.Range(0, input.Length) - .Where(x => x%2 == 0) + .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(input.Substring(x, 2), 16)) .ToArray(); } @@ -151,9 +157,9 @@ namespace NzbDrone.Common.Extensions var first = int.Parse(octalValue.Substring(0, 1)); var second = int.Parse(octalValue.Substring(1, 1)); var third = int.Parse(octalValue.Substring(2, 1)); - var byteResult = (byte)((first << 6) | (second << 3) | (third)); + var byteResult = (byte)((first << 6) | (second << 3) | third); - return Encoding.ASCII.GetString(new [] { byteResult }); + return Encoding.ASCII.GetString(new[] { byteResult }); } public static string SplitCamelCase(this string input) diff --git a/src/NzbDrone.Common/Extensions/UrlExtensions.cs b/src/NzbDrone.Common/Extensions/UrlExtensions.cs index 50e0b9856..e44843838 100644 --- a/src/NzbDrone.Common/Extensions/UrlExtensions.cs +++ b/src/NzbDrone.Common/Extensions/UrlExtensions.cs @@ -28,7 +28,6 @@ namespace NzbDrone.Common.Extensions } return true; - } } } diff --git a/src/NzbDrone.Common/HashUtil.cs b/src/NzbDrone.Common/HashUtil.cs index d43c7280c..a60349271 100644 --- a/src/NzbDrone.Common/HashUtil.cs +++ b/src/NzbDrone.Common/HashUtil.cs @@ -11,7 +11,7 @@ namespace NzbDrone.Common byte[] bytes = Encoding.UTF8.GetBytes(input); foreach (byte myByte in bytes) { - mCrc ^= ((uint)(myByte) << 24); + mCrc ^= (uint)myByte << 24; for (var i = 0; i < 8; i++) { if ((Convert.ToUInt32(mCrc) & 0x80000000) == 0x80000000) @@ -24,6 +24,7 @@ namespace NzbDrone.Common } } } + return $"{mCrc:x8}"; } diff --git a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs index 4548d3df0..96762f120 100644 --- a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs +++ b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs @@ -218,6 +218,7 @@ namespace NzbDrone.Common.Http.Dispatchers { var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance); var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream; + // Note that responseStream will likely be null once mono fixes it. responseStream?.Dispose(); } diff --git a/src/NzbDrone.Common/Http/HttpClient.cs b/src/NzbDrone.Common/Http/HttpClient.cs index 84cf6751d..8df5d23b9 100644 --- a/src/NzbDrone.Common/Http/HttpClient.cs +++ b/src/NzbDrone.Common/Http/HttpClient.cs @@ -18,10 +18,12 @@ namespace NzbDrone.Common.Http HttpResponse Execute(HttpRequest request); void DownloadFile(string url, string fileName); HttpResponse Get(HttpRequest request); - HttpResponse Get(HttpRequest request) where T : new(); + HttpResponse Get(HttpRequest request) + where T : new(); HttpResponse Head(HttpRequest request); HttpResponse Post(HttpRequest request); - HttpResponse Post(HttpRequest request) where T : new(); + HttpResponse Post(HttpRequest request) + where T : new(); } public class HttpClient : IHttpClient @@ -266,7 +268,8 @@ namespace NzbDrone.Common.Http return Execute(request); } - public HttpResponse Get(HttpRequest request) where T : new() + public HttpResponse Get(HttpRequest request) + where T : new() { var response = Get(request); CheckResponseContentType(response); @@ -285,7 +288,8 @@ namespace NzbDrone.Common.Http return Execute(request); } - public HttpResponse Post(HttpRequest request) where T : new() + public HttpResponse Post(HttpRequest request) + where T : new() { var response = Post(request); CheckResponseContentType(response); diff --git a/src/NzbDrone.Common/Http/HttpException.cs b/src/NzbDrone.Common/Http/HttpException.cs index 005fab57a..d78dd5b3e 100644 --- a/src/NzbDrone.Common/Http/HttpException.cs +++ b/src/NzbDrone.Common/Http/HttpException.cs @@ -17,13 +17,11 @@ namespace NzbDrone.Common.Http public HttpException(HttpRequest request, HttpResponse response) : this(request, response, string.Format("HTTP request failed: [{0}:{1}] [{2}] at [{3}]", (int)response.StatusCode, response.StatusCode, request.Method, request.Url)) { - } public HttpException(HttpResponse response) : this(response.Request, response) { - } public override string ToString() diff --git a/src/NzbDrone.Common/Http/HttpHeader.cs b/src/NzbDrone.Common/Http/HttpHeader.cs index 8cf25489a..2794f6dc4 100644 --- a/src/NzbDrone.Common/Http/HttpHeader.cs +++ b/src/NzbDrone.Common/Http/HttpHeader.cs @@ -1,11 +1,11 @@ using System; -using System.Linq; +using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Globalization; +using System.Linq; using System.Text; using NzbDrone.Common.Extensions; -using System.Collections; -using System.Globalization; namespace NzbDrone.Common.Http { @@ -14,12 +14,10 @@ namespace NzbDrone.Common.Http public HttpHeader(NameValueCollection headers) : base(headers) { - } public HttpHeader() { - } public bool ContainsKey(string key) @@ -35,6 +33,7 @@ namespace NzbDrone.Common.Http { return null; } + if (values.Length > 1) { throw new ApplicationException($"Expected {key} to occur only once, but was {values.Join("|")}."); @@ -43,7 +42,8 @@ namespace NzbDrone.Common.Http return values[0]; } - protected T? GetSingleValue(string key, Func converter) where T : struct + protected T? GetSingleValue(string key, Func converter) + where T : struct { var value = GetSingleValue(key); if (value == null) @@ -53,6 +53,7 @@ namespace NzbDrone.Common.Http return converter(value); } + protected void SetSingleValue(string key, string value) { if (value == null) @@ -65,7 +66,8 @@ namespace NzbDrone.Common.Http } } - protected void SetSingleValue(string key, T? value, Func converter = null) where T : struct + protected void SetSingleValue(string key, T? value, Func converter = null) + where T : struct { if (!value.HasValue) { diff --git a/src/NzbDrone.Common/Http/HttpRequest.cs b/src/NzbDrone.Common/Http/HttpRequest.cs index 0c11ba275..3674d61d5 100644 --- a/src/NzbDrone.Common/Http/HttpRequest.cs +++ b/src/NzbDrone.Common/Http/HttpRequest.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Common.Http IgnorePersistentCookies = false; Cookies = new Dictionary(); - if (!RuntimeInfo.IsProduction) { AllowAutoRedirect = false; diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs index d4ccc26d3..2e9bf1a5b 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs @@ -46,7 +46,6 @@ namespace NzbDrone.Common.Http public HttpRequestBuilder(bool useHttps, string host, int port, string urlBase = null) : this(BuildBaseUrl(useHttps, host, port, urlBase)) { - } public static string BuildBaseUrl(bool useHttps, string host, int port, string urlBase = null) @@ -148,7 +147,10 @@ namespace NzbDrone.Common.Http protected virtual void ApplyFormData(HttpRequest request) { - if (FormData.Empty()) return; + if (FormData.Empty()) + { + return; + } if (request.ContentData != null) { @@ -173,11 +175,22 @@ namespace NzbDrone.Common.Http writer.Write(partBoundary); writer.Write("Content-Disposition: form-data"); - if (formData.Name.IsNotNullOrWhiteSpace()) writer.Write("; name=\"{0}\"", formData.Name); - if (formData.FileName.IsNotNullOrWhiteSpace()) writer.Write("; filename=\"{0}\"", formData.FileName); + if (formData.Name.IsNotNullOrWhiteSpace()) + { + writer.Write("; name=\"{0}\"", formData.Name); + } + + if (formData.FileName.IsNotNullOrWhiteSpace()) + { + writer.Write("; filename=\"{0}\"", formData.FileName); + } + writer.Write("\r\n"); - if (formData.ContentType.IsNotNullOrWhiteSpace()) writer.Write("Content-Type: {0}\r\n", formData.ContentType); + if (formData.ContentType.IsNotNullOrWhiteSpace()) + { + writer.Write("Content-Type: {0}\r\n", formData.ContentType); + } writer.Write("\r\n"); writer.Flush(); @@ -201,7 +214,6 @@ namespace NzbDrone.Common.Http var body = bodyStream.ToArray(); // TODO: Scan through body to see if we have a boundary collision? - request.Headers.ContentType = "multipart/form-data; boundary=" + boundary; request.SetContent(body); @@ -379,5 +391,4 @@ namespace NzbDrone.Common.Http return this; } } - } diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs index 18ee914a7..b7a616143 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Common.Http protected HttpRequestBuilderFactory() { - } protected void SetRootBuilder(HttpRequestBuilder rootBuilder) diff --git a/src/NzbDrone.Common/Http/HttpResponse.cs b/src/NzbDrone.Common/Http/HttpResponse.cs index e0b11b51c..eab34c6a0 100644 --- a/src/NzbDrone.Common/Http/HttpResponse.cs +++ b/src/NzbDrone.Common/Http/HttpResponse.cs @@ -48,7 +48,6 @@ namespace NzbDrone.Common.Http } } - public bool HasHttpError => (int)StatusCode >= 400; public bool HasHttpRedirect => StatusCode == HttpStatusCode.Moved || @@ -90,8 +89,8 @@ namespace NzbDrone.Common.Http } } - - public class HttpResponse : HttpResponse where T : new() + public class HttpResponse : HttpResponse + where T : new() { public HttpResponse(HttpResponse response) : base(response.Request, response.Headers, response.ResponseData, response.StatusCode) diff --git a/src/NzbDrone.Common/Http/HttpUri.cs b/src/NzbDrone.Common/Http/HttpUri.cs index 756283eb5..9dfd384ad 100644 --- a/src/NzbDrone.Common/Http/HttpUri.cs +++ b/src/NzbDrone.Common/Http/HttpUri.cs @@ -47,6 +47,7 @@ namespace NzbDrone.Common.Http { builder.Append('/'); } + builder.Append(path.TrimStart('/')); } @@ -78,7 +79,7 @@ namespace NzbDrone.Common.Http var query = match.Groups["query"]; var fragment = match.Groups["fragment"]; - if (!match.Success || scheme.Success && !host.Success && path.Success) + if (!match.Success || (scheme.Success && !host.Success && path.Success)) { throw new ArgumentException("Uri didn't match expected pattern: " + _uri); } @@ -126,6 +127,7 @@ namespace NzbDrone.Common.Http _queryParams = dict.AsReadOnly(); } + return _queryParams; } } @@ -200,6 +202,7 @@ namespace NzbDrone.Common.Http { builder.Append("&"); } + builder.Append(Uri.EscapeDataString(pair.Key)); builder.Append("="); builder.Append(Uri.EscapeDataString(pair.Value)); @@ -208,7 +211,6 @@ namespace NzbDrone.Common.Http return SetQuery(builder.ToString()); } - public override int GetHashCode() { return _uri.GetHashCode(); @@ -237,7 +239,10 @@ namespace NzbDrone.Common.Http public bool Equals(HttpUri other) { - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return _uri.Equals(other._uri); } diff --git a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs index 3722fd9ce..ae987a23d 100644 --- a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs @@ -22,7 +22,7 @@ namespace NzbDrone.Common.Http } public JsonRpcRequestBuilder(string baseUrl, string method, IEnumerable parameters) - : base (baseUrl) + : base(baseUrl) { Method = HttpMethod.POST; JsonMethod = method; diff --git a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs index 3d22f245f..58a7541da 100644 --- a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs +++ b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs @@ -30,15 +30,17 @@ namespace NzbDrone.Common.Http.Proxy if (!string.IsNullOrWhiteSpace(BypassFilter)) { var hostlist = BypassFilter.Split(','); - for(int i = 0; i < hostlist.Length; i++) + for (int i = 0; i < hostlist.Length; i++) { - if(hostlist[i].StartsWith("*")) + if (hostlist[i].StartsWith("*")) { hostlist[i] = ";" + hostlist[i]; } } + return hostlist; } + return new string[] { }; } } diff --git a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs index 4e0a8458b..ca58fedee 100644 --- a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs +++ b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs @@ -31,6 +31,7 @@ namespace NzbDrone.Common.Http.Proxy return proxy; } + private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { switch (proxySettings.Type) @@ -44,6 +45,7 @@ namespace NzbDrone.Common.Http.Proxy { return new WebProxy(proxySettings.Host + ":" + proxySettings.Port, proxySettings.BypassLocalAddress, proxySettings.BypassListAsArray); } + case ProxyType.Socks4: return new SocksWebProxy(new ProxyConfig(IPAddress.Loopback, GetNextFreePort(), GetProxyIpAddress(proxySettings.Host), proxySettings.Port, ProxyConfig.SocksVersion.Four, proxySettings.Username, proxySettings.Password), false); case ProxyType.Socks5: diff --git a/src/NzbDrone.Common/Http/TlsFailureException.cs b/src/NzbDrone.Common/Http/TlsFailureException.cs index b62ff73c4..cb3743c03 100644 --- a/src/NzbDrone.Common/Http/TlsFailureException.cs +++ b/src/NzbDrone.Common/Http/TlsFailureException.cs @@ -7,8 +7,6 @@ namespace NzbDrone.Common.Http public TlsFailureException(WebRequest request, WebException innerException) : base("Failed to establish secure https connection to '" + request.RequestUri + "'.", innerException, WebExceptionStatus.SecureChannelFailure, innerException.Response) { - } - } } diff --git a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs index c62ff37ac..e92aa216e 100644 --- a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs +++ b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs @@ -5,7 +5,6 @@ public UnexpectedHtmlContentException(HttpResponse response) : base(response.Request, response, $"Site responded with browser content instead of api data. This disruption may be temporary, please try again later. [{response.Request.Url}]") { - } } } diff --git a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs index eb4f28c90..1e32d399f 100644 --- a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs +++ b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs @@ -15,6 +15,7 @@ namespace NzbDrone.Common.Instrumentation json[i] = new JValue(CleanseLogMessage.Cleanse(text)); } } + foreach (JToken token in json) { Visit(token); diff --git a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs index 3b99b7ad3..6f778d7de 100644 --- a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs +++ b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs @@ -26,7 +26,10 @@ namespace NzbDrone.Common.Instrumentation { var exception = e.ExceptionObject as Exception; - if (exception == null) return; + if (exception == null) + { + return; + } if (exception is NullReferenceException && exception.ToString().Contains("Microsoft.AspNet.SignalR.Transports.TransportHeartbeat.ProcessServerCommand")) @@ -37,7 +40,7 @@ namespace NzbDrone.Common.Instrumentation if (PlatformInfo.IsMono) { - if (exception is TypeInitializationException && exception.InnerException is DllNotFoundException || + if ((exception is TypeInitializationException && exception.InnerException is DllNotFoundException) || exception is DllNotFoundException) { Logger.Debug(exception, "Minor Fail: " + exception.Message); diff --git a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs index 65c44b87f..2c8e7c8a0 100644 --- a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs +++ b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs @@ -29,7 +29,6 @@ namespace NzbDrone.Common.Instrumentation message += ": " + logEvent.Exception.Message; } } - } return message; diff --git a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs index 3d02c3e76..6a83ce8c5 100644 --- a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs +++ b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs @@ -12,6 +12,8 @@ namespace NzbDrone.Common.Instrumentation { public static class NzbDroneLogger { + private const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; + private static bool _isConfigured; static NzbDroneLogger() @@ -19,7 +21,6 @@ namespace NzbDrone.Common.Instrumentation LogManager.Configuration = new LoggingConfiguration(); } - public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole) { if (_isConfigured) @@ -61,13 +62,11 @@ namespace NzbDrone.Common.Instrumentation private static void RegisterSentry(bool updateClient) { - string dsn; if (updateClient) { dsn = "https://379d628d45ba475a98d2e55675d14a02@sentry.radarr.video/5"; - } else { @@ -117,8 +116,6 @@ namespace NzbDrone.Common.Instrumentation LogManager.Configuration.LoggingRules.Add(loggingRule); } - private const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; - private static void RegisterAppFile(IAppFolderInfo appFolderInfo) { RegisterAppFile(appFolderInfo, "appFileInfo", "radarr.txt", 5, LogLevel.Info); @@ -194,6 +191,5 @@ namespace NzbDrone.Common.Instrumentation { return GetLogger(obj.GetType()); } - } } diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs index 7d351a55a..76f0bcb54 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs @@ -36,7 +36,6 @@ namespace NzbDrone.Common.Instrumentation.Sentry } catch (Exception) { - } return sentryEvent; @@ -50,9 +49,8 @@ namespace NzbDrone.Common.Instrumentation.Sentry var data = b.Data?.ToDictionary(x => x.Key, y => CleanseLogMessage.Cleanse(y.Value)); return new Breadcrumb(message, b.Type, data, b.Category, b.Level); } - catch(Exception) + catch (Exception) { - } return b; @@ -60,7 +58,6 @@ namespace NzbDrone.Common.Instrumentation.Sentry private static string ShortenPath(string path) { - if (string.IsNullOrWhiteSpace(path)) { return null; @@ -68,7 +65,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry // the paths in the stacktrace depend on where it was compiled, // not the current OS - var rootDirs = new [] { "\\src\\", "/src/" }; + var rootDirs = new[] { "\\src\\", "/src/" }; foreach (var rootDir in rootDirs) { var index = path.IndexOf(rootDir, StringComparison.Ordinal); diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs index adacdf906..11cd1bdf3 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs @@ -1,10 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Data.SQLite; using System.Linq; using System.Net; using System.Threading; -using System.Data.SQLite; using NLog; using NLog.Common; using NLog.Targets; @@ -21,7 +21,8 @@ namespace NzbDrone.Common.Instrumentation.Sentry // don't report uninformative SQLite exceptions // busy/locked are benign https://forums.sonarr.tv/t/owin-sqlite-error-5-database-is-locked/5423/11 // The others will be user configuration problems and silt up Sentry - private static readonly HashSet FilteredSQLiteErrors = new HashSet { + private static readonly HashSet FilteredSQLiteErrors = new HashSet + { SQLiteErrorCode.Busy, SQLiteErrorCode.Locked, SQLiteErrorCode.Perm, @@ -35,18 +36,23 @@ namespace NzbDrone.Common.Instrumentation.Sentry // use string and not Type so we don't need a reference to the project // where these are defined - private static readonly HashSet FilteredExceptionTypeNames = new HashSet { + private static readonly HashSet FilteredExceptionTypeNames = new HashSet + { // UnauthorizedAccessExceptions will just be user configuration issues "UnauthorizedAccessException", + // Filter out people stuck in boot loops "CorruptDatabaseException", + // This also filters some people in boot loops "TinyIoCResolutionException" }; - public static readonly List FilteredExceptionMessages = new List { + public static readonly List FilteredExceptionMessages = new List + { // Swallow the many, many exceptions flowing through from Jackett "Jackett.Common.IndexerException", + // Fix openflixr being stupid with permissions "openflixr" }; @@ -54,35 +60,36 @@ namespace NzbDrone.Common.Instrumentation.Sentry // exception types in this list will additionally have the exception message added to the // sentry fingerprint. Make sure that this message doesn't vary by exception // (e.g. containing a path or a url) so that the sentry grouping is sensible - private static readonly HashSet IncludeExceptionMessageTypes = new HashSet { + private static readonly HashSet IncludeExceptionMessageTypes = new HashSet + { "SQLiteException" }; private static readonly IDictionary LoggingLevelMap = new Dictionary { - {LogLevel.Debug, SentryLevel.Debug}, - {LogLevel.Error, SentryLevel.Error}, - {LogLevel.Fatal, SentryLevel.Fatal}, - {LogLevel.Info, SentryLevel.Info}, - {LogLevel.Trace, SentryLevel.Debug}, - {LogLevel.Warn, SentryLevel.Warning}, + { LogLevel.Debug, SentryLevel.Debug }, + { LogLevel.Error, SentryLevel.Error }, + { LogLevel.Fatal, SentryLevel.Fatal }, + { LogLevel.Info, SentryLevel.Info }, + { LogLevel.Trace, SentryLevel.Debug }, + { LogLevel.Warn, SentryLevel.Warning }, }; private static readonly IDictionary BreadcrumbLevelMap = new Dictionary { - {LogLevel.Debug, BreadcrumbLevel.Debug}, - {LogLevel.Error, BreadcrumbLevel.Error}, - {LogLevel.Fatal, BreadcrumbLevel.Critical}, - {LogLevel.Info, BreadcrumbLevel.Info}, - {LogLevel.Trace, BreadcrumbLevel.Debug}, - {LogLevel.Warn, BreadcrumbLevel.Warning}, + { LogLevel.Debug, BreadcrumbLevel.Debug }, + { LogLevel.Error, BreadcrumbLevel.Error }, + { LogLevel.Fatal, BreadcrumbLevel.Critical }, + { LogLevel.Info, BreadcrumbLevel.Info }, + { LogLevel.Trace, BreadcrumbLevel.Debug }, + { LogLevel.Warn, BreadcrumbLevel.Warning }, }; private readonly DateTime _startTime = DateTime.UtcNow; private readonly IDisposable _sdk; - private bool _disposed; - private readonly SentryDebounce _debounce; + + private bool _disposed; private bool _unauthorized; public bool FilterEvents { get; set; } @@ -105,6 +112,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry // TODO: Check specific version o.RequestBodyCompressionLevel = System.IO.Compression.CompressionLevel.NoCompression; } + o.BeforeSend = x => SentryCleanser.CleanseEvent(x); o.BeforeBreadcrumb = x => SentryCleanser.CleanseBreadcrumb(x); o.Environment = BuildInfo.Branch; @@ -257,7 +265,6 @@ namespace NzbDrone.Common.Instrumentation.Sentry return false; } - protected override void Write(LogEventInfo logEvent) { if (_unauthorized || !SentryEnabled) @@ -322,6 +329,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry { _sdk?.Dispose(); } + // Flag us as disposed. This allows us to handle multiple calls to Dispose() as well as ObjectDisposedException _disposed = true; } diff --git a/src/NzbDrone.Common/OAuth/OAuthRequest.cs b/src/NzbDrone.Common/OAuth/OAuthRequest.cs index 9c3476101..7f84d9e7f 100644 --- a/src/NzbDrone.Common/OAuth/OAuthRequest.cs +++ b/src/NzbDrone.Common/OAuth/OAuthRequest.cs @@ -32,8 +32,6 @@ namespace NzbDrone.Common.OAuth /// public virtual string RequestUrl { get; set; } - #region Authorization Header - #if !WINRT public string GetAuthorizationHeader(NameValueCollection parameters) { @@ -121,10 +119,6 @@ namespace NzbDrone.Common.OAuth return authorization; } - #endregion - - #region Authorization Query - #if !WINRT public string GetAuthorizationQuery(NameValueCollection parameters) { @@ -209,8 +203,6 @@ namespace NzbDrone.Common.OAuth return authorization; } - #endregion - private string GetNewSignature(WebParameterCollection parameters) { var timestamp = OAuthTools.GetTimestamp(); @@ -241,8 +233,6 @@ namespace NzbDrone.Common.OAuth return signature; } - #region Static Helpers - public static OAuthRequest ForRequestToken(string consumerKey, string consumerSecret) { var credentials = new OAuthRequest @@ -335,8 +325,6 @@ namespace NzbDrone.Common.OAuth return credentials; } - #endregion - private void ValidateRequestState() { if (IsNullOrBlank(Method)) @@ -500,9 +488,7 @@ namespace NzbDrone.Common.OAuth private static bool IsNullOrBlank(string value) { - return String.IsNullOrEmpty(value) || (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); + return string.IsNullOrEmpty(value) || (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty); } } } - - diff --git a/src/NzbDrone.Common/OAuth/OAuthTools.cs b/src/NzbDrone.Common/OAuth/OAuthTools.cs index 40d936ed2..c2b14c519 100644 --- a/src/NzbDrone.Common/OAuth/OAuthTools.cs +++ b/src/NzbDrone.Common/OAuth/OAuthTools.cs @@ -61,7 +61,7 @@ namespace NzbDrone.Common.OAuth /// public static string GetNonce() { - const string chars = (Lower + Digit); + const string chars = Lower + Digit; var nonce = new char[16]; lock (_randomLock) @@ -71,6 +71,7 @@ namespace NzbDrone.Common.OAuth nonce[i] = chars[_random.Next(0, chars.Length)]; } } + return new string(nonce); } @@ -98,7 +99,7 @@ namespace NzbDrone.Common.OAuth private static long ToUnixTime(DateTime dateTime) { - var timeSpan = (dateTime - new DateTime(1970, 1, 1)); + var timeSpan = dateTime - new DateTime(1970, 1, 1); var timestamp = (long)timeSpan.TotalSeconds; return timestamp; @@ -138,6 +139,7 @@ namespace NzbDrone.Common.OAuth sb.Append(string.Format("%{0:X}", b)); } } + return sb.ToString(); } @@ -155,8 +157,7 @@ namespace NzbDrone.Common.OAuth var ret = original.OfType().Where( c => !Unreserved.OfType().Contains(c) && c != '%').Aggregate( value, (current, c) => current.Replace( - c.ToString(), PercentEncode(c.ToString()) - )); + c.ToString(), PercentEncode(c.ToString()))); return ret.Replace("%%", "%25%"); // Revisit to encode actual %'s } @@ -211,7 +212,7 @@ namespace NzbDrone.Common.OAuth copy.RemoveAll(exclusions); - foreach(var parameter in copy) + foreach (var parameter in copy) { parameter.Value = UrlEncodeStrict(parameter.Value); } @@ -225,7 +226,7 @@ namespace NzbDrone.Common.OAuth #if WINRT return CultureInfo.InvariantCulture.CompareInfo.Compare(left, right, CompareOptions.IgnoreCase) == 0; #else - return String.Compare(left, right, StringComparison.InvariantCultureIgnoreCase) == 0; + return string.Compare(left, right, StringComparison.InvariantCultureIgnoreCase) == 0; #endif } @@ -353,7 +354,7 @@ namespace NzbDrone.Common.OAuth { if (IsNullOrBlank(tokenSecret)) { - tokenSecret = String.Empty; + tokenSecret = string.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); @@ -381,6 +382,7 @@ namespace NzbDrone.Common.OAuth break; } + default: throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); } @@ -403,7 +405,7 @@ namespace NzbDrone.Common.OAuth private static bool IsNullOrBlank(string value) { - return String.IsNullOrEmpty(value) || (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); + return string.IsNullOrEmpty(value) || (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty); } } } diff --git a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs index 511aec066..a1084a0ef 100644 --- a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs +++ b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs @@ -1,8 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Collections.Specialized; +using System.Linq; namespace NzbDrone.Common.OAuth { @@ -16,12 +16,12 @@ namespace NzbDrone.Common.OAuth { var parameters = this.Where(p => p.Name.Equals(name)); - if(parameters.Count() == 0) + if (parameters.Count() == 0) { return null; } - if(parameters.Count() == 1) + if (parameters.Count() == 1) { return parameters.Single(); } @@ -47,7 +47,8 @@ namespace NzbDrone.Common.OAuth } #if !WINRT - public WebParameterCollection(NameValueCollection collection) : this() + public WebParameterCollection(NameValueCollection collection) + : this() { AddCollection(collection); } @@ -67,7 +68,8 @@ namespace NzbDrone.Common.OAuth } #endif - public WebParameterCollection(IDictionary collection) : this() + public WebParameterCollection(IDictionary collection) + : this() { AddCollection(collection); } @@ -128,8 +130,6 @@ namespace NzbDrone.Common.OAuth _parameters.Add(pair); } - #region IList Members - public virtual IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); @@ -142,7 +142,6 @@ namespace NzbDrone.Common.OAuth public virtual void Add(WebParameter parameter) { - _parameters.Add(parameter); } @@ -196,7 +195,5 @@ namespace NzbDrone.Common.OAuth get { return _parameters[index]; } set { _parameters[index] = value; } } - - #endregion } } diff --git a/src/NzbDrone.Common/PathEqualityComparer.cs b/src/NzbDrone.Common/PathEqualityComparer.cs index f015792c3..d443a3bf0 100644 --- a/src/NzbDrone.Common/PathEqualityComparer.cs +++ b/src/NzbDrone.Common/PathEqualityComparer.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Common private PathEqualityComparer() { - } public bool Equals(string x, string y) diff --git a/src/NzbDrone.Common/Processes/ProcessProvider.cs b/src/NzbDrone.Common/Processes/ProcessProvider.cs index 19a2c9a13..685a36679 100644 --- a/src/NzbDrone.Common/Processes/ProcessProvider.cs +++ b/src/NzbDrone.Common/Processes/ProcessProvider.cs @@ -136,7 +136,6 @@ namespace NzbDrone.Common.Processes { _logger.Error(e, "Unable to set environment variable '{0}', value is null", environmentVariable.Key); } - else { _logger.Error(e, "Unable to set environment variable '{0}'", environmentVariable.Key); @@ -156,7 +155,10 @@ namespace NzbDrone.Common.Processes process.OutputDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Debug(eventArgs.Data); @@ -168,7 +170,10 @@ namespace NzbDrone.Common.Processes process.ErrorDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Error(eventArgs.Data); @@ -209,8 +214,11 @@ namespace NzbDrone.Common.Processes public ProcessOutput StartAndCapture(string path, string args = null, StringDictionary environmentVariables = null) { var output = new ProcessOutput(); - var process = Start(path, args, environmentVariables, s => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Standard, s)), - error => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Error, error))); + var process = Start(path, + args, + environmentVariables, + s => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Standard, s)), + error => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Error, error))); process.WaitForExit(); output.ExitCode = process.ExitCode; @@ -283,7 +291,10 @@ namespace NzbDrone.Common.Processes private ProcessInfo ConvertToProcessInfo(Process process) { - if (process == null) return null; + if (process == null) + { + return null; + } process.Refresh(); @@ -291,7 +302,10 @@ namespace NzbDrone.Common.Processes try { - if (process.Id <= 0) return null; + if (process.Id <= 0) + { + return null; + } processInfo = new ProcessInfo(); processInfo.Id = process.Id; @@ -309,7 +323,6 @@ namespace NzbDrone.Common.Processes } return processInfo; - } private static string GetExeFileName(Process process) @@ -325,7 +338,6 @@ namespace NzbDrone.Common.Processes private List GetProcessesByName(string name) { //TODO: move this to an OS specific class - var monoProcesses = Process.GetProcessesByName("mono") .Union(Process.GetProcessesByName("mono-sgen")) .Union(Process.GetProcessesByName("mono-sgen32")) diff --git a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs index 2346b288a..6280e1c56 100644 --- a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs +++ b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs @@ -29,7 +29,6 @@ namespace NzbDrone.Common.Reflection type = type.GetGenericArguments()[0]; } - return type.IsPrimitive || type.IsEnum || type == typeof(string) @@ -48,7 +47,8 @@ namespace NzbDrone.Common.Reflection return propertyInfo.CanWrite && propertyInfo.GetSetMethod(false) != null; } - public static T GetAttribute(this MemberInfo member, bool isRequired = true) where T : Attribute + public static T GetAttribute(this MemberInfo member, bool isRequired = true) + where T : Attribute { var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault(); @@ -60,7 +60,8 @@ namespace NzbDrone.Common.Reflection return (T)attribute; } - public static T[] GetAttributes(this MemberInfo member) where T : Attribute + public static T[] GetAttributes(this MemberInfo member) + where T : Attribute { return member.GetCustomAttributes(typeof(T), false).OfType().ToArray(); } diff --git a/src/NzbDrone.Common/Serializer/IntConverter.cs b/src/NzbDrone.Common/Serializer/IntConverter.cs index 63b4eb213..e49676735 100644 --- a/src/NzbDrone.Common/Serializer/IntConverter.cs +++ b/src/NzbDrone.Common/Serializer/IntConverter.cs @@ -23,6 +23,7 @@ namespace NzbDrone.Common.Serializer { throw new JsonSerializationException("Can't convert type " + existingValue.GetType().FullName + " to number"); } + if (objectType == typeof(long)) { return Convert.ToInt64(reader.Value); diff --git a/src/NzbDrone.Common/Serializer/Json.cs b/src/NzbDrone.Common/Serializer/Json.cs index fe05b01a4..8a23c3f86 100644 --- a/src/NzbDrone.Common/Serializer/Json.cs +++ b/src/NzbDrone.Common/Serializer/Json.cs @@ -36,7 +36,8 @@ namespace NzbDrone.Common.Serializer return serializerSettings; } - public static T Deserialize(string json) where T : new() + public static T Deserialize(string json) + where T : new() { try { @@ -95,7 +96,8 @@ namespace NzbDrone.Common.Serializer return ex; } - public static bool TryDeserialize(string json, out T result) where T : new() + public static bool TryDeserialize(string json, out T result) + where T : new() { try { diff --git a/src/NzbDrone.Common/Serializer/JsonVisitor.cs b/src/NzbDrone.Common/Serializer/JsonVisitor.cs index 4b613589d..0e69a0ae0 100644 --- a/src/NzbDrone.Common/Serializer/JsonVisitor.cs +++ b/src/NzbDrone.Common/Serializer/JsonVisitor.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Common.Serializer { - public class JsonVisitor { protected void Dispatch(JToken json) @@ -66,6 +65,7 @@ namespace NzbDrone.Common.Serializer Visit(token); } } + public virtual void Visit(JConstructor json) { } @@ -85,7 +85,6 @@ namespace NzbDrone.Common.Serializer public virtual void Visit(JValue value) { - } } } diff --git a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs index 9022c029f..772f5640c 100644 --- a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs +++ b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs @@ -48,8 +48,10 @@ namespace NzbDrone.Common.Serializer { builder.Append('_'); } + builder.Append(char.ToLower(enumText[i])); } + enumText = builder.ToString(); writer.WriteValue(enumText); diff --git a/src/NzbDrone.Common/ServiceFactory.cs b/src/NzbDrone.Common/ServiceFactory.cs index 061dd22a2..4f7e4bb0b 100644 --- a/src/NzbDrone.Common/ServiceFactory.cs +++ b/src/NzbDrone.Common/ServiceFactory.cs @@ -1,14 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Common.Composition; namespace NzbDrone.Common { public interface IServiceFactory { - T Build() where T : class; - IEnumerable BuildAll() where T : class; + T Build() + where T : class; + IEnumerable BuildAll() + where T : class; object Build(Type contract); IEnumerable GetImplementations(Type contract); } @@ -22,12 +24,14 @@ namespace NzbDrone.Common _container = container; } - public T Build() where T : class + public T Build() + where T : class { return _container.Resolve(); } - public IEnumerable BuildAll() where T : class + public IEnumerable BuildAll() + where T : class { return _container.ResolveAll().GroupBy(c => c.GetType().FullName).Select(g => g.First()); } diff --git a/src/NzbDrone.Common/ServiceProvider.cs b/src/NzbDrone.Common/ServiceProvider.cs index 75d3b415c..349fa083a 100644 --- a/src/NzbDrone.Common/ServiceProvider.cs +++ b/src/NzbDrone.Common/ServiceProvider.cs @@ -60,7 +60,6 @@ namespace NzbDrone.Common public virtual void Install(string serviceName) { - _logger.Info("Installing service '{0}'", serviceName); var args = $"create {serviceName} " + @@ -151,7 +150,7 @@ namespace NzbDrone.Common public ServiceControllerStatus GetStatus(string serviceName) { - return GetService(serviceName).Status; + return GetService(serviceName).Status; } public void Start(string serviceName) diff --git a/src/NzbDrone.Common/TPL/Debouncer.cs b/src/NzbDrone.Common/TPL/Debouncer.cs index 08ee3b71d..0fa101525 100644 --- a/src/NzbDrone.Common/TPL/Debouncer.cs +++ b/src/NzbDrone.Common/TPL/Debouncer.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Common.TPL _timer.Elapsed += timer_Elapsed; } - void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (_paused == 0) { diff --git a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs index c3d0372d6..2f1a295b5 100644 --- a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs +++ b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs @@ -11,12 +11,15 @@ namespace NzbDrone.Common.TPL /// Whether the current thread is processing work items. [ThreadStatic] private static bool _currentThreadIsProcessingItems; + /// The list of tasks to be executed. - private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + private readonly LinkedList _tasks = new LinkedList(); + /// The maximum concurrency level allowed by this scheduler. private readonly int _maxDegreeOfParallelism; + /// Whether the scheduler is currently processing work items. - private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks) + private int _delegatesQueuedOrRunning = 0; /// /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the @@ -25,7 +28,11 @@ namespace NzbDrone.Common.TPL /// The maximum degree of parallelism provided by this scheduler. public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) { - if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + if (maxDegreeOfParallelism < 1) + { + throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + } + _maxDegreeOfParallelism = maxDegreeOfParallelism; } @@ -78,11 +85,15 @@ namespace NzbDrone.Common.TPL } // Execute the task we pulled out of the queue - base.TryExecuteTask(item); + TryExecuteTask(item); } } + // We're done processing items on the current thread - finally { _currentThreadIsProcessingItems = false; } + finally + { + _currentThreadIsProcessingItems = false; + } }, null); } @@ -93,13 +104,19 @@ namespace NzbDrone.Common.TPL protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If this thread isn't already processing a task, we don't support inlining - if (!_currentThreadIsProcessingItems) return false; + if (!_currentThreadIsProcessingItems) + { + return false; + } // If the task was previously queued, remove it from the queue - if (taskWasPreviouslyQueued) TryDequeue(task); + if (taskWasPreviouslyQueued) + { + TryDequeue(task); + } // Try to run the task. - return base.TryExecuteTask(task); + return TryExecuteTask(task); } /// Attempts to remove a previously scheduled task from the scheduler. @@ -107,7 +124,10 @@ namespace NzbDrone.Common.TPL /// Whether the task could be found and removed. protected sealed override bool TryDequeue(Task task) { - lock (_tasks) return _tasks.Remove(task); + lock (_tasks) + { + return _tasks.Remove(task); + } } /// Gets the maximum concurrency level supported by this scheduler. @@ -121,12 +141,21 @@ namespace NzbDrone.Common.TPL try { Monitor.TryEnter(_tasks, ref lockTaken); - if (lockTaken) return _tasks.ToArray(); - else throw new NotSupportedException(); + if (lockTaken) + { + return _tasks.ToArray(); + } + else + { + throw new NotSupportedException(); + } } finally { - if (lockTaken) Monitor.Exit(_tasks); + if (lockTaken) + { + Monitor.Exit(_tasks); + } } } } diff --git a/src/NzbDrone.Common/TPL/RateLimitService.cs b/src/NzbDrone.Common/TPL/RateLimitService.cs index 6d1b9ee17..f0d30b4ff 100644 --- a/src/NzbDrone.Common/TPL/RateLimitService.cs +++ b/src/NzbDrone.Common/TPL/RateLimitService.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Common.TPL { var waitUntil = _rateLimitStore.AddOrUpdate(key, (s) => DateTime.UtcNow + interval, - (s,i) => new DateTime(Math.Max(DateTime.UtcNow.Ticks, i.Ticks), DateTimeKind.Utc) + interval); + (s, i) => new DateTime(Math.Max(DateTime.UtcNow.Ticks, i.Ticks), DateTimeKind.Utc) + interval); waitUntil -= interval; diff --git a/src/NzbDrone.Common/TinyIoC.cs b/src/NzbDrone.Common/TinyIoC.cs index 2edfd4f94..f3ac33d59 100644 --- a/src/NzbDrone.Common/TinyIoC.cs +++ b/src/NzbDrone.Common/TinyIoC.cs @@ -13,7 +13,10 @@ // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== +#pragma warning disable SX1101, SA1108, SA1119, SA1124, SA1200, SA1208, SA1314, SA1403, SA1503, SA1514, SA1515, SA1519, SX1309 + #region Preprocessor Directives + // Uncomment this line if you want the container to automatically // register the TinyMessenger messenger/event aggregator //#define TINYMESSENGER @@ -21,7 +24,6 @@ // Preprocessor directives for enabling/disabling functionality // depending on platform features. If the platform has an appropriate // #DEFINE then these should be set automatically below. - #define EXPRESSIONS // Platform supports System.Linq.Expressions #define COMPILED_EXPRESSIONS // Platform supports compiling expressions #define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object @@ -278,7 +280,7 @@ namespace TinyIoC GC.SuppressFinalize(this); } - #endregion + #endregion } #endif #endregion @@ -376,8 +378,8 @@ namespace TinyIoC return method; } - //#endif + //#endif #if NETFX_CORE private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes) { @@ -509,7 +511,6 @@ namespace TinyIoC } } } - } // @mbrit - 2012-05-22 - shim for ForEach call on List... @@ -1123,7 +1124,6 @@ namespace TinyIoC public RegisterOptions Register(Type registerType, string name) { return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType)); - } /// @@ -1386,10 +1386,12 @@ namespace TinyIoC throw new ArgumentNullException("types", "types is null."); foreach (var type in implementationTypes) + //#if NETFX_CORE // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) //#else if (!registrationType.IsAssignableFrom(type)) + //#endif throw new ArgumentException(string.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); @@ -1398,8 +1400,8 @@ namespace TinyIoC var queryForDuplicatedTypes = from i in implementationTypes group i by i into j - where j.Count() > 1 - select j.Key.FullName; + where j.Count() > 1 + select j.Key.FullName; var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes); @@ -2451,6 +2453,7 @@ namespace TinyIoC //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + //#endif if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); @@ -2716,6 +2719,7 @@ namespace TinyIoC // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); @@ -2792,6 +2796,7 @@ namespace TinyIoC // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage); @@ -2915,6 +2920,7 @@ namespace TinyIoC return _hashCode; } } + private readonly SafeDictionary _RegisteredTypes; #if USE_OBJECT_CONSTRUCTOR private delegate object ObjectConstructor(params object[] parameters); @@ -2930,7 +2936,7 @@ namespace TinyIoC RegisterDefaultTypes(); } - TinyIoCContainer _Parent; + private TinyIoCContainer _Parent; private TinyIoCContainer(TinyIoCContainer parent) : this() { @@ -3096,6 +3102,7 @@ namespace TinyIoC // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) //#else if (registerType.IsInterface() || registerType.IsAbstract()) + //#endif return new SingletonFactory(registerType, registerImplementation); @@ -3188,6 +3195,7 @@ namespace TinyIoC // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) //#else if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) + //#endif return true; @@ -3196,6 +3204,7 @@ namespace TinyIoC // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) + //#endif return true; @@ -3330,10 +3339,12 @@ namespace TinyIoC return null; Type genericType = type.GetGenericTypeDefinition(); + //#if NETFX_CORE // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); //#else Type[] genericArguments = type.GetGenericArguments(); + //#endif // Just a func @@ -3345,6 +3356,7 @@ namespace TinyIoC // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3364,6 +3376,7 @@ namespace TinyIoC // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string) }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3380,6 +3393,7 @@ namespace TinyIoC // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) + //#endif { Type returnType = genericArguments[2]; @@ -3391,6 +3405,7 @@ namespace TinyIoC // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string), typeof(NamedParameterOverloads) }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3410,8 +3425,8 @@ namespace TinyIoC // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); //#else var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); - //#endif + //#endif return genericResolveAllMethod.Invoke(this, new object[] { false }); } @@ -3431,6 +3446,7 @@ namespace TinyIoC // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) //#else if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) + //#endif return false; @@ -3450,6 +3466,7 @@ namespace TinyIoC // if (type.GetTypeInfo().IsValueType) //#else if (type.IsValueType()) + //#endif return null; @@ -3472,6 +3489,7 @@ namespace TinyIoC // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); //#else return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); + //#endif } @@ -3524,15 +3542,12 @@ namespace TinyIoC try { - if (ctorParams[parameterIndex].ParameterType == typeof(Logger)) { args[parameterIndex] = LogManager.GetLogger(implementationType.Name); } else { - - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? parameters[currentParam.Name] : ResolveInternal( @@ -3612,8 +3627,8 @@ namespace TinyIoC var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() select property; - //#endif + //#endif foreach (var property in properties) { if (property.GetValue(input, null) == null) @@ -3691,6 +3706,7 @@ namespace TinyIoC return false; } } + //#endif return true; } @@ -3698,7 +3714,7 @@ namespace TinyIoC #endregion #region IDisposable Members - bool disposed = false; + private bool disposed = false; public void Dispose() { if (!disposed) @@ -3713,7 +3729,6 @@ namespace TinyIoC #endregion } - } // reverse shim for WinRT SR changes... diff --git a/src/NzbDrone.Console/ConsoleApp.cs b/src/NzbDrone.Console/ConsoleApp.cs index ef1c750ad..47cdbe2fc 100644 --- a/src/NzbDrone.Console/ConsoleApp.cs +++ b/src/NzbDrone.Console/ConsoleApp.cs @@ -35,6 +35,7 @@ namespace NzbDrone.Console System.Console.WriteLine("NLog Exception: " + ex.ToString()); throw; } + Bootstrap.Start(startupArgs, new ConsoleAlerts()); } catch (RadarrStartupException ex) @@ -87,7 +88,10 @@ namespace NzbDrone.Console for (int i = 0; i < 3600; i++) { System.Threading.Thread.Sleep(1000); - if (!System.Console.IsInputRedirected && System.Console.KeyAvailable) break; + if (!System.Console.IsInputRedirected && System.Console.KeyAvailable) + { + break; + } } } diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs index 2f87fa27e..8894c05df 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs @@ -19,13 +19,13 @@ namespace NzbDrone.Core.Test.Blacklisting public void Setup() { _blacklist = new Blacklist - { - MovieId = 1234, - Quality = new QualityModel(), - Languages = new List(), - SourceTitle = "movie.title.1998", - Date = DateTime.UtcNow - }; + { + MovieId = 1234, + Quality = new QualityModel(), + Languages = new List(), + SourceTitle = "movie.title.1998", + Date = DateTime.UtcNow + }; } [Test] diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs index 74eaeb2de..dfe82adff 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs @@ -17,13 +17,13 @@ namespace NzbDrone.Core.Test.Blacklisting public void Setup() { _event = new DownloadFailedEvent - { - MovieId = 69, - Quality = new QualityModel(), - SourceTitle = "series.title.s01e01", - DownloadClient = "SabnzbdClient", - DownloadId = "Sabnzbd_nzo_2dfh73k" - }; + { + MovieId = 69, + Quality = new QualityModel(), + SourceTitle = "series.title.s01e01", + DownloadClient = "SabnzbdClient", + DownloadId = "Sabnzbd_nzo_2dfh73k" + }; _event.Data.Add("publishedDate", DateTime.UtcNow.ToString("s") + "Z"); _event.Data.Add("size", "1000"); diff --git a/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs b/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs index 9efa445a3..6980224a0 100644 --- a/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs +++ b/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs @@ -1,24 +1,24 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; -using NUnit.Framework; using Moq; -using NzbDrone.Core.Organizer; +using NUnit.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.BulkImport { [TestFixture] public class AddMultiMoviesFixture : CoreTest { - private List fakeMovies; + private List _fakeMovies; [SetUp] public void Setup() { - fakeMovies = Builder.CreateListOfSize(3).BuildList(); - fakeMovies.ForEach(m => + _fakeMovies = Builder.CreateListOfSize(3).BuildList(); + _fakeMovies.ForEach(m => { m.Path = null; m.RootFolderPath = @"C:\Test\TV"; @@ -32,7 +32,7 @@ namespace NzbDrone.Core.Test.BulkImport .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); foreach (Movie movie in movies) { @@ -49,9 +49,9 @@ namespace NzbDrone.Core.Test.BulkImport .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - Mocker.GetMock().Setup(s => s.All()).Returns(new List { fakeMovies[0] }); + Mocker.GetMock().Setup(s => s.All()).Returns(new List { _fakeMovies[0] }); - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); Mocker.GetMock().Verify(v => v.InsertMany(It.Is>(l => l.Count == 2))); } @@ -63,12 +63,11 @@ namespace NzbDrone.Core.Test.BulkImport .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - fakeMovies[2].TmdbId = fakeMovies[0].TmdbId; + _fakeMovies[2].TmdbId = _fakeMovies[0].TmdbId; - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); Mocker.GetMock().Verify(v => v.InsertMany(It.Is>(l => l.Count == 2))); } - } } diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs index 087a854d7..c903cb839 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs @@ -5,7 +5,6 @@ using NUnit.Framework; using NzbDrone.Core.Configuration; using NzbDrone.Core.Test.Framework; - namespace NzbDrone.Core.Test.Configuration { [TestFixture] @@ -16,7 +15,6 @@ namespace NzbDrone.Core.Test.Configuration { Mocker.GetMock().Setup(c => c.All()) .Returns(new List { new Config { Key = "key1", Value = "Value1" } }); - } [Test] @@ -28,6 +26,5 @@ namespace NzbDrone.Core.Test.Configuration Mocker.GetMock().Verify(c => c.All(), Times.Once()); } - } } diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs index ee834d507..2ed847f4e 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs @@ -28,7 +28,6 @@ namespace NzbDrone.Core.Test.Configuration AssertUpsert(key, value); } - [Test] public void Get_value_should_return_default_when_no_value() { diff --git a/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs b/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs index 51493cb1e..492150de7 100644 --- a/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs +++ b/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.CustomFormat public static List GetSampleFormatItems(params string[] allowed) { - return _customFormats.Select(f => new ProfileFormatItem {Format = f, Allowed = allowed.Contains(f.Name)}).ToList(); + return _customFormats.Select(f => new ProfileFormatItem { Format = f, Allowed = allowed.Contains(f.Name) }).ToList(); } public static List GetDefaultFormatItems() diff --git a/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs b/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs index 236e1c1e7..828bba689 100644 --- a/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs +++ b/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs @@ -21,6 +21,7 @@ namespace NzbDrone.Core.Test.CustomFormat [TestCase("s_Dvd", TagType.Source, Source.DVD)] [TestCase("S_WEBdL", TagType.Source, Source.WEBDL)] [TestCase("S_CAM", TagType.Source, Source.CAM)] + // [TestCase("L_English", TagType.Language, Language.English)] // [TestCase("L_Italian", TagType.Language, Language.Italian)] // [TestCase("L_iTa", TagType.Language, Language.Italian)] @@ -33,9 +34,9 @@ namespace NzbDrone.Core.Test.CustomFormat [TestCase("C_RQ_Surround", TagType.Custom, "surround", TagModifier.AbsolutelyRequired)] [TestCase("C_RQN_Surround", TagType.Custom, "surround", TagModifier.AbsolutelyRequired, TagModifier.Not)] [TestCase("C_RQNRX_Surround|(5|7)(\\.1)?", TagType.Custom, "surround|(5|7)(\\.1)?", TagModifier.AbsolutelyRequired, TagModifier.Not, TagModifier.Regex)] - [TestCase("G_10<>20", TagType.Size, new[] { 10737418240L, 21474836480L})] - [TestCase("G_15.55<>20", TagType.Size, new[] { 16696685363L, 21474836480L})] - [TestCase("G_15.55<>25.1908754", TagType.Size, new[] { 16696685363L, 27048496500L})] + [TestCase("G_10<>20", TagType.Size, new[] { 10737418240L, 21474836480L })] + [TestCase("G_15.55<>20", TagType.Size, new[] { 16696685363L, 21474836480L })] + [TestCase("G_15.55<>25.1908754", TagType.Size, new[] { 16696685363L, 27048496500L })] [TestCase("R__1080", TagType.Resolution, Resolution.R1080p)] public void should_parse_tag_from_string(string raw, TagType type, object value, params TagModifier[] modifiers) { @@ -45,19 +46,22 @@ namespace NzbDrone.Core.Test.CustomFormat { modifier |= m; } + parsed.TagType.Should().Be(type); if (value is long[]) { - value = (((long[]) value)[0], ((long[]) value)[1]); + value = (((long[])value)[0], ((long[])value)[1]); } + if ((parsed.Value as Regex) != null) { - (parsed.Value as Regex).ToString().Should().Be((value as string)); + (parsed.Value as Regex).ToString().Should().Be(value as string); } else { parsed.Value.Should().Be(value); } + parsed.TagModifier.Should().Be(modifier); } } diff --git a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs index 114647d3a..68f7d9fb5 100644 --- a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs @@ -9,14 +9,12 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class BasicRepositoryFixture : DbTest, ScheduledTask> { private ScheduledTask _basicType; - [SetUp] public void Setup() { @@ -44,10 +42,8 @@ namespace NzbDrone.Core.Test.Datastore Subject.Purge(); AllStoredModels.Should().BeEmpty(); - } - [Test] public void should_be_able_to_delete_model() { @@ -64,7 +60,7 @@ namespace NzbDrone.Core.Test.Datastore Subject.Insert(_basicType); var storeObject = Subject.Get(_basicType.Id); - storeObject.Should().BeEquivalentTo(_basicType, o=>o.IncludingAllRuntimeProperties()); + storeObject.Should().BeEquivalentTo(_basicType, o => o.IncludingAllRuntimeProperties()); } [Test] @@ -86,19 +82,16 @@ namespace NzbDrone.Core.Test.Datastore Assert.Throws(() => Subject.Get(12)); } - [Test] public void get_all_with_empty_db_should_return_empty_list() { Subject.All().Should().BeEmpty(); } - [Test] public void should_be_able_to_call_ToList_on_empty_quariable() { Subject.All().ToList().Should().BeEmpty(); - } } } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs index 649a7303e..50e1b892b 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs @@ -27,9 +27,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_bool_when_getting_int_from_db(int input, bool expected) { var context = new ConverterContext - { - DbValue = (long)input - }; + { + DbValue = (long)input + }; Subject.FromDB(context).Should().Be(expected); } @@ -38,9 +38,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_db_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } @@ -49,9 +49,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_throw_for_non_boolean_equivalent_number_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = (long)2 - }; + { + DbValue = 2L + }; Assert.Throws(() => Subject.FromDB(context)); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs index 17ce66cfb..4921bfda2 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs @@ -6,8 +6,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -42,10 +42,10 @@ namespace NzbDrone.Core.Test.Datastore.Converters dataRecordMock.Setup(s => s.GetString(0)).Returns("RefreshMovie"); var context = new ConverterContext - { - DataRecord = dataRecordMock.Object, - DbValue = new RefreshMovieCommand().ToJson() - }; + { + DataRecord = dataRecordMock.Object, + DbValue = new RefreshMovieCommand().ToJson() + }; Subject.FromDB(context).Should().BeOfType(); } @@ -54,9 +54,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(null); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs index bf4974124..1b5c09c7a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs @@ -36,9 +36,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = 10.5D; var context = new ConverterContext - { - DbValue = expected - }; + { + DbValue = expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -49,9 +49,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = 10.5D; var context = new ConverterContext - { - DbValue = $"{expected}" - }; + { + DbValue = $"{expected}" + }; Subject.FromDB(context).Should().Be(expected); } @@ -60,9 +60,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs index a09b49dd3..494bba760 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs @@ -5,8 +5,8 @@ using Marr.Data.Converters; using Marr.Data.Mapping; using Moq; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -35,10 +35,10 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = PendingReleaseReason.Delay; var context = new ConverterContext - { - ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(PendingReleaseReason) }, - DbValue = (long)expected - }; + { + ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(PendingReleaseReason) }, + DbValue = (long)expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -47,9 +47,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(null); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs index 8444fa053..2d4a8e530 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs @@ -30,9 +30,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var guid = Guid.NewGuid(); var context = new ConverterContext - { - DbValue = guid.ToString() - }; + { + DbValue = guid.ToString() + }; Subject.FromDB(context).Should().Be(guid); } @@ -41,9 +41,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_empty_guid_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(Guid.Empty); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs index 0be50e92a..793eb5f58 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs @@ -24,9 +24,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var i = 5; var context = new ConverterContext - { - DbValue = i - }; + { + DbValue = i + }; Subject.FromDB(context).Should().Be(i); } @@ -37,9 +37,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var i = 5; var context = new ConverterContext - { - DbValue = i.ToString() - }; + { + DbValue = i.ToString() + }; Subject.FromDB(context).Should().Be(i); } @@ -48,9 +48,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs index f7f3da0d8..c0c92efd3 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs @@ -28,9 +28,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var osPath = new OsPath(path); var context = new ConverterContext - { - DbValue = path - }; + { + DbValue = path + }; Subject.FromDB(context).Should().Be(osPath); } @@ -39,9 +39,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs index efc33bf8a..c36758be2 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs @@ -15,10 +15,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_null_config_if_config_is_null() { var result = Subject.FromDB(new ConverterContext() - { - DbValue = DBNull.Value - }); - + { + DbValue = DBNull.Value + }); result.Should().Be(NullConfig.Instance); } @@ -32,7 +31,6 @@ namespace NzbDrone.Core.Test.Datastore.Converters DbValue = dbValue }); - result.Should().Be(NullConfig.Instance); } } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs index 31ae8b6b3..6cad0566a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs @@ -37,9 +37,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var quality = Quality.Bluray1080p; var context = new ConverterContext - { - DbValue = quality.Id - }; + { + DbValue = quality.Id + }; Subject.FromDB(context).Should().Be(quality); } @@ -48,9 +48,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(Quality.Unknown); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs index c96848179..a590bbe62 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs @@ -31,9 +31,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var timeSpan = TimeSpan.FromMinutes(5); var context = new ConverterContext - { - DbValue = timeSpan - }; + { + DbValue = timeSpan + }; Subject.FromDB(context).Should().Be(timeSpan); } @@ -44,9 +44,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var timeSpan = TimeSpan.FromMinutes(5); var context = new ConverterContext - { - DbValue = timeSpan.ToString("c", CultureInfo.InvariantCulture) - }; + { + DbValue = timeSpan.ToString("c", CultureInfo.InvariantCulture) + }; Subject.FromDB(context).Should().Be(timeSpan); } @@ -55,9 +55,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_time_span_zero_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(TimeSpan.Zero); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs index 904f653d3..51c07a1b3 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs @@ -30,8 +30,8 @@ namespace NzbDrone.Core.Test.Datastore.Converters var dateTime = DateTime.Now.ToUniversalTime(); var context = new ConverterContext - { - DbValue = dateTime + { + DbValue = dateTime }; Subject.FromDB(context).Should().Be(dateTime); @@ -41,9 +41,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs index 0196db290..ca59bb729 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs @@ -3,8 +3,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { @@ -20,7 +20,6 @@ namespace NzbDrone.Core.Test.Datastore .BeNull(); } - [Test] public void vaccume() { diff --git a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs index 27810c21d..652a90f7b 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs @@ -1,13 +1,13 @@ +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Collections.Generic; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Datastore { @@ -22,6 +22,7 @@ namespace NzbDrone.Core.Test.Datastore [Ignore("MovieFile isnt lazy loaded anymore so this will fail.")] [Test] + //TODO: Update this! public void one_to_one() { @@ -61,11 +62,10 @@ namespace NzbDrone.Core.Test.Datastore Db.Single().MovieFile.Should().BeNull(); } - [Test] public void embedded_document_as_json() { - var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2 )}; + var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2) }; var languages = new List { Language.English }; var history = Builder.CreateNew() @@ -90,10 +90,8 @@ namespace NzbDrone.Core.Test.Datastore .With(c => c.Languages = languages) .Build().ToList(); - history[0].Quality = new QualityModel { Quality = Quality.HDTV1080p, Revision = new Revision(version: 2)}; - history[1].Quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2)}; - - + history[0].Quality = new QualityModel { Quality = Quality.HDTV1080p, Revision = new Revision(version: 2) }; + history[1].Quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2) }; Db.InsertMany(history); diff --git a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs index fee343581..4780896f3 100644 --- a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs @@ -12,10 +12,8 @@ namespace NzbDrone.Core.Test.Datastore [TestFixture] public class MappingExtensionFixture { - public class EmbeddedType : IEmbeddedDocument { - } public class TypeWithAllMappableProperties @@ -42,10 +40,8 @@ namespace NzbDrone.Core.Test.Datastore MapRepository.Instance.RegisterTypeConverter(typeof(List), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(EmbeddedType), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(int), new Int32Converter()); - } - [Test] public void test_mappable_types() { diff --git a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs index d39c8528c..05cfd3dfb 100644 --- a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs @@ -1,14 +1,13 @@ using FizzWare.NBuilder; using NUnit.Framework; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Qualities; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class MarrDataLazyLoadingFixture : DbTest { @@ -16,12 +15,11 @@ namespace NzbDrone.Core.Test.Datastore public void Setup() { var profile = new Profile - { - Name = "Test", - Cutoff = Quality.WEBDL720p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities() - }; - + { + Name = "Test", + Cutoff = Quality.WEBDL720p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities() + }; profile = Db.Insert(profile); @@ -48,7 +46,5 @@ namespace NzbDrone.Core.Test.Datastore Db.InsertMany(episodes); } - - } } diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs index be2b07b66..62ed62be3 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs @@ -66,30 +66,30 @@ namespace NzbDrone.Core.Test.Datastore.Migration var db = WithMigrationTestDb(c => { c.Insert.IntoTable("Profiles").Row(new - { - GrabDelay = 1, - Name = "OneHour", - Cutoff = 0, - Items = "[]" - }); + { + GrabDelay = 1, + Name = "OneHour", + Cutoff = 0, + Items = "[]" + }); c.Insert.IntoTable("Series").Row(new - { - TvdbId = 0, - TvRageId = 0, - Title = "Series", - TitleSlug = "series", - CleanTitle = "series", - Status = 0, - Images = "[]", - Path = @"C:\Test\Series", - Monitored = 1, - SeasonFolder = 1, - RunTime = 0, - SeriesType = 0, - UseSceneNumbering = 0, - Tags = "[1]" - }); + { + TvdbId = 0, + TvRageId = 0, + Title = "Series", + TitleSlug = "series", + CleanTitle = "series", + Status = 0, + Images = "[]", + Path = @"C:\Test\Series", + Monitored = 1, + SeasonFolder = 1, + RunTime = 0, + SeriesType = 0, + UseSceneNumbering = 0, + Tags = "[1]" + }); }); var tag = db.Query("SELECT Id, Label FROM Tags").Single(); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs index e59c58706..59f66b25a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs @@ -20,16 +20,15 @@ namespace NzbDrone.Core.Test.Datastore.Migration { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","abc"} + { "indexer", "test" }, + { "downloadClientId", "abc" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -40,7 +39,6 @@ namespace NzbDrone.Core.Test.Datastore.Migration history.Should().Contain(c => c.DownloadId == "abc"); } - [Test] public void should_leave_items_with_no_grabid() { @@ -48,15 +46,14 @@ namespace NzbDrone.Core.Test.Datastore.Migration { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"} + { "indexer", "test" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -74,9 +71,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"group","test2"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "group", "test2" }, + { "downloadClientId", "123" } }); }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs index ed94d8354..29d8d411d 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Test.Datastore.Migration db.Query("SELECT * FROM Series").Should().BeEmpty(); } - [Test] public void should_reset_job_last_execution_time() { @@ -58,17 +57,17 @@ namespace NzbDrone.Core.Test.Datastore.Migration c.Insert.IntoTable("Series").Row(new { Tvdbid = 1, - TvRageId =1, - Title ="Title1", - CleanTitle ="CleanTitle1", - Status =1, - Images ="", - Path ="c:\\test", - Monitored =1, - SeasonFolder =1, - Runtime= 0, - SeriesType=0, - UseSceneNumbering =0, + TvRageId = 1, + Title = "Title1", + CleanTitle = "CleanTitle1", + Status = 1, + Images = "", + Path = "c:\\test", + Monitored = 1, + SeasonFolder = 1, + Runtime = 0, + SeriesType = 0, + UseSceneNumbering = 0, LastInfoSync = "2000-01-01 00:00:00" }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs index 7aae7010e..afd2aab45 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs @@ -2,8 +2,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs index 716dedb8b..9a73fb50c 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs @@ -15,6 +15,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration [TestCase("http://kickass.to")] [TestCase("https://kickass.to")] [TestCase("http://kat.cr")] + // [TestCase("HTTP://KICKASS.SO")] Not sure if there is an easy way to do this, not sure if worth it. public void should_replace_old_url(string oldUrl) { diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/147_custom_formatsFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/147_custom_formatsFixture.cs index 6208d659d..1ebf69101 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/147_custom_formatsFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/147_custom_formatsFixture.cs @@ -1,14 +1,14 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Languages; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -31,7 +31,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration public void WithDefaultProfiles(add_custom_formats m) { - AddDefaultProfile(m, "Any", Quality.Bluray480p, + AddDefaultProfile(m, + "Any", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -57,7 +59,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration Quality.Remux2160p, Quality.BRDISK); - AddDefaultProfile(m, "SD", Quality.Bluray480p, + AddDefaultProfile(m, + "SD", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -70,24 +74,32 @@ namespace NzbDrone.Core.Test.Datastore.Migration Quality.Bluray480p, Quality.Bluray576p); - AddDefaultProfile(m, "HD-720p", Quality.Bluray720p, + AddDefaultProfile(m, + "HD-720p", + Quality.Bluray720p, Quality.HDTV720p, Quality.WEBDL720p, Quality.Bluray720p); - AddDefaultProfile(m, "HD-1080p", Quality.Bluray1080p, + AddDefaultProfile(m, + "HD-1080p", + Quality.Bluray1080p, Quality.HDTV1080p, Quality.WEBDL1080p, Quality.Bluray1080p, Quality.Remux1080p); - AddDefaultProfile(m, "Ultra-HD", Quality.Remux2160p, + AddDefaultProfile(m, + "Ultra-HD", + Quality.Remux2160p, Quality.HDTV2160p, Quality.WEBDL2160p, Quality.Bluray2160p, Quality.Remux2160p); - AddDefaultProfile(m, "HD - 720p/1080p", Quality.Bluray720p, + AddDefaultProfile(m, + "HD - 720p/1080p", + Quality.Bluray720p, Quality.HDTV720p, Quality.HDTV1080p, Quality.WEBDL720p, @@ -95,8 +107,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration Quality.Bluray720p, Quality.Bluray1080p, Quality.Remux1080p, - Quality.Remux2160p - ); + Quality.Remux2160p); } [Test] diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/149_regex_required_tagsFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/149_regex_required_tagsFixture.cs index aa5b13885..e4765319b 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/149_regex_required_tagsFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/149_regex_required_tagsFixture.cs @@ -1,5 +1,5 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; @@ -12,10 +12,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration [TestFixture] public class regex_required_tagsFixture : MigrationTest { - public void AddCustomFormat(convert_regex_required_tags c, string name, params string[] formatTags) { - var customFormat = new {Name = name, FormatTags = formatTags.ToList().ToJson()}; + var customFormat = new { Name = name, FormatTags = formatTags.ToList().ToJson() }; c.Insert.IntoTable("CustomFormats").Row(customFormat); } @@ -51,7 +50,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration var convertedTags = items.First().DeserializedTags; convertedTags.Should().HaveCount(3); - convertedTags.Should().BeEquivalentTo( "C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); + convertedTags.Should().BeEquivalentTo("C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); } [Test] @@ -68,7 +67,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration var convertedTags = items.First().DeserializedTags; convertedTags.Should().HaveCount(3); - convertedTags.Should().BeEquivalentTo( "C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); + convertedTags.Should().BeEquivalentTo("C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); var convertedTags2 = items.Last().DeserializedTags; diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs index a7f7430eb..7afde6ef0 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs @@ -1,5 +1,5 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; @@ -12,10 +12,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration [TestFixture] public class fix_format_tags_double_underscoreFixture : MigrationTest { - public void AddCustomFormat(fix_format_tags_double_underscore c, string name, params string[] formatTags) { - var customFormat = new {Name = name, FormatTags = formatTags.ToList().ToJson()}; + var customFormat = new { Name = name, FormatTags = formatTags.ToList().ToJson() }; c.Insert.IntoTable("CustomFormats").Row(customFormat); } diff --git a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs index 84037c050..08577f42a 100644 --- a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs @@ -22,7 +22,6 @@ namespace NzbDrone.Core.Test.Datastore .CreateNew() .With(s => s.Id = 0) .Build(); - } [Test] @@ -72,13 +71,12 @@ namespace NzbDrone.Core.Test.Datastore _sampleType.Id.Should().Be(1); } - [Test] public void should_read_and_write_in_utc() { var storedTime = DateTime.UtcNow; - _sampleType.LastExecution =storedTime; + _sampleType.LastExecution = storedTime; Subject.Insert(_sampleType); @@ -122,15 +120,14 @@ namespace NzbDrone.Core.Test.Datastore item.Id.Should().Be(_sampleType.Id); } - [Test] public void set_fields_should_only_update_selected_filed() { var childModel = new ScheduledTask - { - TypeName = "Address", - Interval = 12 - }; + { + TypeName = "Address", + Interval = 12 + }; Subject.Insert(childModel); @@ -143,6 +140,4 @@ namespace NzbDrone.Core.Test.Datastore Db.All().Single().Interval.Should().Be(12); } } - } - diff --git a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs index ad64ff036..8a51ab9ff 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs @@ -15,15 +15,14 @@ namespace NzbDrone.Core.Test.Datastore.PagingSpecExtensionsTests public void should_calcuate_expected_offset(int page, int pageSize, int expected) { var pagingSpec = new PagingSpec - { - Page = page, - PageSize = pageSize, - SortDirection = SortDirection.Ascending, - SortKey = "AirDate" - }; + { + Page = page, + PageSize = pageSize, + SortDirection = SortDirection.Ascending, + SortKey = "AirDate" + }; pagingSpec.PagingOffset().Should().Be(expected); } - } } diff --git a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs index 0067adb1f..2cb954636 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs @@ -26,12 +26,12 @@ namespace NzbDrone.Core.Test.Datastore.PagingSpecExtensionsTests public void should_convert_ascending_to_asc() { var pagingSpec = new PagingSpec - { - Page = 1, - PageSize = 10, - SortDirection = SortDirection.Ascending, - SortKey = "AirDate" - }; + { + Page = 1, + PageSize = 10, + SortDirection = SortDirection.Ascending, + SortKey = "AirDate" + }; pagingSpec.ToSortDirection().Should().Be(Marr.Data.QGen.SortDirection.Asc); } diff --git a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs index de162f4de..810ae5790 100644 --- a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs +++ b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs @@ -5,36 +5,35 @@ namespace NzbDrone.Core.Test.Datastore.ReflectionStrategyFixture [TestFixture] public class Benchmarks { -/* private const int iterations = 5000000; - private object _target; - private IReflectionStrategy _simpleReflectionStrategy; + /* private const int iterations = 5000000; + private object _target; + private IReflectionStrategy _simpleReflectionStrategy; - [SetUp] - public void Setup() - { - // _simpleReflectionStrategy = new DelegateReflectionStrategy(); - } + [SetUp] + public void Setup() + { + // _simpleReflectionStrategy = new DelegateReflectionStrategy(); + } - [Test] - public void clr_reflection_test() - { - _target = new Series(); + [Test] + public void clr_reflection_test() + { + _target = new Series(); - var del = _simpleReflectionStrategy.BuildSetter(typeof(Series), "Title"); + var del = _simpleReflectionStrategy.BuildSetter(typeof(Series), "Title"); - for (int i = 0; i < iterations; i++) - { - del(_target, "TestTile"); - //_simpleReflectionStrategy.SetFieldValue(_target, "Title", "TestTile"); - } - } + for (int i = 0; i < iterations; i++) + { + del(_target, "TestTile"); + //_simpleReflectionStrategy.SetFieldValue(_target, "Title", "TestTile"); + } + } - private void SetField() - { + private void SetField() + { - }*/ - + }*/ } } diff --git a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs index 43f05bd9c..64efa19ba 100644 --- a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs @@ -76,7 +76,6 @@ namespace NzbDrone.Core.Test.Datastore.SqliteSchemaDumperTests result.Columns.First().Type.Should().Be(DbType.Int64); result.Columns.Last().Name.Should().Be("MyCol"); result.Columns.Last().Type.Should().Be(DbType.Int64); - } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs index 84fb5fa53..c052c7b95 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs @@ -4,10 +4,10 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -16,40 +16,35 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class AcceptableSizeSpecificationFixture : CoreTest { - private Movie movie; - private RemoteMovie remoteMovie; - private QualityDefinition qualityType; + private Movie _movie; + private RemoteMovie _remoteMovie; + private QualityDefinition _qualityType; [SetUp] public void Setup() { + _movie = Builder.CreateNew().Build(); - movie = Builder.CreateNew().Build(); - - qualityType = Builder.CreateNew() + _qualityType = Builder.CreateNew() .With(q => q.MinSize = 2) .With(q => q.MaxSize = 10) .With(q => q.Quality = Quality.SDTV) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { - Movie = movie, + Movie = _movie, Release = new ReleaseInfo(), ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, - }; Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); - - - Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(qualityType); + Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(_qualityType); } - [TestCase(30, 50, false)] [TestCase(30, 250, true)] [TestCase(30, 500, false)] @@ -58,57 +53,57 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [TestCase(60, 1000, false)] public void single_episode(int runtime, int sizeInMegaBytes, bool expectedResult) { - movie.Runtime = runtime; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = sizeInMegaBytes.Megabytes(); + _movie.Runtime = runtime; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(expectedResult); } [Test] public void should_return_true_if_size_is_zero() { - movie.Runtime = 120; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 0; - qualityType.MinSize = 10; - qualityType.MaxSize = 20; + _movie.Runtime = 120; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 0; + _qualityType.MinSize = 10; + _qualityType.MaxSize = 20; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_30_minute() { - movie.Runtime = 30; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 18457280000; - qualityType.MaxSize = null; + _movie.Runtime = 30; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 18457280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_60_minute() { - movie.Runtime = 60; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 36857280000; - qualityType.MaxSize = null; + _movie.Runtime = 60; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 36857280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_use_110_minutes_if_runtime_is_0() { - movie.Runtime = 0; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 1095.Megabytes(); + _movie.Runtime = 0; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 1095.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(true); - remoteMovie.Release.Size = 1105.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(true); + _remoteMovie.Release.Size = 1105.Megabytes(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(false); ExceptionVerification.ExpectedWarns(1); } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs index 970cd52da..38076fdc9 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs @@ -4,10 +4,10 @@ using FluentAssertions; using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.CustomFormat; using NzbDrone.Core.Test.Framework; @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class CustomFormatAllowedByProfileSpecificationFixture : CoreTest { - private RemoteMovie remoteMovie; + private RemoteMovie _remoteMovie; private CustomFormats.CustomFormat _format1; private CustomFormats.CustomFormat _format2; @@ -31,12 +31,11 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _format2 = new CustomFormats.CustomFormat("Cool Format"); _format2.Id = 2; - var fakeSeries = Builder.CreateNew() .With(c => c.Profile = (LazyLoaded)new Profile { Cutoff = Quality.Bluray1080p.Id }) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { Movie = fakeSeries, ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.DVD, new Revision(version: 2)) }, @@ -48,55 +47,55 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [Test] public void should_allow_if_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_deny_if_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_deny_if_one_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2, _format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2, _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_allow_if_all_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2, _format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2, _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_deny_if_no_format_was_parsed_and_none_not_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_allow_if_no_format_was_parsed_and_none_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(CustomFormats.CustomFormat.None.Name, _format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(CustomFormats.CustomFormat.None.Name, _format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs index 07b50b1b9..31dcc4b6c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs @@ -1,29 +1,27 @@ using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.CustomFormat; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class CutoffSpecificationFixture : CoreTest { - private CustomFormats.CustomFormat _customFormat; [SetUp] public void Setup() { - } private void GivenCustomFormatHigher() { - _customFormat = new CustomFormats.CustomFormat("My Format", "L_ENGLISH") {Id = 1}; + _customFormat = new CustomFormats.CustomFormat("My Format", "L_ENGLISH") { Id = 1 }; CustomFormatsFixture.GivenCustomFormats(_customFormat, CustomFormats.CustomFormat.None); } @@ -70,9 +68,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { GivenCustomFormatHigher(); var old = new QualityModel(Quality.HDTV720p); - old.CustomFormats = new List {CustomFormats.CustomFormat.None}; + old.CustomFormats = new List { CustomFormats.CustomFormat.None }; var newQ = new QualityModel(Quality.Bluray1080p); - newQ.CustomFormats = new List {_customFormat}; + newQ.CustomFormats = new List { _customFormat }; Subject.CutoffNotMet( new Profile { @@ -80,20 +78,22 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Items = Qualities.QualityFixture.GetDefaultQualities(), FormatCutoff = CustomFormats.CustomFormat.None.Id, FormatItems = CustomFormatsFixture.GetSampleFormatItems("None", "My Format") - }, old, newQ).Should().BeFalse(); + }, + old, + newQ).Should().BeFalse(); } [Test] public void should_return_true_if_cutoffs_are_met_but_is_a_revision_upgrade() { - Profile _profile = new Profile + Profile profile = new Profile { Cutoff = Quality.HDTV1080p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), }; Subject.CutoffNotMet( - _profile, + profile, new QualityModel(Quality.WEBDL1080p, new Revision(version: 1)), new QualityModel(Quality.WEBDL1080p, new Revision(version: 2))).Should().BeTrue(); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs index 0885d8a84..cd192ea14 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs @@ -4,13 +4,13 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -51,15 +51,15 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Reject("fail3")); _reports = new List { new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" } }; - _remoteEpisode = new RemoteMovie { + _remoteEpisode = new RemoteMovie + { Movie = new Movie(), ParsedMovieInfo = new ParsedMovieInfo() }; - _mappingResult = new MappingResult {Movie = new Movie(), MappingResultType = MappingResultType.Success}; + _mappingResult = new MappingResult { Movie = new Movie(), MappingResultType = MappingResultType.Success }; _mappingResult.RemoteMovie = _remoteEpisode; - Mocker.GetMock() .Setup(c => c.Map(It.IsAny(), It.IsAny(), It.IsAny())).Returns(_mappingResult); } @@ -184,9 +184,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _reports = new List { - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"} + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" } }; Subject.GetRssDecision(_reports); @@ -248,7 +248,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _reports = new List { - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, }; Subject.GetRssDecision(_reports).Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs index cfc1472eb..128e42b76 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs @@ -4,29 +4,30 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.History; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class HistorySpecificationFixture : CoreTest { + private const int FIRST_EPISODE_ID = 1; + private const int SECOND_EPISODE_ID = 2; + private HistorySpecification _upgradeHistory; private RemoteMovie _parseResultSingle; private QualityModel _upgradableQuality; private QualityModel _notupgradableQuality; private Movie _fakeMovie; - private const int FIRST_EPISODE_ID = 1; - private const int SECOND_EPISODE_ID = 2; [SetUp] public void Setup() @@ -85,13 +86,12 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _upgradeHistory.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } -// [Test] -// public void should_return_true_if_latest_history_has_a_download_id_and_cdh_is_enabled() -// { -// GivenMostRecentForEpisode(FIRST_EPISODE_ID, "test", _notupgradableQuality, DateTime.UtcNow, HistoryEventType.Grabbed); -// _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().BeTrue(); -// } - + // [Test] + // public void should_return_true_if_latest_history_has_a_download_id_and_cdh_is_enabled() + // { + // GivenMostRecentForEpisode(FIRST_EPISODE_ID, "test", _notupgradableQuality, DateTime.UtcNow, HistoryEventType.Grabbed); + // _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().BeTrue(); + // } [Test] public void should_return_true_if_latest_history_item_is_older_than_twelve_hours() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs index 0e98bd46c..919fb3ecf 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs @@ -3,11 +3,11 @@ using FluentAssertions; using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -24,26 +24,26 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { ParsedMovieInfo = new ParsedMovieInfo { - Languages = new List {Language.English} + Languages = new List { Language.English } }, Movie = new Movie - { - Profile = new LazyLoaded(new Profile - { - Language = Language.English - }) - } + { + Profile = new LazyLoaded(new Profile + { + Language = Language.English + }) + } }; } private void WithEnglishRelease() { - _remoteMovie.ParsedMovieInfo.Languages = new List {Language.English}; + _remoteMovie.ParsedMovieInfo.Languages = new List { Language.English }; } private void WithGermanRelease() { - _remoteMovie.ParsedMovieInfo.Languages = new List {Language.German}; + _remoteMovie.ParsedMovieInfo.Languages = new List { Language.German }; } [Test] diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs index 298984e65..869550f6b 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs @@ -4,8 +4,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -34,7 +34,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _firstEpisode = new Movie() { Monitored = true }; _secondEpisode = new Movie() { Monitored = true }; - var singleEpisodeList = new List { _firstEpisode }; var doubleEpisodeList = new List { _firstEpisode, _secondEpisode }; @@ -79,8 +78,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public void should_return_true_for_single_episode_search() { _fakeSeries.Monitored = false; - _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new MovieSearchCriteria {UserInvokedSearch = true}).Accepted.Should().BeTrue(); + _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new MovieSearchCriteria { UserInvokedSearch = true }).Accepted.Should().BeTrue(); } - } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs index 7826542d3..3cf32ce99 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs @@ -1,24 +1,25 @@ using System; using System.Collections.Generic; using System.Linq; -using Moq; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using NUnit.Framework; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; +using Moq; +using NUnit.Framework; using NzbDrone.Common.Extensions; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.CustomFormat; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] + //TODO: Update for custom qualities! public class PrioritizeDownloadDecisionFixture : CoreTest { @@ -30,8 +31,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { GivenPreferredDownloadProtocol(DownloadProtocol.Usenet); - _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH"){Id=1}; - _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH"){Id=2}; + _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH") { Id = 1 }; + _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH") { Id = 2 }; CustomFormatsFixture.GivenCustomFormats(CustomFormats.CustomFormat.None, _customFormat1, _customFormat2); } @@ -44,8 +45,12 @@ namespace NzbDrone.Core.Test.DecisionEngineTests remoteMovie.ParsedMovieInfo.Year = 1998; remoteMovie.ParsedMovieInfo.Quality = quality; - remoteMovie.Movie = Builder.CreateNew().With(m => m.Profile = new Profile { Items = Qualities.QualityFixture.GetDefaultQualities(), - PreferredTags = new List { "DTS-HD", "SPARKS"}, FormatItems = CustomFormatsFixture.GetSampleFormatItems() }) + remoteMovie.Movie = Builder.CreateNew().With(m => m.Profile = new Profile + { + Items = Qualities.QualityFixture.GetDefaultQualities(), + PreferredTags = new List { "DTS-HD", "SPARKS" }, + FormatItems = CustomFormatsFixture.GetSampleFormatItems() + }) .With(m => m.Title = "A Movie").Build(); remoteMovie.Release = new ReleaseInfo(); @@ -119,7 +124,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests var remoteEpisode1 = GivenRemoteMovie(new QualityModel(Quality.HDTV720p), age: 10); var remoteEpisode2 = GivenRemoteMovie(new QualityModel(Quality.HDTV720p), age: 5); - var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); decisions.Add(new DownloadDecision(remoteEpisode2)); @@ -185,7 +189,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisionsForMovies(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteMovie.Release).Seeders.Should().Be(torrentInfo2.Seeders); + ((TorrentInfo)qualifiedReports.First().RemoteMovie.Release).Seeders.Should().Be(torrentInfo2.Seeders); } [Test] @@ -201,7 +205,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests torrentInfo1.Seeders = 10; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Peers = 100; @@ -231,7 +234,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests torrentInfo1.Seeders = 0; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Seeders = 0; torrentInfo2.Peers = 100; @@ -277,7 +279,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisionsForMovies(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteMovie.Release).Should().Be(torrentInfo1); + ((TorrentInfo)qualifiedReports.First().RemoteMovie.Release).Should().Be(torrentInfo1); } [Test] diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs index f1ef0ddd9..ada976e0a 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs @@ -4,10 +4,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs index 980e7363f..ddaebf8de 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs @@ -3,10 +3,10 @@ using FluentAssertions; using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class QualityAllowedByProfileSpecificationFixture : CoreTest { - private RemoteMovie remoteMovie; + private RemoteMovie _remoteMovie; public static object[] AllowedTestCases = { @@ -38,29 +38,31 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .With(c => c.Profile = (LazyLoaded)new Profile { Cutoff = Quality.Bluray1080p.Id }) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { Movie = fakeSeries, ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.DVD, new Revision(version: 2)) }, }; } - [Test, TestCaseSource("AllowedTestCases")] + [Test] + [TestCaseSource("AllowedTestCases")] public void should_allow_if_quality_is_defined_in_profile(Quality qualityType) { - remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; - remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; + _remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } - [Test, TestCaseSource("DeniedTestCases")] + [Test] + [TestCaseSource("DeniedTestCases")] public void should_not_allow_if_quality_is_not_defined_in_profile(Quality qualityType) { - remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; - remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; + _remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs index f8d798593..907595566 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs @@ -1,9 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -26,7 +26,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [SetUp] public void Setup() { - } private void GivenAutoDownloadPropers(bool autoDownloadPropers) @@ -36,7 +35,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .Returns(autoDownloadPropers); } - [Test, TestCaseSource("IsUpgradeTestCases")] + [Test] + [TestCaseSource("IsUpgradeTestCases")] public void IsUpgradeTest(Quality current, int currentVersion, Quality newQuality, int newVersion, Quality cutoff, bool expected) { GivenAutoDownloadPropers(true); @@ -58,7 +58,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .Should().BeFalse(); } - [Test] public void should_return_false_if_release_and_existing_file_are_the_same() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs index 45b5af5c6..f0ab6b0f9 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs @@ -4,11 +4,11 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Queue; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -27,7 +27,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Mocker.Resolve(); _movie = Builder.CreateNew() - .With(e => e.Profile = new Profile { + .With(e => e.Profile = new Profile + { Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }) @@ -88,9 +89,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.SDTV) - }) + { + Quality = new QualityModel(Quality.SDTV) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -103,9 +104,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.DVD) - }) + { + Quality = new QualityModel(Quality.DVD) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -120,9 +121,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.HDTV720p) - }) + { + Quality = new QualityModel(Quality.HDTV720p) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -147,7 +148,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } - [Test] public void should_return_false_when_quality_is_better_and_upgrade_allowed_is_false_for_quality_profile() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs index b3f63dfde..41a6ddbeb 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs @@ -1,10 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Parser.Model; - -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,10 +19,10 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _remoteMovie = new RemoteMovie { Release = new ReleaseInfo - { - Title = "Movie.title.1998", - DownloadProtocol = DownloadProtocol.Torrent - } + { + Title = "Movie.title.1998", + DownloadProtocol = DownloadProtocol.Torrent + } }; } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs index 877c9932b..280c1dbbd 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs @@ -3,10 +3,10 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Restrictions; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,15 +20,15 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _remoteMovie = new RemoteMovie { - Movie = new Movie - { - Tags = new HashSet() - }, - Release = new ReleaseInfo - { - Title = "Dexter.S08E01.EDITED.WEBRip.x264-KYR" - } - }; + Movie = new Movie + { + Tags = new HashSet() + }, + Release = new ReleaseInfo + { + Title = "Dexter.S08E01.EDITED.WEBRip.x264-KYR" + } + }; Mocker.SetConstant(Mocker.Resolve()); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs index 75837fc94..0de0b35e6 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs @@ -1,12 +1,12 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs index b35e6cae3..e4f526595 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs @@ -11,12 +11,12 @@ using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -58,7 +58,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync //_remoteEpisode.Episodes = Builder.CreateListOfSize(1).Build().ToList(); //_remoteEpisode.Episodes.First().EpisodeFileId = 0; - Mocker.GetMock() .Setup(s => s.BestForTags(It.IsAny>())) .Returns(_delayProfile); @@ -76,7 +75,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync // { // Quality = quality // }); - _remoteEpisode.Movie.MovieFile = new LazyLoaded(new MovieFile { Quality = quality }); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs index 4a232435d..21e9a5aff 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs @@ -3,15 +3,14 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.DecisionEngine.Specifications; - using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs index ca44fe186..6c8a65634 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs @@ -3,8 +3,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.Search; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.Search diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs index 24172a9c7..979f7b538 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs @@ -6,8 +6,8 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.Search @@ -32,6 +32,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.Search IndexerId = 1, Title = "Series.Title.S01.720p.BluRay.X264-RlsGrp", Seeders = 0, + //IndexerSettings = new TorrentRssIndexerSettings {MinimumSeeders = 5} } }; @@ -64,7 +65,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.Search } // These tests are not needed anymore, since indexer settings are saved on the release itself! - [Test] public void should_return_true_if_indexer_not_specified() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs index 6dc1d5071..4882e69b0 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs @@ -4,10 +4,10 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests diff --git a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs index 9b739060b..36f15cc59 100644 --- a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs +++ b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs @@ -5,8 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.DiskSpace; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DiskSpace diff --git a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs index 1b49369cd..1e2a56bb7 100644 --- a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs @@ -11,10 +11,10 @@ using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download @@ -41,7 +41,6 @@ namespace NzbDrone.Core.Test.Download .With(c => c.RemoteMovie = remoteEpisode) .Build(); - Mocker.GetMock() .SetupGet(c => c.Definition) .Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" }); @@ -57,7 +56,6 @@ namespace NzbDrone.Core.Test.Download Mocker.GetMock() .Setup(s => s.GetMovie("Drone.1998")) .Returns(remoteEpisode.Movie); - } private RemoteMovie BuildRemoteMovie() @@ -68,7 +66,6 @@ namespace NzbDrone.Core.Test.Download }; } - private void GivenNoGrabbedHistory() { Mocker.GetMock() @@ -86,7 +83,6 @@ namespace NzbDrone.Core.Test.Download }); } - private void GivenABadlyNamedDownload() { _trackedDownload.DownloadItem.DownloadId = "1234"; @@ -152,7 +148,7 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_not_process_if_output_path_is_empty() { - _trackedDownload.DownloadItem.OutputPath = new OsPath(); + _trackedDownload.DownloadItem.OutputPath = default; Subject.Process(_trackedDownload); @@ -168,11 +164,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Subject.Process(_trackedDownload); @@ -189,11 +185,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}, new Rejection("Rejected!")), "Test Failure"), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1999.mkv"},new Rejection("Rejected!")), "Test Failure") + new LocalMovie { Path = @"C:\TestPath\Droned.1999.mkv" }, new Rejection("Rejected!")), "Test Failure") }); Subject.Process(_trackedDownload); @@ -213,11 +209,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}, new Rejection("Rejected!")), "Test Failure"), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"},new Rejection("Rejected!")), "Test Failure") + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure") }); _trackedDownload.RemoteMovie.Movie = null; @@ -234,11 +230,10 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure") }); - Subject.Process(_trackedDownload); AssertNoCompletedDownload(); @@ -253,8 +248,8 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})), - new ImportResult(new ImportDecision(new LocalMovie{Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })), + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure") }); Subject.Process(_trackedDownload); @@ -271,7 +266,7 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Mocker.GetMock() @@ -292,7 +287,7 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Mocker.GetMock() @@ -318,12 +313,11 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_mark_as_import_title_mismatch_if_ignore_warnings_is_true() { - Mocker.GetMock() .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Subject.Process(_trackedDownload, true); diff --git a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs index 49ff2f420..e0c5794b1 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs @@ -6,16 +6,16 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; +using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Download.Clients; namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { @@ -99,12 +99,10 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests public void should_not_download_if_any_movie_was_already_downloaded() { var remoteMovie1 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteMovie2 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); @@ -128,15 +126,9 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests [Test] public void should_return_all_downloaded_reports() { - var remoteMovie1 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p), - GetMovie(1) - ); + var remoteMovie1 = GetRemoteMovie(new QualityModel(Quality.HDTV720p), GetMovie(1)); - var remoteMovie2 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + var remoteMovie2 = GetRemoteMovie(new QualityModel(Quality.HDTV720p), GetMovie(2)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); @@ -150,18 +142,15 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { var remoteMovie1 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(1) - ); + GetMovie(1)); var remoteMovie2 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + GetMovie(2)); var remoteMovie3 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + GetMovie(2)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs index 071765976..28ecca4e1 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs @@ -1,4 +1,3 @@ - using System; using System.Collections.Generic; using System.IO; @@ -16,7 +15,6 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole { - [TestFixture] public class UsenetBlackholeFixture : DownloadClientFixtureBase { @@ -97,7 +95,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole VerifyPostprocessing(result); } - [Test] public void should_return_category() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs index 7ac27df8a..e4d86a18b 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Deluge; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests @@ -31,57 +31,57 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests }; _queued = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Queued, - Name = _title, - Size = 1000, - BytesDownloaded = 0, - Progress = 0.0, - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Queued, + Name = _title, + Size = 1000, + BytesDownloaded = 0, + Progress = 0.0, + DownloadPath = "somepath" + }; _downloading = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Downloading, - Name = _title, - Size = 1000, - BytesDownloaded = 100, - Progress = 10.0, - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Downloading, + Name = _title, + Size = 1000, + BytesDownloaded = 100, + Progress = 10.0, + DownloadPath = "somepath" + }; _failed = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Error, - Name = _title, - Size = 1000, - BytesDownloaded = 100, - Progress = 10.0, - Message = "Error", - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Error, + Name = _title, + Size = 1000, + BytesDownloaded = 100, + Progress = 10.0, + Message = "Error", + DownloadPath = "somepath" + }; _completed = new DelugeTorrent - { - Hash = "HASH", - IsFinished = true, - State = DelugeTorrentStatus.Paused, - Name = _title, - Size = 1000, - BytesDownloaded = 1000, - Progress = 100.0, - DownloadPath = "somepath", - IsAutoManaged = true, - StopAtRatio = true, - StopRatio = 1.0, - Ratio = 1.5 - }; + { + Hash = "HASH", + IsFinished = true, + State = DelugeTorrentStatus.Paused, + Name = _title, + Size = 1000, + BytesDownloaded = 1000, + Progress = 100.0, + DownloadPath = "somepath", + IsAutoManaged = true, + StopAtRatio = true, + StopRatio = 1.0, + Ratio = 1.5 + }; Mocker.GetMock() .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs index 5469d4a9f..cae124c9a 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs @@ -1,17 +1,17 @@ using System; +using FluentAssertions; using Moq; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Download; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Download; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Download.DownloadClientTests { @@ -30,7 +30,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests Mocker.GetMock() .Setup(s => s.Map(It.IsAny(), It.IsAny(), (SearchCriteriaBase)null)) - .Returns(() => new MappingResult{RemoteMovie = CreateRemoteMovie(), MappingResultType = MappingResultType.Success}); + .Returns(() => new MappingResult { RemoteMovie = CreateRemoteMovie(), MappingResultType = MappingResultType.Success }); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) @@ -67,6 +67,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests { VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Queued); @@ -77,6 +78,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Paused); @@ -87,6 +89,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Downloading); @@ -108,6 +111,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests downloadClientItem.Title.Should().NotBeNullOrEmpty(); downloadClientItem.RemainingSize.Should().Be(0); downloadClientItem.RemainingTime.Should().Be(TimeSpan.Zero); + //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Completed); } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs index cd9896d99..6197b1b83 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs @@ -67,13 +67,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, - { "size_uploaded", "0"}, + { "size_downloaded", "0" }, + { "size_uploaded", "0" }, { "speed_download", "0" } } } @@ -91,13 +91,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } }, } @@ -115,13 +115,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -139,13 +139,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, - { "size_uploaded", "10"}, + { "size_downloaded", "100" }, + { "size_uploaded", "10" }, { "speed_download", "50" } } } @@ -163,13 +163,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, - { "size_uploaded", "1"}, + { "size_downloaded", "10" }, + { "size_uploaded", "1" }, { "speed_download", "0" } } } @@ -187,13 +187,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -211,13 +211,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -235,13 +235,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -259,13 +259,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -587,7 +587,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests [TestCase(DownloadStationTaskStatus.Downloading, false, false)] [TestCase(DownloadStationTaskStatus.Finished, true, true)] - [TestCase(DownloadStationTaskStatus.Seeding, true, false)] + [TestCase(DownloadStationTaskStatus.Seeding, true, false)] [TestCase(DownloadStationTaskStatus.Waiting, false, false)] public void GetItems_should_return_canBeMoved_and_canBeDeleted_as_expected(DownloadStationTaskStatus apiStatus, bool canMoveFilesExpected, bool canBeRemovedExpected) { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs index 331914da9..79463f1cc 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs @@ -9,9 +9,9 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.DownloadStation; using NzbDrone.Core.Download.Clients.DownloadStation.Proxies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { @@ -64,12 +64,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, + { "size_downloaded", "0" }, { "speed_download", "0" } } } @@ -87,12 +87,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } }, } @@ -110,12 +110,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } } } @@ -133,12 +133,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, + { "size_downloaded", "100" }, { "speed_download", "50" } } } @@ -156,12 +156,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, + { "size_downloaded", "10" }, { "speed_download", "0" } } } @@ -231,7 +231,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests .Setup(s => s.Get(It.IsAny())) .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[1000])); */ - Mocker.GetMock() .Setup(s => s.AddTaskFromData(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnQueuedItem); @@ -246,7 +245,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests .Returns(tasks); } - protected static string CleanFileName(String name) + protected static string CleanFileName(string name) { return FileNameBuilder.CleanFileName(name) + ".nzb"; } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs index d9f87a880..daaf8aed8 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs @@ -1,14 +1,14 @@ -using Moq; +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Hadouken; using NzbDrone.Core.Download.Clients.Hadouken.Models; using NzbDrone.Core.MediaFiles.TorrentInfo; -using System; -using System.Collections.Generic; -using System.Linq; -using FluentAssertions; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests @@ -81,7 +81,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() @@ -210,7 +210,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests [Test] public void should_return_status_with_outputdirs() { - var configItems = new Dictionary(); + var configItems = new Dictionary(); configItems.Add("bittorrent.defaultSavePath", @"C:\Downloads\Downloading\deluge".AsOsAgnostic()); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs index 964c5978e..535bef92f 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs @@ -1,18 +1,18 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.Download; -using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Download.Clients.Nzbget; using NzbDrone.Core.Download.Clients.NzbVortex; using NzbDrone.Core.Download.Clients.NzbVortex.Responses; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests { @@ -28,42 +28,42 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbVortexSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "1234-ABCD", - TvCategory = "tv", - RecentMoviePriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "1234-ABCD", + TvCategory = "tv", + RecentMoviePriority = (int)NzbgetPriority.High + }; _queued = new NzbVortexQueueItem - { - Id = RandomNumber, - DownloadedSize = 1000, - TotalDownloadSize = 10, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE" - }; + { + Id = RandomNumber, + DownloadedSize = 1000, + TotalDownloadSize = 10, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE" + }; _failed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", - DestinationPath = "somedirectory", - State = NzbVortexStateType.UncompressFailed, - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", + DestinationPath = "somedirectory", + State = NzbVortexStateType.UncompressFailed, + }; _completed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", - DestinationPath = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", - State = NzbVortexStateType.Done - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", + DestinationPath = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", + State = NzbVortexStateType.Done + }; } protected void GivenFailedDownload() diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs index 7ee2b8cba..e7e2bc84c 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs @@ -1,15 +1,15 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { @@ -26,53 +26,53 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbgetSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MovieCategory = "movie", - RecentMoviePriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MovieCategory = "movie", + RecentMoviePriority = (int)NzbgetPriority.High + }; _queued = new NzbgetQueueItem - { - FileSizeLo = 1000, - RemainingSizeLo = 10, - Category = "movie", - NzbName = "Droned.1998.1080p.WEB-DL-DRONE", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } - }; + { + FileSizeLo = 1000, + RemainingSizeLo = 10, + Category = "movie", + NzbName = "Droned.1998.1080p.WEB-DL-DRONE", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } + }; _failed = new NzbgetHistoryItem - { - FileSizeLo = 1000, - Category = "movie", - Name = "Droned.1998.1080p.WEB-DL-DRONE", - DestDir = "somedirectory", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, - ParStatus = "Some Error", - UnpackStatus = "NONE", - MoveStatus = "NONE", - ScriptStatus = "NONE", - DeleteStatus = "NONE", - MarkStatus = "NONE" - }; + { + FileSizeLo = 1000, + Category = "movie", + Name = "Droned.1998.1080p.WEB-DL-DRONE", + DestDir = "somedirectory", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, + ParStatus = "Some Error", + UnpackStatus = "NONE", + MoveStatus = "NONE", + ScriptStatus = "NONE", + DeleteStatus = "NONE", + MarkStatus = "NONE" + }; _completed = new NzbgetHistoryItem - { - FileSizeLo = 1000, - Category = "movie", - Name = "Droned.1998.1080p.WEB-DL-DRONE", - DestDir = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, - ParStatus = "SUCCESS", - UnpackStatus = "NONE", - MoveStatus = "SUCCESS", - ScriptStatus = "NONE", - DeleteStatus = "NONE", - MarkStatus = "NONE" - }; + { + FileSizeLo = 1000, + Category = "movie", + Name = "Droned.1998.1080p.WEB-DL-DRONE", + DestDir = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, + ParStatus = "SUCCESS", + UnpackStatus = "NONE", + MoveStatus = "SUCCESS", + ScriptStatus = "NONE", + DeleteStatus = "NONE", + MarkStatus = "NONE" + }; Mocker.GetMock() .Setup(s => s.GetGlobalStatus(It.IsAny())) @@ -81,7 +81,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests DownloadRate = 7000000 }); - Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) .Returns("14.0"); @@ -321,7 +320,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { // TODO: We would love to have a way to distinguish between scripts reporting video corruption, or some internal script error. // That way we could return Warning instead of Failed to notify the user to take action. - _completed.ScriptStatus = "FAILURE"; GivenQueue(null); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs index 2775d03b9..7c819e8e6 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs @@ -58,7 +58,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests Mocker.GetMock().Verify(c => c.DownloadFile(_nzbUrl, _nzbPath), Times.Once()); } - [Test] public void should_throw_on_failed_download() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs index 13519da25..06f05b758 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs @@ -1,15 +1,15 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.QBittorrent; -using NzbDrone.Test.Common; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests { @@ -30,12 +30,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), new Byte[0])); + .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[0])); Mocker.GetMock() .Setup(s => s.GetConfig(It.IsAny())) @@ -53,7 +53,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.SeeOther)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.SeeOther)); } protected void GivenRedirectToTorrent() @@ -63,7 +63,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests Mocker.GetMock() .Setup(s => s.Get(It.Is(h => h.Url.FullUri == _downloadUrl))) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.Found)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.Found)); } protected void GivenFailedDownload() @@ -96,8 +96,8 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests protected void GivenHighPriority() { - Subject.Definition.Settings.As().OlderMoviePriority = (int) QBittorrentPriority.First; - Subject.Definition.Settings.As().RecentMoviePriority = (int) QBittorrentPriority.First; + Subject.Definition.Settings.As().OlderMoviePriority = (int)QBittorrentPriority.First; + Subject.Definition.Settings.As().RecentMoviePriority = (int)QBittorrentPriority.First; } protected void GivenGlobalSeedLimits(float maxRatio, int maxSeedingTime = -1, bool removeOnMaxRatio = false) @@ -117,7 +117,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests protected virtual void GivenTorrents(List torrents) { if (torrents == null) + { torrents = new List(); + } Mocker.GetMock() .Setup(s => s.GetTorrents(It.IsAny())) @@ -414,8 +416,10 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests protected virtual QBittorrentTorrent GivenCompletedTorrent( string state = "pausedUP", - float ratio = 0.1f, float ratioLimit = -2, - int seedingTime = 1, int seedingTimeLimit = -2) + float ratio = 0.1f, + float ratioLimit = -2, + int seedingTime = 1, + int seedingTimeLimit = -2) { var torrent = new QBittorrentTorrent { @@ -500,7 +504,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_seedingtime_reached_and_not_paused() { @@ -628,11 +631,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests // Let this stand as a lesson to never write temporary unit tests on your dev machine and claim it works. // Commit the tests and let it run with the official build on the official build agents. // (Also don't replace library versions in your build script) - var json = "{ \"eta\": 18446744073709335000 }"; var torrent = Newtonsoft.Json.JsonConvert.DeserializeObject(json); torrent.Eta.ToString().Should().Be("18446744073709335000"); - } [Test] diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs index 524614ded..af08fa8b8 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs @@ -1,11 +1,11 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.RTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests { @@ -61,7 +61,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests .Setup(s => s.AddTorrentFromFile(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnCompletedItem); - Mocker.GetMock() .Setup(s => s.HasHashTorrent(It.IsAny(), It.IsAny())) .Returns(true); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs index 1b9dc4bb6..0532dbff9 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs @@ -15,9 +15,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests.JsonConve [TestCase("0:1:59", 119)] [TestCase("0:59:59", 3599)] [TestCase("1:0:0", 3600)] - [TestCase("1:0:0:1", 24 * 3600 + 1)] - [TestCase("40:12:14", 40 * 3600 + 12 * 60 + 14)] - [TestCase("1:16:12:14", 40 * 3600 + 12 * 60 + 14)] + [TestCase("1:0:0:1", (24 * 3600) + 1)] + [TestCase("40:12:14", (40 * 3600) + (12 * 60) + 14)] + [TestCase("1:16:12:14", (40 * 3600) + (12 * 60) + 14)] public void valid_time_formats_should_be_parsed_correctly(string time, int expectedSeconds) { var thing = string.Format(QUERY, time); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs index 6dd6b50bf..120c2a217 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs @@ -1,16 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Sabnzbd; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Test.Common; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; using NzbDrone.Core.Validation; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests { @@ -28,20 +28,20 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new SabnzbdSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "5c770e3197e4fe763423ee7c392c25d1", - Username = "admin", - Password = "pass", - MovieCategory = "movie", - RecentMoviePriority = (int)SabnzbdPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "5c770e3197e4fe763423ee7c392c25d1", + Username = "admin", + Password = "pass", + MovieCategory = "movie", + RecentMoviePriority = (int)SabnzbdPriority.High + }; _queued = new SabnzbdQueue - { - DefaultRootFolder = @"Y:\nzbget\root".AsOsAgnostic(), - Paused = false, - Items = new List() + { + DefaultRootFolder = @"Y:\nzbget\root".AsOsAgnostic(), + Paused = false, + Items = new List() { new SabnzbdQueueItem { @@ -54,11 +54,11 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Title = "Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _failed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -69,11 +69,11 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Title = "Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _completed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -85,19 +85,19 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Storage = "/remote/mount/vv/Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _config = new SabnzbdConfig + { + Misc = new SabnzbdConfigMisc { - Misc = new SabnzbdConfigMisc - { - complete_dir = @"/remote/mount" - }, - Categories = new List + complete_dir = @"/remote/mount" + }, + Categories = new List { new SabnzbdCategory { Name = "movie", Dir = "vv" } } - }; + }; Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) @@ -108,9 +108,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests .Returns(_config); _fullStatus = new SabnzbdFullStatus - { - CompleteDir = @"Y:\sabnzbd\root\complete".AsOsAgnostic() - }; + { + CompleteDir = @"Y:\sabnzbd\root\complete".AsOsAgnostic() + }; Mocker.GetMock() .Setup(s => s.GetFullStatus(It.IsAny())) @@ -161,7 +161,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests protected virtual void GivenHistory(SabnzbdHistory history) { if (history == null) + { history = new SabnzbdHistory() { Items = new List() }; + } Mocker.GetMock() .Setup(s => s.GetHistory(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs index f16b050a9..ee2b3adba 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs @@ -284,7 +284,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests item.RemainingTime.Should().NotHaveValue(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_reached_and_not_stopped() { @@ -340,7 +339,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_idletime_reached_and_not_paused() { @@ -389,7 +387,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests public void should_not_be_removable_if_overridden_max_idletime_not_reached_and_paused() { GivenGlobalSeedLimits(null, 20); - PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40); + PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40); var item = Subject.GetItems().Single(); item.CanBeRemoved.Should().BeFalse(); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs index d6d4434c2..e2c55423b 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs @@ -110,7 +110,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests Mocker.GetMock() .Setup(v => v.GetConfig(It.IsAny())) .Returns(() => Json.Deserialize(_transmissionConfigItems.ToJson())); - } protected void GivenMovieCategory() @@ -184,7 +183,10 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests protected void PrepareClientToReturnCompletedItem(bool stopped = false, double ratio = 0.9, int seedingTime = 60, double? ratioLimit = null, int? idleLimit = null) { if (stopped) + { _completed.Status = TransmissionTorrentStatus.Stopped; + } + _completed.UploadedEver = (int)(_completed.DownloadedEver * ratio); _completed.SecondsSeeding = seedingTime * 60; @@ -214,7 +216,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests } } - GivenTorrents(new List { _completed diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs index 11551917c..d9b1ebfb3 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.UTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.UTorrentTests @@ -25,65 +25,65 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.UTorrentTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new UTorrentSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MovieCategory = "movie" - }; + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MovieCategory = "movie" + }; _queued = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 1000, - Progress = 0, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 1000, + Progress = 0, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _downloading = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _failed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Error, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Error, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _completed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 0, - Progress = 1.0, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 0, + Progress = 1.0, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; Mocker.GetMock() .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs index 88359757c..61c7ec51f 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs @@ -341,6 +341,5 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.VuzeTests items.Should().HaveCount(1); items.First().OutputPath.Should().Be(@"C:\Downloads\" + fileName); } - } } diff --git a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs index f6157b08b..adab7b46a 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs @@ -10,9 +10,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download { @@ -108,7 +108,8 @@ namespace NzbDrone.Core.Test.Download { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new WebException()); }); @@ -127,7 +128,8 @@ namespace NzbDrone.Core.Test.Download var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new TooManyRequestsException(request, response)); }); @@ -176,7 +178,8 @@ namespace NzbDrone.Core.Test.Download { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseUnavailableException(v.Release, "Error", new WebException()); }); diff --git a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs index 9524efa17..14487be50 100644 --- a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs @@ -8,9 +8,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download @@ -43,11 +43,9 @@ namespace NzbDrone.Core.Test.Download .With(c => c.RemoteMovie = remoteEpisode) .Build(); - Mocker.GetMock() .Setup(s => s.Find(_trackedDownload.DownloadItem.DownloadId, HistoryEventType.Grabbed)) .Returns(_grabHistory); - } private void GivenNoGrabbedHistory() @@ -130,7 +128,6 @@ namespace NzbDrone.Core.Test.Download _trackedDownload.State.Should().NotBe(TrackedDownloadStage.DownloadFailed); } - private void AssertDownloadFailed() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs index b0faa25c2..f2922753d 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using Marr.Data; using Moq; @@ -7,12 +8,11 @@ using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Linq; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,16 +34,16 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Build(); _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -84,7 +84,6 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.MovieId = _movie.Id) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs index 8ff0f0ea0..cb69aa502 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; @@ -7,7 +8,6 @@ using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FluentAssertions; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -18,9 +18,10 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { - new PendingRelease { Release = new ReleaseInfo { IndexerId = 1 } } - }); + .Returns(new List + { + new PendingRelease { Release = new ReleaseInfo { IndexerId = 1 } } + }); } [Test] diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs index e2e833929..0eee3f04a 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using Marr.Data; using Moq; @@ -7,12 +8,11 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Linq; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,16 +34,16 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Build(); _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -77,7 +77,6 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Setup(s => s.GetMovies(It.IsAny>())) .Returns(new List { _movie }); - Mocker.GetMock() .Setup(s => s.PrioritizeDecisionsForMovies(It.IsAny>())) .Returns((List d) => d); diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs index fb638f4de..b7a626fcd 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs @@ -5,10 +5,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Crypto; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -32,7 +32,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.All()) - .Returns( _pending); + .Returns(_pending); Mocker.GetMock() .Setup(s => s.GetMovie(It.IsAny())) @@ -50,11 +50,11 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests private void AddPending(int id, string title, int year) { _pending.Add(new PendingRelease - { - Id = id, - ParsedMovieInfo = new ParsedMovieInfo { MovieTitle = title, Year = year }, - MovieId = _movie.Id - }); + { + Id = id, + ParsedMovieInfo = new ParsedMovieInfo { MovieTitle = title, Year = year }, + MovieId = _movie.Id + }); } [Test] @@ -74,5 +74,4 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock().Verify(c => c.DeleteMany(It.Is>(s => s.SequenceEqual(ids)))); } } - } diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs index aecfec726..a0ee68987 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs @@ -9,12 +9,12 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,18 +34,17 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests _movie = Builder.CreateNew() .Build(); - _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -55,6 +54,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests _parsedMovieInfo.Quality = new QualityModel(Quality.HDTV720p); _remoteMovie = new RemoteMovie(); + //_remoteEpisode.Episodes = new List{ _episode }; _remoteMovie.Movie = _movie; _remoteMovie.ParsedMovieInfo = _parsedMovieInfo; @@ -89,7 +89,6 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.MovieId = _movie.Id) diff --git a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs index 19f2f99e2..857b7d826 100644 --- a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs @@ -5,11 +5,11 @@ using NUnit.Framework; using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.Download.TrackedDownloads { @@ -25,12 +25,14 @@ namespace NzbDrone.Core.Test.Download.TrackedDownloads { Mocker.GetMock() .Setup(s => s.FindByDownloadId(It.Is(sr => sr == "35238"))) - .Returns(new List(){ - new History.History(){ - DownloadId = "35238", - SourceTitle = "TV Series S01", - MovieId = 3, - } + .Returns(new List() + { + new History.History() + { + DownloadId = "35238", + SourceTitle = "TV Series S01", + MovieId = 3, + } }); } @@ -52,7 +54,7 @@ namespace NzbDrone.Core.Test.Download.TrackedDownloads Mocker.GetMock() .Setup(s => s.Map(It.Is(i => i.MovieTitle == "A Movie"), It.IsAny(), null)) - .Returns(new MappingResult{RemoteMovie = remoteEpisode}); + .Returns(new MappingResult { RemoteMovie = remoteEpisode }); ParseMovieTitle(); @@ -75,7 +77,5 @@ namespace NzbDrone.Core.Test.Download.TrackedDownloads trackedDownload.RemoteMovie.Movie.Should().NotBeNull(); trackedDownload.RemoteMovie.Movie.Id.Should().Be(3); } - - } } diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs index 0449def72..3935fe979 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs @@ -4,8 +4,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Roksbox; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Roksbox diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs index cd10a48d2..7662ec5a8 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs @@ -4,8 +4,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Wdtv; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Wdtv diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs index 6ea699dd0..f9b518191 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs @@ -5,8 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Xbmc; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Xbmc diff --git a/src/NzbDrone.Core.Test/FluentTest.cs b/src/NzbDrone.Core.Test/FluentTest.cs index f9116afcb..a17f142e3 100644 --- a/src/NzbDrone.Core.Test/FluentTest.cs +++ b/src/NzbDrone.Core.Test/FluentTest.cs @@ -87,11 +87,7 @@ namespace NzbDrone.Core.Test [Test] public void MaxOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MaxOrDefault(); + var result = new List().MaxOrDefault(); //Resolve result.Should().Be(0); @@ -100,10 +96,8 @@ namespace NzbDrone.Core.Test [Test] public void MaxOrDefault_should_return_max_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MaxOrDefault(); //Resolve @@ -113,10 +107,8 @@ namespace NzbDrone.Core.Test [Test] public void MaxOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MaxOrDefault(); //Resolve @@ -126,10 +118,8 @@ namespace NzbDrone.Core.Test [Test] public void Truncate_should_truncate_strings_to_max_specified_number_of_bytes() { - var str = ReadAllText("Files/LongOverview.txt"); - var resultString = str.Truncate(1000); //Resolve @@ -140,10 +130,8 @@ namespace NzbDrone.Core.Test [Test] public void Truncate_should_not_truncate_string_shorter_than_max_bytes() { - var str = "Hello World"; - var resultString = str.Truncate(1000); //Resolve @@ -154,11 +142,7 @@ namespace NzbDrone.Core.Test [Test] public void MinOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MinOrDefault(); + var result = new List().MinOrDefault(); //Resolve result.Should().Be(0); @@ -167,10 +151,8 @@ namespace NzbDrone.Core.Test [Test] public void MinOrDefault_should_return_min_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MinOrDefault(); //Resolve @@ -180,22 +162,19 @@ namespace NzbDrone.Core.Test [Test] public void MinOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MinOrDefault(); //Resolve result.Should().Be(0); } - - [TestCase(100,100,100)] - [TestCase(110,100,100)] - [TestCase(199,100,100)] - [TestCase(1000,100,1000)] - [TestCase(0,100,0)] + [TestCase(100, 100, 100)] + [TestCase(110, 100, 100)] + [TestCase(199, 100, 100)] + [TestCase(1000, 100, 1000)] + [TestCase(0, 100, 0)] public void round_to_level(long number, int level, int result) { number.Round(level).Should().Be(result); diff --git a/src/NzbDrone.Core.Test/Framework/CoreTest.cs b/src/NzbDrone.Core.Test/Framework/CoreTest.cs index c7caa959f..ab3cb795f 100644 --- a/src/NzbDrone.Core.Test/Framework/CoreTest.cs +++ b/src/NzbDrone.Core.Test/Framework/CoreTest.cs @@ -1,17 +1,17 @@ -using Moq; using System; +using Moq; using NUnit.Framework; using NzbDrone.Common.Cache; using NzbDrone.Common.Cloud; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; using NzbDrone.Common.Http.Dispatchers; -using NzbDrone.Common.TPL; -using NzbDrone.Test.Common; using NzbDrone.Common.Http.Proxy; -using NzbDrone.Core.Http; +using NzbDrone.Common.TPL; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Http; using NzbDrone.Core.Parser; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Framework { @@ -47,12 +47,14 @@ namespace NzbDrone.Core.Test.Framework { result.Quality = QualityParser.ParseQuality(title); } + return result; }); } } - public abstract class CoreTest : CoreTest where TSubject : class + public abstract class CoreTest : CoreTest + where TSubject : class { private TSubject _subject; @@ -73,7 +75,6 @@ namespace NzbDrone.Core.Test.Framework return _subject; } - } } } diff --git a/src/NzbDrone.Core.Test/Framework/DbTest.cs b/src/NzbDrone.Core.Test/Framework/DbTest.cs index b498950a2..f548c2c41 100644 --- a/src/NzbDrone.Core.Test/Framework/DbTest.cs +++ b/src/NzbDrone.Core.Test/Framework/DbTest.cs @@ -41,7 +41,6 @@ namespace NzbDrone.Core.Test.Framework return _subject; } - } } @@ -57,7 +56,9 @@ namespace NzbDrone.Core.Test.Framework get { if (_db == null) + { throw new InvalidOperationException("Test object database doesn't exists. Make sure you call WithRealDb() if you intend to use an actual database."); + } return _db; } @@ -78,6 +79,7 @@ namespace NzbDrone.Core.Test.Framework Mocker.SetConstant(mainDb); break; } + case MigrationType.Log: { var logDb = new LogDatabase(database); @@ -85,6 +87,7 @@ namespace NzbDrone.Core.Test.Framework Mocker.SetConstant(logDb); break; } + default: { throw new ArgumentException("Invalid MigrationType"); diff --git a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs index d05aed778..45f919245 100644 --- a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs +++ b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs @@ -11,7 +11,8 @@ namespace NzbDrone.Core.Test.Framework public interface IDirectDataMapper { List> Query(string sql); - List Query(string sql) where T : new(); + List Query(string sql) + where T : new(); } public class DirectDataMapper : IDirectDataMapper @@ -55,7 +56,8 @@ namespace NzbDrone.Core.Test.Framework return dataTable.Rows.Cast().Select(MapToDictionary).ToList(); } - public List Query(string sql) where T : new() + public List Query(string sql) + where T : new() { var dataTable = GetDataTable(sql); @@ -86,7 +88,8 @@ namespace NzbDrone.Core.Test.Framework return item; } - protected T MapToObject(DataRow dataRow) where T : new() + protected T MapToObject(DataRow dataRow) + where T : new() { var item = new T(); diff --git a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs index ba7433647..c751bbf55 100644 --- a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs +++ b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Test.Framework { [Category("DbMigrationTest")] [Category("DbTest")] - public abstract class MigrationTest : DbTest where TMigration : NzbDroneMigrationBase + public abstract class MigrationTest : DbTest + where TMigration : NzbDroneMigrationBase { protected long MigrationVersion { diff --git a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs index 97efa8c79..9394ba74b 100644 --- a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs +++ b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs @@ -7,20 +7,22 @@ namespace NzbDrone.Core.Test.Framework { public static class NBuilderExtensions { - public static T BuildNew(this ISingleObjectBuilder builder) where T : ModelBase, new() + public static T BuildNew(this ISingleObjectBuilder builder) + where T : ModelBase, new() { return builder.With(c => c.Id = 0).Build(); } - public static List BuildList(this IListBuilder builder) where T : ModelBase, new() + public static List BuildList(this IListBuilder builder) + where T : ModelBase, new() { return builder.Build().ToList(); } - public static List BuildListOfNew(this IListBuilder builder) where T : ModelBase, new() + public static List BuildListOfNew(this IListBuilder builder) + where T : ModelBase, new() { return BuildList(builder.All().With(c => c.Id = 0)); } - } } diff --git a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs index 30fb2be0c..4215a66c6 100644 --- a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs +++ b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs @@ -8,12 +8,18 @@ namespace NzbDrone.Core.Test.Framework { public interface ITestDatabase { - void InsertMany(IEnumerable items) where T : ModelBase, new(); - T Insert(T item) where T : ModelBase, new(); - List All() where T : ModelBase, new(); - T Single() where T : ModelBase, new(); - void Update(T childModel) where T : ModelBase, new(); - void Delete(T childModel) where T : ModelBase, new(); + void InsertMany(IEnumerable items) + where T : ModelBase, new(); + T Insert(T item) + where T : ModelBase, new(); + List All() + where T : ModelBase, new(); + T Single() + where T : ModelBase, new(); + void Update(T childModel) + where T : ModelBase, new(); + void Delete(T childModel) + where T : ModelBase, new(); IDirectDataMapper GetDirectDataMapper(); } @@ -28,32 +34,38 @@ namespace NzbDrone.Core.Test.Framework _dbConnection = dbConnection; } - public void InsertMany(IEnumerable items) where T : ModelBase, new() + public void InsertMany(IEnumerable items) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).InsertMany(items.ToList()); } - public T Insert(T item) where T : ModelBase, new() + public T Insert(T item) + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).Insert(item); } - public List All() where T : ModelBase, new() + public List All() + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).All().ToList(); } - public T Single() where T : ModelBase, new() + public T Single() + where T : ModelBase, new() { return All().SingleOrDefault(); } - public void Update(T childModel) where T : ModelBase, new() + public void Update(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Update(childModel); } - public void Delete(T childModel) where T : ModelBase, new() + public void Delete(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Delete(childModel); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs index 40a980074..7b791e91f 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs @@ -10,8 +10,8 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.HealthCheck.Checks @@ -30,7 +30,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .With(c => c.Path = "C:\\Movie\\".AsOsAgnostic()) .Build().ToList(); - _metadata = Builder.CreateListOfSize(1) .Build().ToList(); @@ -38,16 +37,13 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Setup(c => c.GetAllMovies()) .Returns(_movies); - Mocker.GetMock() .Setup(c => c.GetFilesByMovie(_movies.First().Id)) .Returns(_metadata); - Mocker.GetMock().SetupGet(c => c.CleanupMetadataImages).Returns(true); } - [Test] public void should_not_process_non_image_files() { @@ -57,7 +53,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Subject.Clean(); Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); - } [Test] @@ -70,8 +65,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); } - - [Test] public void should_not_run_if_flag_is_false() { @@ -85,7 +78,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks AssertImageWasNotRemoved(); } - [Test] public void should_set_clean_flag_to_false() { @@ -96,11 +88,9 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Mocker.GetMock().VerifySet(c => c.CleanupMetadataImages = false, Times.Once()); } - [Test] public void should_delete_html_images() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "image.jpg".AsOsAgnostic(); @@ -110,19 +100,15 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/html_image.jpg"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); - Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_delete_empty_images() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().Type = MetadataType.MovieImage; @@ -132,18 +118,15 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/emptyfile.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_not_delete_non_html_files() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "image.jpg".AsOsAgnostic(); @@ -152,7 +135,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/Queue.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); AssertImageWasNotRemoved(); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs index dd0fc09be..d2097304e 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks public void should_return_error_when_download_client_throws() { var downloadClient = Mocker.GetMock(); - downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition{Name = "Test"}); + downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition { Name = "Test" }); downloadClient.Setup(s => s.GetItems()) .Throws(); diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs index 3fb2a2a70..cffb07207 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs @@ -114,7 +114,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Subject.Check().ShouldBeWarning(); } - [Test] public void should_return_filter_warning_if_search_is_enabled_but_filtered() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs index 1d71d3a80..a77eecf13 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs @@ -39,19 +39,18 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks if (backoffHours != 0.0) { _blockedIndexers.Add(new IndexerStatus - { - ProviderId = id, - InitialFailure = DateTime.UtcNow.AddHours(-failureHours), - MostRecentFailure = DateTime.UtcNow.AddHours(-0.1), - EscalationLevel = 5, - DisabledTill = DateTime.UtcNow.AddHours(backoffHours) - }); + { + ProviderId = id, + InitialFailure = DateTime.UtcNow.AddHours(-failureHours), + MostRecentFailure = DateTime.UtcNow.AddHours(-0.1), + EscalationLevel = 5, + DisabledTill = DateTime.UtcNow.AddHours(backoffHours) + }); } return mockIndexer; } - [Test] public void should_not_return_error_when_no_indexers() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs index b95063928..e33402e41 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Returns(new Version(version)); } - [TestCase("5.18")] [TestCase("5.20")] public void should_return_ok(string version) diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs index bf1a06cf4..cd8f87211 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs @@ -5,8 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.HealthCheck.Checks; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HealthCheck.Checks { diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs index bd6a581d7..916b83a80 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs @@ -1,11 +1,11 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.History; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; -using System.Collections.Generic; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HistoryTests { @@ -33,7 +33,6 @@ namespace NzbDrone.Core.Test.HistoryTests StoredModel.Data.Should().HaveCount(2); } - [Test] public void should_get_download_history() { @@ -58,6 +57,5 @@ namespace NzbDrone.Core.Test.HistoryTests downloadHistory.Should().HaveCount(1); } - } } diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs index b8c58f5a6..83a0457fb 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs @@ -1,18 +1,18 @@ +using System.Collections.Generic; using System.IO; using FizzWare.NBuilder; +using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.History; using NzbDrone.Core.Qualities; -using System.Collections.Generic; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Qualities; -using FluentAssertions; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.HistoryTests { @@ -73,10 +73,10 @@ namespace NzbDrone.Core.Test.HistoryTests .Build(); var localMovie = new LocalMovie() - { - Movie = movie, - Path = @"C:\Test\Unsorted\Movie.2011.mkv" - }; + { + Movie = movie, + Path = @"C:\Test\Unsorted\Movie.2011.mkv" + }; Subject.Handle(new MovieImportedEvent(localMovie, movieFile, true, "sab", "abcd")); diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs index ba4ed976e..b9bd4d4be 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs @@ -1,13 +1,13 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Collections.Generic; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers public void should_delete_orphaned_blacklist_items() { var blacklist = Builder.CreateNew() - .With(h => h.MovieId = new int()) + .With(h => h.MovieId = default) .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) .BuildNew(); @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Db.Insert(movie); var blacklist = Builder.CreateNew() - .With(h => h.MovieId = new int()) + .With(h => h.MovieId = default) .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) .With(b => b.MovieId = movie.Id) diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs index d6bd721d7..cbffa879f 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs @@ -1,12 +1,12 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -30,7 +30,6 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers [Test] public void should_delete_orphaned_items() { - var history = Builder.CreateNew() .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs index fa5727ea7..8c1479c35 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs @@ -1,15 +1,15 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs index c92e12549..8728afc3d 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Languages; -using System.Collections.Generic; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -20,7 +20,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { var movieFile = Builder.CreateNew() .With(h => h.Quality = new QualityModel()) - .With(h => h.Languages = new List { Language.English}) + .With(h => h.Languages = new List { Language.English }) .BuildNew(); Db.Insert(movieFile); diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs index 503d7f6f2..5d05b7ae6 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs @@ -3,9 +3,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs index fa7401ef5..b69727d04 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tags; using NzbDrone.Core.Restrictions; +using NzbDrone.Core.Tags; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs index 7ba5dbf22..396bc9dcd 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs @@ -35,9 +35,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs index 694dcff7a..3034f4981 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs @@ -35,9 +35,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs index 2e7759397..067149904 100644 --- a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs @@ -1,9 +1,9 @@ -using NzbDrone.Core.Http; +using FluentAssertions; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using NzbDrone.Common.Http.Proxy; using NzbDrone.Common.Http; +using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs index 6273c7ef8..f92d8728a 100644 --- a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs +++ b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs @@ -1,8 +1,8 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Http; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs index edfa3ff16..82120f888 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs @@ -45,7 +45,6 @@ namespace NzbDrone.Core.Test.IndexerTests return new IndexerResponse(new IndexerRequest(httpRequest), httpResponse); } - [Test] public void should_handle_relative_url() { diff --git a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs index df81688fd..99c716cb8 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs @@ -64,8 +64,7 @@ namespace NzbDrone.Core.Test.IndexerTests.HDBitsTests Mocker.GetMock() .Setup(v => v.Execute(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), - Encoding.UTF8.GetBytes(responseJson))); + .Returns(r => new HttpResponse(r, new HttpHeader(), Encoding.UTF8.GetBytes(responseJson))); var torrents = Subject.FetchRecent(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs index 08204e6a7..cabc82040 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; @@ -5,9 +8,6 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.IPTorrents; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests { @@ -18,10 +18,10 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "http://fake.com/" } - }; + { + Name = "IPTorrents", + Settings = new IPTorrentsSettings() { BaseUrl = "http://fake.com/" } + }; } private void GivenOldFeedFormat() @@ -29,7 +29,7 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/torrents/rss?u=snip;tp=snip;3;80;93;37;download" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/torrents/rss?u=snip;tp=snip;3;80;93;37;download" } }; } @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37;download" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37;download" } }; } @@ -47,7 +47,7 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37" } }; } diff --git a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs index 7d4509d8f..4cc12f77b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.IndexerTests Mocker.SetConstant(repo); var existingIndexers = Builder.CreateNew().BuildNew(); - existingIndexers.ConfigContract = typeof (NewznabSettings).Name; + existingIndexers.ConfigContract = typeof(NewznabSettings).Name; repo.Insert(existingIndexers); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs index 39d382bbd..c79bb8df7 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs @@ -23,9 +23,9 @@ namespace NzbDrone.Core.Test.IndexerTests.IntegrationTests UseRealHttp(); _singleSearchCriteria = new MovieSearchCriteria() - { - SceneTitles = new List { "Person of Interest" }, - }; + { + SceneTitles = new List { "Person of Interest" }, + }; } private void ValidateTorrentResult(IList reports, bool hasSize = false, bool hasInfoUrl = false, bool hasMagnet = false) @@ -60,6 +60,5 @@ namespace NzbDrone.Core.Test.IndexerTests.IntegrationTests reports.Should().OnlyContain(c => c.Size > 0); } } - } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs index 64c0d1051..e31bfc35b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs @@ -19,15 +19,15 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests public void Setup() { Subject.Definition = new IndexerDefinition() + { + Id = 5, + Name = "Newznab", + Settings = new NewznabSettings() { - Id = 5, - Name = "Newznab", - Settings = new NewznabSettings() - { - BaseUrl = "http://indexer.local/", - Categories = new int[] { 1 } - } - }; + BaseUrl = "http://indexer.local/", + Categories = new int[] { 1 } + } + }; _caps = new NewznabCapabilities(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs index 379fa0ebc..49e26fe55 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs @@ -18,10 +18,10 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests { Subject.Settings = new NewznabSettings() { - BaseUrl = "http://127.0.0.1:1234/", - Categories = new [] { 1, 2 }, - AnimeCategories = new [] { 3, 4 }, - ApiKey = "abcd", + BaseUrl = "http://127.0.0.1:1234/", + Categories = new[] { 1, 2 }, + AnimeCategories = new[] { 3, 4 }, + ApiKey = "abcd", }; _movieSearchCriteria = new MovieSearchCriteria @@ -115,6 +115,5 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests page.Url.Query.Should().Contain("imdbid=0076759"); } - } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs index 547e84b67..51e2227d4 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests { public class NewznabSettingFixture : CoreTest { - [TestCase("http://nzbs.org")] [TestCase("http:///www.nzbplanet.net")] public void requires_apikey(string url) @@ -18,10 +17,8 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().Contain(c => c.PropertyName == "ApiKey"); - } [TestCase("")] @@ -35,14 +32,11 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().NotContain(c => c.PropertyName == "ApiKey"); setting.Validate().Errors.Should().Contain(c => c.PropertyName == "BaseUrl"); - } - [TestCase("http://nzbs2.org")] public void doesnt_requires_apikey(string url) { @@ -52,7 +46,6 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests BaseUrl = url }; - setting.Validate().IsValid.Should().BeTrue(); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs index ba670d632..0ca24bc75 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs @@ -18,10 +18,10 @@ namespace NzbDrone.Core.Test.IndexerTests.NyaaTests public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Nyaa", - Settings = new NyaaSettings() - }; + { + Name = "Nyaa", + Settings = new NyaaSettings() + }; } [Test] @@ -50,7 +50,7 @@ namespace NzbDrone.Core.Test.IndexerTests.NyaaTests torrentInfo.Size.Should().Be(2523293286); //2.35 GiB torrentInfo.InfoHash.Should().Be(null); torrentInfo.MagnetUrl.Should().Be(null); - torrentInfo.Peers.Should().Be(2+1); + torrentInfo.Peers.Should().Be(2 + 1); torrentInfo.Seeders.Should().Be(1); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs index 82cd7da3b..2e6ff1f83 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs @@ -17,14 +17,14 @@ namespace NzbDrone.Core.Test.IndexerTests.OmgwtfnzbsTests public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Omgwtfnzbs", + Settings = new OmgwtfnzbsSettings() { - Name = "Omgwtfnzbs", - Settings = new OmgwtfnzbsSettings() - { - ApiKey = "xxx", - Username = "me@my.domain" - } - }; + ApiKey = "xxx", + Username = "me@my.domain" + } + }; } [Test] diff --git a/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs index 2e3768a08..707f0f2a7 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs @@ -35,11 +35,11 @@ namespace NzbDrone.Core.Test.IndexerTests.PTPTests Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.POST))) - .Returns(r => new HttpResponse(r,new HttpHeader(), authStream.ToString())); + .Returns(r => new HttpResponse(r, new HttpHeader(), authStream.ToString())); Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) - .Returns(r => new HttpResponse(r, new HttpHeader {ContentType = HttpAccept.Json.Value}, responseJson)); + .Returns(r => new HttpResponse(r, new HttpHeader { ContentType = HttpAccept.Json.Value }, responseJson)); var torrents = Subject.FetchRecent(); @@ -53,6 +53,7 @@ namespace NzbDrone.Core.Test.IndexerTests.PTPTests first.DownloadProtocol.Should().Be(DownloadProtocol.Torrent); first.DownloadUrl.Should().Be("https://passthepopcorn.me/torrents.php?action=download&id=452135&authkey=00000000000000000000000000000000&torrent_pass=00000000000000000000000000000000"); first.InfoUrl.Should().Be("https://passthepopcorn.me/torrents.php?id=148131&torrentid=452135"); + //first.PublishDate.Should().Be(DateTime.Parse("2017-04-17T12:13:42+0000").ToUniversalTime()); stupid timezones first.Size.Should().Be(2466170624L); first.InfoHash.Should().BeNullOrEmpty(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs index 6de8fd38d..797aa9617 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs @@ -19,10 +19,10 @@ namespace NzbDrone.Core.Test.IndexerTests.RarbgTests public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Rarbg", - Settings = new RarbgSettings() - }; + { + Name = "Rarbg", + Settings = new RarbgSettings() + }; Mocker.GetMock() .Setup(v => v.GetToken(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs index a4c3a05d4..2b73b3b73 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Test.IndexerTests public TestIndexer(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public IIndexerRequestGenerator _requestGenerator; diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs index 7a0c2989e..110db4ec2 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using FluentValidation.Results; using NLog; +using NLog.Config; +using NLog.Targets; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Parser; -using NLog.Config; -using NLog.Targets; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { @@ -21,7 +21,7 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests public List TestPublic() { var result = new List(); - this.SetupNLog(); // Enable this to enable trace logging with nlog for debugging purposes + SetupNLog(); // Enable this to enable trace logging with nlog for debugging purposes Test(result); return result; } diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs index 3833184f3..23131d280 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs @@ -12,7 +12,6 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { - [TestFixture] public class TorrentRssIndexerFixture : CoreTest { @@ -219,7 +218,7 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests torrentInfo.CommentUrl.Should().Be("https://animetosho.org/view/fff-ore-monogatari-vol-01-bd-720p-aac.1009077"); torrentInfo.Indexer.Should().Be(Subject.Definition.Name); torrentInfo.PublishDate.Should().Be(DateTime.Parse("Tue, 02 Aug 2016 13:48:04 +0000").ToUniversalTime()); - torrentInfo.Size.Should().Be((long)Math.Round((double)1.366m * 1024L * 1024L * 1024L)); + torrentInfo.Size.Should().Be((long)Math.Round(1.366D * 1024L * 1024L * 1024L)); torrentInfo.InfoHash.Should().BeNull(); torrentInfo.MagnetUrl.Should().BeNull(); torrentInfo.Peers.Should().NotHaveValue(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs index 0ed86b3c1..e506c2978 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs @@ -1,11 +1,11 @@ -using Moq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Test.Framework; -using FluentAssertions; -using NzbDrone.Core.Indexers.Exceptions; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs index 6c82df89d..298023513 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs @@ -37,14 +37,14 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests var settings = Subject.Detect(_indexerSettings); settings.Should().BeEquivalentTo(new TorrentRssIndexerParserSettings - { - UseEZTVFormat = true, - UseEnclosureUrl = false, - UseEnclosureLength = false, - ParseSizeInDescription = false, - ParseSeedersInDescription = false, - SizeElementName = null - }); + { + UseEZTVFormat = true, + UseEnclosureUrl = false, + UseEnclosureLength = false, + ParseSizeInDescription = false, + ParseSeedersInDescription = false, + SizeElementName = null + }); } [Test] diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs index 72982a55b..d65c92660 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs @@ -21,14 +21,14 @@ namespace NzbDrone.Core.Test.IndexerTests.TorznabTests public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Torznab", + Settings = new TorznabSettings() { - Name = "Torznab", - Settings = new TorznabSettings() - { - BaseUrl = "http://indexer.local/", - Categories = new int[] { 1 } - } - }; + BaseUrl = "http://indexer.local/", + Categories = new int[] { 1 } + } + }; _caps = new NewznabCapabilities(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs b/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs index 6608bd42f..f9874e012 100644 --- a/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs +++ b/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.InstrumentationTests public class DatabaseTargetFixture : DbTest { private static string _uniqueMessage; - Logger _logger; + private Logger _logger; protected override MigrationType MigrationType => MigrationType.Log; @@ -64,7 +64,6 @@ namespace NzbDrone.Core.Test.InstrumentationTests VerifyLog(StoredModel, LogLevel.Info); } - [Test] [Explicit] [ManualTest] @@ -126,7 +125,6 @@ namespace NzbDrone.Core.Test.InstrumentationTests epFile.RelativePath.Should().BeNull(); } - [TearDown] public void Teardown() { @@ -136,7 +134,7 @@ namespace NzbDrone.Core.Test.InstrumentationTests private void VerifyLog(Log logItem, LogLevel level) { logItem.Time.Should().BeWithin(TimeSpan.FromSeconds(2)); - logItem.Logger.Should().Be(this.GetType().Name); + logItem.Logger.Should().Be(GetType().Name); logItem.Level.Should().Be(level.Name); _logger.Name.Should().EndWith(logItem.Logger); } diff --git a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs index df12a77b9..29e36acc2 100644 --- a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs +++ b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs @@ -1,7 +1,7 @@ using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Languages; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Languages { @@ -10,64 +10,66 @@ namespace NzbDrone.Core.Test.Languages { public static object[] FromIntCases = { - new object[] {1, Language.English}, - new object[] {2, Language.French}, - new object[] {3, Language.Spanish}, - new object[] {4, Language.German}, - new object[] {5, Language.Italian}, - new object[] {6, Language.Danish}, - new object[] {7, Language.Dutch}, - new object[] {8, Language.Japanese}, - new object[] {9, Language.Icelandic}, - new object[] {10, Language.Chinese}, - new object[] {11, Language.Russian}, - new object[] {12, Language.Polish}, - new object[] {13, Language.Vietnamese}, - new object[] {14, Language.Swedish}, - new object[] {15, Language.Norwegian}, - new object[] {16, Language.Finnish}, - new object[] {17, Language.Turkish}, - new object[] {18, Language.Portuguese}, - new object[] {19, Language.Flemish}, - new object[] {20, Language.Greek}, - new object[] {21, Language.Korean}, - new object[] {22, Language.Hungarian} + new object[] { 1, Language.English }, + new object[] { 2, Language.French }, + new object[] { 3, Language.Spanish }, + new object[] { 4, Language.German }, + new object[] { 5, Language.Italian }, + new object[] { 6, Language.Danish }, + new object[] { 7, Language.Dutch }, + new object[] { 8, Language.Japanese }, + new object[] { 9, Language.Icelandic }, + new object[] { 10, Language.Chinese }, + new object[] { 11, Language.Russian }, + new object[] { 12, Language.Polish }, + new object[] { 13, Language.Vietnamese }, + new object[] { 14, Language.Swedish }, + new object[] { 15, Language.Norwegian }, + new object[] { 16, Language.Finnish }, + new object[] { 17, Language.Turkish }, + new object[] { 18, Language.Portuguese }, + new object[] { 19, Language.Flemish }, + new object[] { 20, Language.Greek }, + new object[] { 21, Language.Korean }, + new object[] { 22, Language.Hungarian } }; public static object[] ToIntCases = { - new object[] {Language.English, 1}, - new object[] {Language.French, 2}, - new object[] {Language.Spanish, 3}, - new object[] {Language.German, 4}, - new object[] {Language.Italian, 5}, - new object[] {Language.Danish, 6}, - new object[] {Language.Dutch, 7}, - new object[] {Language.Japanese, 8}, - new object[] {Language.Icelandic, 9}, - new object[] {Language.Chinese, 10}, - new object[] {Language.Russian, 11}, - new object[] {Language.Polish, 12}, - new object[] {Language.Vietnamese, 13}, - new object[] {Language.Swedish, 14}, - new object[] {Language.Norwegian, 15}, - new object[] {Language.Finnish, 16}, - new object[] {Language.Turkish, 17}, - new object[] {Language.Portuguese, 18}, - new object[] {Language.Flemish, 19}, - new object[] {Language.Greek, 20}, - new object[] {Language.Korean, 21}, - new object[] {Language.Hungarian, 22} + new object[] { Language.English, 1 }, + new object[] { Language.French, 2 }, + new object[] { Language.Spanish, 3 }, + new object[] { Language.German, 4 }, + new object[] { Language.Italian, 5 }, + new object[] { Language.Danish, 6 }, + new object[] { Language.Dutch, 7 }, + new object[] { Language.Japanese, 8 }, + new object[] { Language.Icelandic, 9 }, + new object[] { Language.Chinese, 10 }, + new object[] { Language.Russian, 11 }, + new object[] { Language.Polish, 12 }, + new object[] { Language.Vietnamese, 13 }, + new object[] { Language.Swedish, 14 }, + new object[] { Language.Norwegian, 15 }, + new object[] { Language.Finnish, 16 }, + new object[] { Language.Turkish, 17 }, + new object[] { Language.Portuguese, 18 }, + new object[] { Language.Flemish, 19 }, + new object[] { Language.Greek, 20 }, + new object[] { Language.Korean, 21 }, + new object[] { Language.Hungarian, 22 } }; - [Test, TestCaseSource("FromIntCases")] + [Test] + [TestCaseSource("FromIntCases")] public void should_be_able_to_convert_int_to_languageTypes(int source, Language expected) { var language = (Language)source; language.Should().Be(expected); } - [Test, TestCaseSource("ToIntCases")] + [Test] + [TestCaseSource("ToIntCases")] public void should_be_able_to_convert_languageTypes_to_int(Language source, int expected) { var i = (int)source; diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs index 40b7e8d8a..ff34a9efe 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs @@ -20,21 +20,17 @@ namespace NzbDrone.Core.Test.MediaCoverTests _httpResponse = new HttpResponse(null, new HttpHeader(), "", HttpStatusCode.OK); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(100); Mocker.GetMock().Setup(c => c.Head(It.IsAny())).Returns(_httpResponse); - } - private void GivenFileExistsOnDisk() { Mocker.GetMock().Setup(c => c.FileExists(It.IsAny())).Returns(true); } - private void GivenExistingFileSize(long bytes) { GivenFileExistsOnDisk(); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(bytes); - } [Test] @@ -52,7 +48,6 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.AlreadyExists("http://url", "c:\\file.exe").Should().BeFalse(); } - [Test] public void should_return_true_if_file_exists_and_same_size_and_not_corrupt() { diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs index a09614d08..602c5448f 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs @@ -9,16 +9,16 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaCoverTests { [TestFixture] public class MediaCoverServiceFixture : CoreTest { - Movie _movie; + private Movie _movie; [SetUp] public void Setup() @@ -48,7 +48,7 @@ namespace NzbDrone.Core.Test.MediaCoverTests { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; Mocker.GetMock().Setup(c => c.FileGetLastWrite(It.IsAny())) @@ -59,7 +59,6 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg"); } @@ -68,13 +67,11 @@ namespace NzbDrone.Core.Test.MediaCoverTests { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; - Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg"); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs index eb93bfc29..795f5587e 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs @@ -7,8 +7,8 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs index 411246fec..943ce4f2f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs @@ -9,9 +9,9 @@ using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs index e09821b38..ae746b347 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs @@ -9,10 +9,10 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -28,8 +28,8 @@ namespace NzbDrone.Core.Test.MediaFiles public void Setup() { ParseMovieTitle(); - //UseRealParsingService(); + //UseRealParsingService(); Mocker.GetMock().Setup(c => c.GetVideoFiles(It.IsAny(), It.IsAny())) .Returns(_videoFiles); @@ -45,7 +45,6 @@ namespace NzbDrone.Core.Test.MediaFiles Mocker.GetMock() .Setup(s => s.Import(It.IsAny>(), true, null, ImportMode.Auto)) .Returns(new List()); - } private void GivenValidMovie() @@ -279,7 +278,6 @@ namespace NzbDrone.Core.Test.MediaFiles var imported = new List(); imported.Add(new ImportDecision(localMovie)); - Subject.ProcessPath(fileName); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs index b1367f334..19377d08f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs @@ -8,19 +8,20 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles { [TestFixture] + //TODO: Update all of this for movies. public class ImportApprovedMoviesFixture : CoreTest { @@ -44,8 +45,7 @@ namespace NzbDrone.Core.Test.MediaFiles _rejectedDecisions.Add(new ImportDecision(new LocalMovie(), new Rejection("Rejected!"))); _rejectedDecisions.Add(new ImportDecision(new LocalMovie(), new Rejection("Rejected!"))); - _approvedDecisions.Add(new ImportDecision - ( + _approvedDecisions.Add(new ImportDecision( new LocalMovie { Movie = movie, @@ -54,7 +54,6 @@ namespace NzbDrone.Core.Test.MediaFiles ReleaseGroup = "DRONE" })); - Mocker.GetMock() .Setup(s => s.UpgradeMovieFile(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new MovieFileMoveResult()); @@ -193,8 +192,8 @@ namespace NzbDrone.Core.Test.MediaFiles var fileDecision = _approvedDecisions.First(); fileDecision.LocalMovie.Size = 1.Gigabytes(); - var sampleDecision = new ImportDecision - (new LocalMovie + var sampleDecision = new ImportDecision( + new LocalMovie { Movie = fileDecision.LocalMovie.Movie, Path = @"C:\Test\TV\30 Rock\30 Rock - 2017 - Pilot.avi".AsOsAgnostic(), @@ -202,7 +201,6 @@ namespace NzbDrone.Core.Test.MediaFiles Size = 80.Megabytes() }); - var all = new List(); all.Add(fileDecision); all.Add(sampleDecision); @@ -217,7 +215,7 @@ namespace NzbDrone.Core.Test.MediaFiles [Test] public void should_copy_when_cannot_move_files_downloads() { - Subject.Import(new List { _approvedDecisions.First() }, true, new DownloadClientItem { Title = "30.Rock.S01E01", CanMoveFiles = false}); + Subject.Import(new List { _approvedDecisions.First() }, true, new DownloadClientItem { Title = "30.Rock.S01E01", CanMoveFiles = false }); Mocker.GetMock() .Verify(v => v.UpgradeMovieFile(It.IsAny(), _approvedDecisions.First().LocalMovie, true), Times.Once()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs index 85b57989f..db8430559 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; @@ -5,7 +6,6 @@ using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.MediaFiles { @@ -29,14 +29,12 @@ namespace NzbDrone.Core.Test.MediaFiles .With(s => s.MovieId = 12) .BuildListOfNew(); - Db.InsertMany(files); var movieFiles = Subject.GetFilesByMovie(12); movieFiles.Should().HaveCount(4); movieFiles.Should().OnlyContain(c => c.MovieId == 12); - } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs index e6e50a81f..2f8fc3ab8 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs @@ -5,8 +5,8 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests @@ -20,10 +20,10 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests public void Setup() { _series = new Movie - { - Id = 10, - Path = @"C:\".AsOsAgnostic() - }; + { + Id = 10, + Path = @"C:\".AsOsAgnostic() + }; } [Test] @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List()); - Subject.FilterExistingFiles(files, _series).Should().BeEquivalentTo(files); } @@ -58,7 +57,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(files.Select(f => new MovieFile { RelativePath = Path.GetFileName(f) }).ToList()); - Subject.FilterExistingFiles(files, _series).Should().BeEmpty(); } @@ -76,10 +74,9 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -100,10 +97,9 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -124,7 +120,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); Subject.FilterExistingFiles(files, _series).Should().HaveCount(3); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs index 8800b123f..71a399de7 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -27,7 +27,6 @@ namespace NzbDrone.Core.Test.MediaFiles Mocker.GetMock() .Setup(e => e.FileExists(It.Is(c => !c.Contains(DELETED_PATH)))) .Returns(true); - } private void GivenMovieFiles(IEnumerable movieFiles) diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs index cc9e06864..68c203107 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs @@ -150,11 +150,11 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo.MediaInfoFormatterTests public void should_use_AudioChannelPositionText_when_AudioChannelChannelPosition_is_invalid() { var mediaInfoModel = new MediaInfoModel - { + { AudioChannels = 6, AudioChannelPositions = "15 objects", AudioChannelPositionsText = "15 objects / Front: L C R, Side: L R, LFE", - SchemaRevision = 3 + SchemaRevision = 3 }; MediaInfoFormatter.FormatAudioChannels(mediaInfoModel).Should().Be(5.1m); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs index 32e012b19..d6b083350 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs @@ -4,13 +4,13 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { @@ -23,10 +23,10 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo public void Setup() { _movie = new Movie - { - Id = 1, - Path = @"C:\movie".AsOsAgnostic() - }; + { + Id = 1, + Path = @"C:\movie".AsOsAgnostic() + }; Mocker.GetMock() .SetupGet(s => s.EnableMediaInfo) @@ -240,7 +240,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -260,7 +260,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -276,7 +276,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs index c4642733e..5884c73df 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs @@ -62,7 +62,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaInfo info.VideoColourPrimaries.Should().Be("BT.601 NTSC"); info.VideoTransferCharacteristics.Should().Be("BT.709"); info.AudioAdditionalFeatures.Should().BeOneOf("", "LC"); - } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs index 11c76a3af..63b5dc810 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs @@ -7,10 +7,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieFileMovingServiceTests diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs index 2ca155734..ca14001c4 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; @@ -5,7 +6,6 @@ using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Aggregation.Aggregators { @@ -57,7 +57,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Aggregation.Aggregators _localMovie.FileMovieInfo = GetParsedMovieInfo(Language.English); Subject.Aggregate(_localMovie, false).Languages.Should().Contain(_localMovie.DownloadClientMovieInfo.Languages); - } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs index f4e358ab0..c52ebf676 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs @@ -1,11 +1,11 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality { diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs index 7eb1c481c..8a34f95a7 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs @@ -3,12 +3,12 @@ using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport @@ -26,7 +26,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport .With(s => s.Runtime = 30) .Build(); - _localMovie = new LocalMovie { Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs index 13090bd13..d4b9abb49 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs @@ -1,25 +1,26 @@ using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using NzbDrone.Core.Download; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; namespace NzbDrone.Core.Test.MediaFiles.MovieImport { [TestFixture] + //TODO: Add tests to ensure helpers for augmenters are correctly passed. public class ImportDecisionMakerFixture : CoreTest { @@ -201,7 +202,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport .Setup(c => c.ParseMinimalPathMovieInfo(It.IsAny())) .Returns(null); - var folderInfo = new ParsedMovieInfo {SimpleReleaseTitle = "A Movie Folder 2018", Quality = _quality}; + var folderInfo = new ParsedMovieInfo { SimpleReleaseTitle = "A Movie Folder 2018", Quality = _quality }; var result = Subject.GetImportDecisions(_videoFiles, _movie, null, folderInfo, true); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs index e601a7e3a..2cc5da258 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs @@ -6,9 +6,9 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications @@ -23,17 +23,17 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications [SetUp] public void Setup() { - _rootFolder = @"C:\Test\TV".AsOsAgnostic(); + _rootFolder = @"C:\Test\TV".AsOsAgnostic(); _movie = Builder.CreateNew() .With(s => s.Path = Path.Combine(_rootFolder, "30 Rock")) .Build(); _localMovie = new LocalMovie() - { - Path = @"C:\Test\Unsorted\30 Rock\30.rock.s01e01.avi".AsOsAgnostic(), - Movie = _movie - }; + { + Path = @"C:\Test\Unsorted\30 Rock\30.rock.s01e01.avi".AsOsAgnostic(), + Movie = _movie + }; } private void GivenFileSize(long size) @@ -61,7 +61,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications [Test] public void should_reject_when_there_isnt_enough_space_for_file_plus_min_free_space() { - Mocker.GetMock() .Setup(s => s.MinimumFreeSpaceWhenImporting) .Returns(100); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs index 123bcf7f6..f001806cb 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs @@ -63,6 +63,5 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications _localMovie.Path = @"C:\Test\Unsorted\Series.Title.S01E01.720p.HDTV-Sonarr\S01E05.mkv".AsOsAgnostic(); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeFalse(); }*/ - } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs index bcb9faf30..112d837df 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs @@ -2,9 +2,9 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { @@ -21,10 +21,10 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications .Build(); _localEpisode = new LocalMovie - { - Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", - Movie = _movie, - }; + { + Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", + Movie = _movie, + }; } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs index f7fca70a4..1b482582b 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs @@ -6,9 +6,9 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs index c7b483beb..8f63ff25c 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs @@ -4,9 +4,9 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs index 3c889d091..36d8e5970 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs @@ -4,11 +4,11 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { @@ -26,11 +26,11 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications .Build(); _localMovie = new LocalMovie() - { - Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", - Quality = new QualityModel(Quality.HDTV720p, new Revision(version: 1)), - Movie = _movie - }; + { + Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", + Quality = new QualityModel(Quality.HDTV720p, new Revision(version: 1)), + Movie = _movie + }; } [Test] @@ -45,20 +45,16 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications [Test] public void should_return_true_if_upgrade_for_existing_episodeFile() { - _localMovie.Movie.MovieFileId = 1; _localMovie.Movie.MovieFile = new LazyLoaded( new MovieFile { Quality = new QualityModel(Quality.SDTV, new Revision(version: 1)) - } - ); - + }); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeTrue(); } - [Test] public void should_return_false_if_not_an_upgrade_for_existing_episodeFile() { @@ -67,8 +63,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications new MovieFile { Quality = new QualityModel(Quality.Bluray720p, new Revision(version: 1)) - } - ); + }); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeFalse(); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs index b08954388..1b8b13382 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles { @@ -59,7 +59,7 @@ namespace NzbDrone.Core.Test.MediaFiles { GivenNoMovieFiles(); - Subject.Execute(new RenameFilesCommand(_movie.Id, new List{1})); + Subject.Execute(new RenameFilesCommand(_movie.Id, new List { 1 })); Mocker.GetMock() .Verify(v => v.PublishEvent(It.IsAny()), Times.Never()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs index 866e813e9..6c6902066 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs @@ -35,7 +35,7 @@ namespace NzbDrone.Core.Test.MediaFiles _newQuality = _oldQuality.JsonClone(); var format = new CustomFormats.CustomFormat("Awesome Format"); format.Id = 1; - _newQuality.CustomFormats = new List{format}; + _newQuality.CustomFormats = new List { format }; _newInfo = new ParsedMovieInfo { @@ -43,7 +43,7 @@ namespace NzbDrone.Core.Test.MediaFiles }; Mocker.GetMock().Setup(s => s.GetMovies(It.IsAny>())) - .Returns(new List{_movieFile}); + .Returns(new List { _movieFile }); Mocker.GetMock().Setup(s => s.GetByMovieId(It.IsAny(), null)) .Returns(new List()); @@ -51,7 +51,7 @@ namespace NzbDrone.Core.Test.MediaFiles private void ExecuteCommand() { - Subject.Execute(new UpdateMovieFileQualityCommand(new List{0})); + Subject.Execute(new UpdateMovieFileQualityCommand(new List { 0 })); } [Test] @@ -83,7 +83,7 @@ namespace NzbDrone.Core.Test.MediaFiles .With(h => h.SourceTitle = "My Movie 2018.mkv").Build(); Mocker.GetMock().Setup(s => s.GetByMovieId(It.IsAny(), null)) - .Returns(new List {imported}); + .Returns(new List { imported }); Mocker.GetMock().Setup(s => s.ParseMovieInfo("My Movie 2018.mkv", It.IsAny>())) .Returns(_newInfo); diff --git a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs index ce7e9fc34..f990dc488 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs @@ -4,9 +4,9 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -21,15 +21,14 @@ namespace NzbDrone.Core.Test.MediaFiles { _localMovie = new LocalMovie(); _localMovie.Movie = new Movie - { - Path = @"C:\Test\TV\Series".AsOsAgnostic() - }; + { + Path = @"C:\Test\TV\Series".AsOsAgnostic() + }; _movieFile = Builder .CreateNew() .Build(); - Mocker.GetMock() .Setup(c => c.FileExists(It.IsAny())) .Returns(true); @@ -56,8 +55,6 @@ namespace NzbDrone.Core.Test.MediaFiles Mocker.GetMock().Verify(v => v.DeleteFile(It.IsAny(), It.IsAny()), Times.Once()); } - - [Test] public void should_delete_episode_file_from_database() { diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs index 72d7a2431..c27c060e6 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.Messaging.Commands [Test] public void should_return_true_when_single_property_matches() { - var command1 = new MoviesSearchCommand { MovieIds = new List{ 1 } }; + var command1 = new MoviesSearchCommand { MovieIds = new List { 1 } }; var command2 = new MoviesSearchCommand { MovieIds = new List { 1 } }; CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs index 20c209eda..7e22f6f85 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs @@ -210,13 +210,10 @@ namespace NzbDrone.Core.Test.Messaging.Commands public class CommandB : Command { - public CommandB() { - } public override string CompletionMessage => null; } - } diff --git a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs index 76561592b..6a716f08c 100644 --- a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs @@ -12,33 +12,27 @@ namespace NzbDrone.Core.Test.Messaging.Events [TestFixture] public class EventAggregatorFixture : TestBase { - private Mock> HandlerA1; - private Mock> HandlerA2; - - private Mock> HandlerB1; - private Mock> HandlerB2; - - private Mock> AsyncHandlerA1; + private Mock> _handlerA1; + private Mock> _handlerA2; + private Mock> _handlerB1; + private Mock> _handlerB2; [SetUp] public void Setup() { - HandlerA1 = new Mock>(); - HandlerA2 = new Mock>(); - HandlerB1 = new Mock>(); - HandlerB2 = new Mock>(); - - AsyncHandlerA1 = new Mock>(); + _handlerA1 = new Mock>(); + _handlerA2 = new Mock>(); + _handlerB1 = new Mock>(); + _handlerB2 = new Mock>(); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerA1.Object, HandlerA2.Object }); + .Returns(new List> { _handlerA1.Object, _handlerA2.Object }); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerB1.Object, HandlerB2.Object }); - + .Returns(new List> { _handlerB1.Object, _handlerB2.Object }); } [Test] @@ -48,8 +42,8 @@ namespace NzbDrone.Core.Test.Messaging.Events Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); } [Test] @@ -57,88 +51,37 @@ namespace NzbDrone.Core.Test.Messaging.Events { var eventA = new EventA(); - Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); - HandlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); - HandlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); } - [Test] public void broken_handler_should_not_effect_others_handler() { var eventA = new EventA(); - - HandlerA1.Setup(c => c.Handle(It.IsAny())) + _handlerA1.Setup(c => c.Handle(It.IsAny())) .Throws(new NotImplementedException()); Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); ExceptionVerification.ExpectedErrors(1); } - - - /* [Test] - public void should_queue_multiple_async_events() - { - var eventA = new EventA(); - - - - var handlers = new List> - { - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - }; - - Mocker.GetMock() - .Setup(c => c.BuildAll>()) - .Returns(new List>()); - - Mocker.GetMock() - .Setup(c => c.BuildAll>()) - .Returns(handlers); - - var counter = new ConcurrencyCounter(handlers.Count); - - - AsyncHandlerA1.Setup(c => c.HandleAsync(It.IsAny())) - .Callback(c => - { - var id = counter.Start(); - Thread.Sleep(1000); - counter.Stop(id); - }); - - Subject.PublishEvent(eventA); - - counter.WaitForAllItems(); - - counter.MaxThreads.Should().Be(3); - }*/ } - public class EventA : IEvent { - } public class EventB : IEvent { - } } diff --git a/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs index 26a81f531..568470eb9 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs @@ -3,8 +3,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MetadataSource { diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs index 1b2b9acd1..f7306cabe 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs @@ -1,8 +1,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MetadataSource.SkyHook; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.Categories; namespace NzbDrone.Core.Test.MetadataSource.SkyHook @@ -42,6 +42,7 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook movie.Studio.Should().NotBeNullOrWhiteSpace(); movie.Runtime.Should().BeGreaterThan(0); movie.TitleSlug.Should().NotBeNullOrWhiteSpace(); + //series.TvRageId.Should().BeGreaterThan(0); movie.TmdbId.Should().BeGreaterThan(0); } diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs index 24e3fc050..4ae0b066d 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs @@ -18,6 +18,7 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook } [TestCase("Prometheus", "Prometheus")] + // TODO: TMDB Doesn't like when we clean periods from this // [TestCase("The Man from U.N.C.L.E.", "The Man from U.N.C.L.E.")] [TestCase("imdb:tt2527336", "Star Wars: The Last Jedi")] diff --git a/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs index bd2b49fcb..a09a4dbb2 100644 --- a/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs @@ -39,10 +39,10 @@ namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests [Test] public void should_update_insert_remove_titles() { - var titles = new List {_title2, _title3}; - var updates = new List {_title2}; - var deletes = new List {_title1}; - var inserts = new List {_title3}; + var titles = new List { _title2, _title3 }; + var updates = new List { _title2 }; + var deletes = new List { _title1 }; + var inserts = new List { _title3 }; GivenExistingTitles(_title1, _title2); Subject.UpdateTitles(titles, _movie); @@ -56,8 +56,8 @@ namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests public void should_not_insert_duplicates() { GivenExistingTitles(); - var titles = new List {_title1, _title1}; - var inserts = new List{ _title1 }; + var titles = new List { _title1, _title1 }; + var inserts = new List { _title1 }; Subject.UpdateTitles(titles, _movie); @@ -68,7 +68,7 @@ namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests public void should_not_insert_main_title() { GivenExistingTitles(); - var titles = new List{_title1}; + var titles = new List { _title1 }; var movie = Builder.CreateNew().With(m => m.CleanTitle = _title1.CleanTitle).Build(); Subject.UpdateTitles(titles, movie); @@ -80,7 +80,7 @@ namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests public void should_update_movie_id() { GivenExistingTitles(); - var titles = new List {_title1, _title2}; + var titles = new List { _title1, _title2 }; Subject.UpdateTitles(titles, _movie); @@ -96,7 +96,7 @@ namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests var updateTitle = existingTitle.JsonClone(); updateTitle.Id = 0; - Subject.UpdateTitles(new List {updateTitle}, _movie); + Subject.UpdateTitles(new List { updateTitle }, _movie); Mocker.GetMock().Verify(r => r.UpdateMany(It.Is>(list => list.First().Id == existingTitle.Id)), Times.Once()); } diff --git a/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs index 573126b7b..d658d9858 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs @@ -5,10 +5,10 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MovieTests @@ -121,7 +121,6 @@ namespace NzbDrone.Core.Test.MovieTests .Setup(s => s.FolderExists(It.IsAny())) .Returns(false); - Subject.Execute(_command); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs index b93735053..0f0e6a6cc 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs @@ -1,10 +1,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MovieTests.MovieRepositoryTests { @@ -21,14 +21,13 @@ namespace NzbDrone.Core.Test.MovieTests.MovieRepositoryTests public void should_lazyload_quality_profile() { var profile = new Profile - { - Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), - FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), - FormatCutoff = CustomFormats.CustomFormat.None.Id, - Cutoff = Quality.Bluray1080p.Id, - Name = "TestProfile" - }; - + { + Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), + FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), + FormatCutoff = CustomFormats.CustomFormat.None.Id, + Cutoff = Quality.Bluray1080p.Id, + Name = "TestProfile" + }; Mocker.Resolve().Insert(profile); @@ -37,7 +36,6 @@ namespace NzbDrone.Core.Test.MovieTests.MovieRepositoryTests Subject.Insert(movie); - StoredModel.Profile.Should().NotBeNull(); } } diff --git a/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs index a317561e5..4a01f5f78 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs @@ -1,8 +1,8 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MovieTests.MovieServiceTests @@ -10,29 +10,27 @@ namespace NzbDrone.Core.Test.MovieTests.MovieServiceTests [TestFixture] public class AddMovieFixture : CoreTest { - private Movie fakeMovie; + private Movie _fakeMovie; [SetUp] public void Setup() { - fakeMovie = Builder.CreateNew().Build(); + _fakeMovie = Builder.CreateNew().Build(); } [Test] public void movie_added_event_should_have_proper_path() { - fakeMovie.Path = null; - fakeMovie.RootFolderPath = @"C:\Test\Movies"; + _fakeMovie.Path = null; + _fakeMovie.RootFolderPath = @"C:\Test\Movies"; Mocker.GetMock() - .Setup(s => s.GetMovieFolder(fakeMovie, null)) - .Returns(fakeMovie.Title); + .Setup(s => s.GetMovieFolder(_fakeMovie, null)) + .Returns(_fakeMovie.Title); - var series = Subject.AddMovie(fakeMovie); + var series = Subject.AddMovie(_fakeMovie); series.Path.Should().NotBeNull(); - } - } } diff --git a/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs index 39a148eaf..c5cc267e8 100644 --- a/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs @@ -4,10 +4,10 @@ using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MovieTests diff --git a/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs b/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs index 8aea02a52..25b3811dd 100644 --- a/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Core.Test.NetImport.CouchPotato return new NetImportResponse(new NetImportRequest(httpRequest), httpResponse); } - [Test] public void should_parse_json_of_couchpotato() { diff --git a/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs b/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs index e46fde60e..286805f2f 100644 --- a/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs @@ -11,12 +11,12 @@ namespace NzbDrone.Core.Test.NetImport [TestFixture] public class RSSImportFixture : CoreTest { - [SetUp] public void Setup() { Subject.Definition = Subject.DefaultDefinitions.First(); } + private void GivenRecentFeedResponse(string rssXmlFile) { var recentFeed = ReadAllText(@"Files/" + rssXmlFile); diff --git a/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs b/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs index b9ff6f455..face0effd 100644 --- a/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Core.Test.NetImport return new NetImportResponse(new NetImportRequest(httpRequest), httpResponse); } - [Test] public void should_parse_xml_of_imdb() { diff --git a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs index b754eae20..f61b2350b 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using FluentValidation.Results; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; using NzbDrone.Core.Validation; using NzbDrone.Test.Common; @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Test.NotificationTests [TestFixture] public class NotificationBaseFixture : TestBase { - class TestSetting : IProviderConfig + private class TestSetting : IProviderConfig { public NzbDroneValidationResult Validate() { @@ -21,12 +21,11 @@ namespace NzbDrone.Core.Test.NotificationTests } } - class TestNotificationWithOnDownload : NotificationBase + private class TestNotificationWithOnDownload : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -36,15 +35,13 @@ namespace NzbDrone.Core.Test.NotificationTests { TestLogger.Info("OnDownload was called"); } - } - class TestNotificationWithAllEvents : NotificationBase + private class TestNotificationWithAllEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -69,21 +66,17 @@ namespace NzbDrone.Core.Test.NotificationTests { TestLogger.Info("OnHealthIssue was called"); } - } - class TestNotificationWithNoEvents : NotificationBase + private class TestNotificationWithNoEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); } - - } [Test] @@ -110,7 +103,6 @@ namespace NzbDrone.Core.Test.NotificationTests notification.SupportsOnHealthIssue.Should().BeTrue(); } - [Test] public void should_support_none_if_none_are_implemented() { @@ -123,5 +115,4 @@ namespace NzbDrone.Core.Test.NotificationTests notification.SupportsOnHealthIssue.Should().BeFalse(); } } - } diff --git a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs index 10f409804..072a5e3aa 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs @@ -2,10 +2,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Synology; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.NotificationTests @@ -50,7 +50,7 @@ namespace NzbDrone.Core.Test.NotificationTests { Settings = new SynologyIndexerSettings { - UpdateLibrary = true + UpdateLibrary = true } }; } diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs index 82f8731ca..edce144ea 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs @@ -3,10 +3,10 @@ using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs index a7fd46611..5337ad226 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs @@ -4,10 +4,10 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -33,9 +33,9 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc Subject.Definition = new NotificationDefinition(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true - }; + { + UpdateLibrary = true + }; } private void GivenOldFiles() @@ -45,10 +45,10 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc .ToList(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true, - CleanLibrary = true - }; + { + UpdateLibrary = true, + CleanLibrary = true + }; } [Test] diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs index c7751f041..0fcf16e14 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs @@ -3,10 +3,10 @@ using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -61,8 +61,8 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc Subject.UpdateMovie(_settings, fakeMovie); - Mocker.GetMock() - .Verify(v => v.UpdateLibrary(_settings, null), Times.Once()); + Mocker.GetMock() + .Verify(v => v.UpdateLibrary(_settings, null), Times.Once()); } } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs index 0da86640b..aed489ea3 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs @@ -14,6 +14,5 @@ namespace NzbDrone.Core.Test.OrganizerTests { FileNameBuilder.CleanFileName(name).Should().Be(expectedName); } - } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs index a60fccd3e..626257574 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs @@ -3,10 +3,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -56,6 +56,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [TestCase("[a] title", "a title")] [TestCase("backslash \\ backlash", "backslash backlash")] [TestCase("I'm the Boss", "Im the Boss")] + //[TestCase("", "")] public void should_get_expected_title_back(string title, string expected) { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs index deed98174..91bd08bc6 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs @@ -2,14 +2,14 @@ using System.IO; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; -using Moq; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -29,11 +29,9 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -68,7 +66,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardMovieFormat = "{Movie_Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South_Park"); } @@ -77,7 +75,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardMovieFormat = "{Movie.Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South.Park"); } @@ -86,7 +84,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardMovieFormat = "{Movie-Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South-Park"); } @@ -95,7 +93,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardMovieFormat = "{MOVIE TITLE}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("SOUTH PARK"); } @@ -113,7 +111,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardMovieFormat = "{movie title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("south park"); } @@ -127,9 +125,6 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .Should().Be("South.Park.1997"); } - - - [Test] public void should_replace_quality_title() { @@ -200,9 +195,6 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .Should().Be("30.Rock.S01E01.xvid-LOL"); } - - - [Test] public void should_should_replace_release_group() { @@ -342,12 +334,10 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .Should().Be("30.Rock.S01E01.xvid-LOL"); } - - [Test] public void should_not_include_quality_proper_when_release_is_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Quality Title} {Quality Proper}"; + _namingConfig.StandardMovieFormat = "{Quality Title} {Quality Proper}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("HDTV-720p"); @@ -356,7 +346,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [Test] public void should_wrap_proper_in_square_brackets() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Title}] {[Quality Proper]}"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Title}] {[Quality Proper]}"; GivenProper(); @@ -367,7 +357,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [Test] public void should_not_wrap_proper_in_square_brackets_when_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Title}] {[Quality Proper]}"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Title}] {[Quality Proper]}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("South Park [HDTV-720p]"); @@ -376,7 +366,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [Test] public void should_replace_quality_full_with_quality_title_only_when_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("South Park [HDTV-720p]"); @@ -385,7 +375,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [Test] public void should_replace_quality_full_with_quality_title_and_proper_only_when_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; GivenProper(); @@ -396,7 +386,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [Test] public void should_replace_quality_full_with_quality_title_and_real_when_a_real() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; GivenReal(); Subject.BuildFileName(_movie, _movieFile) @@ -409,7 +399,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [TestCase('_')] public void should_trim_extra_separators_from_end_when_quality_proper_is_not_included(char separator) { - _namingConfig.StandardMovieFormat= string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}", separator); + _namingConfig.StandardMovieFormat = string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}", separator); Subject.BuildFileName(_movie, _movieFile) .Should().Be("HDTV-720p"); @@ -421,7 +411,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [TestCase('_')] public void should_trim_extra_separators_from_middle_when_quality_proper_is_not_included(char separator) { - _namingConfig.StandardMovieFormat= string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}{0}{{Movie{0}Title}}", separator); + _namingConfig.StandardMovieFormat = string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}{0}{{Movie{0}Title}}", separator); Subject.BuildFileName(_movie, _movieFile) .Should().Be(string.Format("HDTV-720p{0}South{0}Park", separator)); @@ -431,7 +421,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_be_able_to_use_original_filename() { _movie.Title = "30 Rock"; - _namingConfig.StandardMovieFormat= "{Movie Title} - {Original Filename}"; + _namingConfig.StandardMovieFormat = "{Movie Title} - {Original Filename}"; _movieFile.SceneName = "30.Rock.S01E01.xvid-LOL"; _movieFile.RelativePath = "30 Rock - S01E01 - Test"; @@ -444,7 +434,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_be_able_to_use_original_filename_only() { _movie.Title = "30 Rock"; - _namingConfig.StandardMovieFormat= "{Original Filename}"; + _namingConfig.StandardMovieFormat = "{Original Filename}"; _movieFile.SceneName = "30.Rock.S01E01.xvid-LOL"; _movieFile.RelativePath = "30 Rock - S01E01 - Test"; @@ -457,7 +447,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_use_Sonarr_as_release_group_when_not_available() { _movieFile.ReleaseGroup = null; - _namingConfig.StandardMovieFormat= "{Release Group}"; + _namingConfig.StandardMovieFormat = "{Release Group}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("Radarr"); @@ -469,7 +459,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_not_use_Sonarr_as_release_group_if_pattern_has_separator(string pattern, string expectedFileName) { _movieFile.ReleaseGroup = null; - _namingConfig.StandardMovieFormat= pattern; + _namingConfig.StandardMovieFormat = pattern; Subject.BuildFileName(_movie, _movieFile) .Should().Be(expectedFileName); @@ -481,7 +471,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_use_existing_casing_for_release_group(string releaseGroup) { _movieFile.ReleaseGroup = releaseGroup; - _namingConfig.StandardMovieFormat= "{Release Group}"; + _namingConfig.StandardMovieFormat = "{Release Group}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be(releaseGroup); @@ -495,11 +485,9 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardMovieFormat = "{MediaInfo AudioLanguages}"; - - Subject.BuildFileName( _movie , _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be(expected); } @@ -511,11 +499,9 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardMovieFormat = "{MediaInfo AudioLanguagesAll}"; - - Subject.BuildFileName( _movie , _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be(expected); } @@ -523,8 +509,10 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [TestCase(10, "BT.2020", "PQ", "South.Park.HDR")] [TestCase(10, "BT.2020", "HLG", "South.Park.HDR")] [TestCase(0, null, null, "South.Park")] - public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, string colourPrimaries, - string transferCharacteristics, string expectedName) + public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, + string colourPrimaries, + string transferCharacteristics, + string expectedName) { _namingConfig.StandardMovieFormat = "{Movie.Title}.{MediaInfo VideoDynamicRange}"; @@ -543,7 +531,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Once()); } @@ -557,7 +545,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(schemaRevision: 3); _movie.Path = null; - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -570,7 +558,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -583,7 +571,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests GivenMediaInfoModel(schemaRevision: 5); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -601,9 +589,15 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } - private void GivenMediaInfoModel(string videoCodec = "AVC", string audioCodec = "DTS", int audioChannels = 6, int videoBitDepth = 8, - string videoColourPrimaries = "", string videoTransferCharacteristics = "", string audioLanguages = "English", - string subtitles = "English/Spanish/Italian", int schemaRevision = 5) + private void GivenMediaInfoModel(string videoCodec = "AVC", + string audioCodec = "DTS", + int audioChannels = 6, + int videoBitDepth = 8, + string videoColourPrimaries = "", + string videoTransferCharacteristics = "", + string audioLanguages = "English", + string subtitles = "English/Spanish/Italian", + int schemaRevision = 5) { _movieFile.MediaInfo = new MediaInfoModel { @@ -617,8 +611,6 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests VideoTransferCharacteristics = videoTransferCharacteristics, SchemaRevision = schemaRevision }; - } - } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs index 33c362f60..b8771bf9b 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NUnit.Framework.Internal; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -48,4 +48,4 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .Should().Be($"Movie Title ({_movie.TmdbId})"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs index 95df14608..35568c868 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs @@ -1,8 +1,8 @@ +using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using FluentAssertions; namespace NzbDrone.Core.Test.OrganizerTests { @@ -10,15 +10,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class GetMovieFolderFixture : CoreTest { - private NamingConfig namingConfig; + private NamingConfig _namingConfig; [SetUp] public void Setup() { - namingConfig = NamingConfig.Default; + _namingConfig = NamingConfig.Default; Mocker.GetMock() - .Setup(c => c.GetConfig()).Returns(namingConfig); + .Setup(c => c.GetConfig()).Returns(_namingConfig); } [TestCase("Arrival", 2016, "{Movie Title} ({Release Year})", "Arrival (2016)")] @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Test.OrganizerTests [TestCase("The Big Short", 2015, "{Movie Title} ({Release Year})", "The Big Short (2015)")] public void should_use_movieFolderFormat_to_build_folder_name(string movieTitle, int year, string format, string expected) { - namingConfig.MovieFolderFormat = format; + _namingConfig.MovieFolderFormat = format; var movie = new Movie { Title = movieTitle, Year = year }; diff --git a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs index 89699a0b7..21d9afcac 100644 --- a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class NormalizeTitleFixture : CoreTest { @@ -129,9 +128,8 @@ namespace NzbDrone.Core.Test.ParserTests foreach (var s in dirtyFormat) { var dirty = string.Format(s, word); - dirty.CleanSeriesTitle().Should().Be(("word" + word.ToLower() + "word")); + dirty.CleanSeriesTitle().Should().Be("word" + word.ToLower() + "word"); } - } [TestCase("The Office", "theoffice")] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs index 6b7572d92..62c564b5d 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class ParserFixture : CoreTest { diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs index 84e78ecf4..101183463 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs @@ -7,7 +7,8 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { [TestFixture] - public abstract class AugmentMovieInfoFixture : CoreTest where TAugmenter : class, IAugmentParsedMovieInfo + public abstract class AugmentMovieInfoFixture : CoreTest + where TAugmenter : class, IAugmentParsedMovieInfo { protected ParsedMovieInfo MovieInfo; diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs index ac21a5ebd..41027c486 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs @@ -21,6 +21,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests public override void Setup() { base.Setup(); + //Add multi indexer GivenIndexerSettings(new RarbgSettings { @@ -30,7 +31,6 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests (int)Language.French, } }); - } protected new AugmentWithHistory Subject @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { if (_customSubject == null) { - _customSubject = new AugmentWithHistory(Mocker.GetMock().Object, new List{ Mocker.Resolve()}); + _customSubject = new AugmentWithHistory(Mocker.GetMock().Object, new List { Mocker.Resolve() }); } return _customSubject; @@ -57,8 +57,9 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests private History.History HistoryWithData(params string[] data) { var dict = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - for (var i = 0; i < data.Length; i += 2) { - dict.Add(data[i], data[i+1]); + for (var i = 0; i < data.Length; i += 2) + { + dict.Add(data[i], data[i + 1]); } return new History.History diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs index fca6406dc..0f881235f 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs @@ -50,10 +50,10 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { var folderInfo = new ParsedMovieInfo { - Languages = new List {Language.French} + Languages = new List { Language.French } }; - MovieInfo.Languages = new List{Language.English}; + MovieInfo.Languages = new List { Language.English }; var result = Subject.AugmentMovieInfo(MovieInfo, folderInfo); diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs index 384a48c5f..e4e8acd8e 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { _indexerDefinition = new IndexerDefinition { - Settings = new RarbgSettings { MultiLanguages = languages.ToList().Select(l => (int) l) } + Settings = new RarbgSettings { MultiLanguages = languages.ToList().Select(l => (int)l) } }; Mocker.GetMock() @@ -29,8 +29,6 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { IndexerId = 1 }; - - } [Test] @@ -80,6 +78,5 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests var movieInfo = Subject.AugmentMovieInfo(MovieInfo, releaseInfo); movieInfo.ExtraInfo["IndexerFlags"].Should().BeEquivalentTo(IndexerFlags.PTP_Approved | IndexerFlags.PTP_Golden); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs index 44648d4e0..6dac2f9d9 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs @@ -1,8 +1,8 @@ using Moq; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests { @@ -28,7 +28,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests Subject.GetMovie(title); Mocker.GetMock() - .Verify(s => s.FindByTitle(Parser.Parser.ParseMovieTitle(title,false,false).MovieTitle), Times.Once()); + .Verify(s => s.FindByTitle(Parser.Parser.ParseMovieTitle(title, false, false).MovieTitle), Times.Once()); } /*[Test] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs index e59666890..9d713b592 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs @@ -6,10 +6,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Datastore; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests @@ -30,19 +30,17 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests [SetUp] public void Setup() { - _movie = Builder.CreateNew() .With(m => m.Title = "Fack Ju Göthe 2") .With(m => m.CleanTitle = "fackjugoethe2") .With(m => m.Year = 2015) - .With(m => m.AlternativeTitles = new LazyList( new List {new AlternativeTitle("Fack Ju Göthe 2: Same same")})) + .With(m => m.AlternativeTitles = new LazyList(new List { new AlternativeTitle("Fack Ju Göthe 2: Same same") })) .Build(); _parsedMovieInfo = new ParsedMovieInfo { MovieTitle = _movie.Title, Year = _movie.Year, - }; _wrongYearInfo = new ParsedMovieInfo @@ -158,6 +156,5 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests Subject.Map(_umlautInfo, "", _movieSearchCriteria).Movie.Should().Be(_movieSearchCriteria.Movie); Subject.Map(_umlautAltInfo, "", _movieSearchCriteria).Movie.Should().Be(_movieSearchCriteria.Movie); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs index 3c1907851..e11e08fc8 100644 --- a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Test.ParserTests public class QualityParserFixture : CoreTest { - [SetUp] public void Setup() { @@ -19,7 +18,6 @@ namespace NzbDrone.Core.Test.ParserTests } //public static object[] SelfQualityParserCases = QualityDefinition.DefaultQualityDefinitions.ToArray(); - public static object[] OtherSourceQualityParserCases = { new object[] { "SD TV", Source.TV, Resolution.R480p, Modifier.NONE }, @@ -113,7 +111,6 @@ namespace NzbDrone.Core.Test.ParserTests ParseAndVerifyQuality(title, Source.TV, proper, Resolution.R720p); } - [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.X264-QCF", false)] [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.x264-QCF", false)] [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.proper.X264-QCF", true)] @@ -282,7 +279,6 @@ namespace NzbDrone.Core.Test.ParserTests //{ // ParseAndVerifyQuality(title, Quality.RAWHD, proper); //} - [TestCase("Sonny.With.a.Chance.S02E15", false)] [TestCase("Law & Order: Special Victims Unit - 11x11 - Quickie", false)] [TestCase("Series.Title.S01E01.webm", false)] @@ -306,7 +302,8 @@ namespace NzbDrone.Core.Test.ParserTests }*/ - [Test, TestCaseSource("OtherSourceQualityParserCases")] + [Test] + [TestCaseSource("OtherSourceQualityParserCases")] public void should_parse_quality_from_other_source(string qualityString, Source source, Resolution resolution, Modifier modifier = Modifier.NONE) { foreach (var c in new char[] { '-', '.', ' ', '_' }) @@ -363,6 +360,7 @@ namespace NzbDrone.Core.Test.ParserTests { result.Quality.Resolution.Should().Be((int)resolution); } + result.Quality.Source.Should().Be(source); if (modifier != Modifier.NONE) { diff --git a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs index ae56e308f..ca183c37a 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs @@ -37,17 +37,17 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("NCIS.S16E04.Third.Wheel.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb-GEROV", "NTb")] [TestCase("Will.and.Grace.S10E06.Kid.n.Play.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb-Z0iDS3N", "NTb")] [TestCase("Absolute.Power.S02E06.The.House.of.Lords.DVDRip.x264-MaG-Chamele0n", "MaG")] + //[TestCase("", "")] public void should_parse_release_group(string title, string expected) { Parser.Parser.ParseReleaseGroup(title).Should().Be(expected); } - - [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV English", "SKGTV")] [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV_English", "SKGTV")] [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV.English", "SKGTV")] + //[TestCase("", "")] public void should_not_include_language_in_release_group(string title, string expected) { @@ -72,6 +72,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("[Anime-Koi] Barakamon - S01E06 - Guys From Tokyo", "Anime-Koi")] [TestCase("[Anime-Koi] Barakamon - S01E07 - A High-Grade Fish", "Anime-Koi")] [TestCase("[Anime-Koi] Kami-sama Hajimemashita 2 - 01 [h264-720p][28D54E2C]", "Anime-Koi")] + //[TestCase("Tokyo.Ghoul.02x01.013.HDTV-720p-Anime-Koi", "Anime-Koi")] //[TestCase("", "")] public void should_parse_anime_release_groups(string title, string expected) diff --git a/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs b/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs index 881015064..e6166733f 100644 --- a/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Test.ParserTests.RomanNumeralTests { private const string TEST_VALUES = @"Files/ArabicRomanNumeralDictionary.JSON"; - private Dictionary _arabicToRomanNumeralsMapping; [OneTimeSetUp] @@ -22,10 +21,9 @@ namespace NzbDrone.Core.Test.ParserTests.RomanNumeralTests JsonConvert.DeserializeObject>(File.ReadAllText(pathToTestValues)); } - [Test(Description = "Converts the supported range [1-3999] of Arabic to Roman numerals.")] [Order(0)] - public void should_convert_arabic_numeral_to_roman_numeral([Range(1,20)] int arabicNumeral) + public void should_convert_arabic_numeral_to_roman_numeral([Range(1, 20)] int arabicNumeral) { RomanNumeral romanNumeral = new RomanNumeral(arabicNumeral); @@ -44,8 +42,5 @@ namespace NzbDrone.Core.Test.ParserTests.RomanNumeralTests Assert.AreEqual(romanNumeral.ToInt(), expectecdValue); } - - - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs index cd2488050..0162c3b81 100644 --- a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Core.Test.ParserTests SceneChecker.IsSceneTitle(title).Should().BeTrue(); } - [TestCase("S08E05 - Virtual In-Stanity [WEBDL-720p]")] [TestCase("S08E05 - Virtual In-Stanity.With.Dots [WEBDL-720p]")] [TestCase("Something")] @@ -30,7 +29,5 @@ namespace NzbDrone.Core.Test.ParserTests { SceneChecker.IsSceneTitle(title).Should().BeFalse(); } - - } } diff --git a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs index ff533103e..c86678035 100644 --- a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs @@ -75,7 +75,6 @@ namespace NzbDrone.Core.Test.Profiles.Delay { delayProfile.Order.Should().Be(int.MaxValue); } - else { delayProfile.Order.Should().Be(i + 1); diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs index 2f29fe20b..e845d70e8 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs @@ -18,13 +18,13 @@ namespace NzbDrone.Core.Test.Profiles public void should_be_able_to_read_and_write() { var profile = new Profile - { - Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), - FormatCutoff = CustomFormats.CustomFormat.None.Id, - FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), - Cutoff = Quality.Bluray1080p.Id, - Name = "TestProfile" - }; + { + Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), + FormatCutoff = CustomFormats.CustomFormat.None.Id, + FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), + Cutoff = Quality.Bluray1080p.Id, + Name = "TestProfile" + }; Subject.Insert(profile); @@ -32,8 +32,6 @@ namespace NzbDrone.Core.Test.Profiles StoredModel.Cutoff.Should().Be(profile.Cutoff); StoredModel.Items.Should().Equal(profile.Items, (a, b) => a.Quality == b.Quality && a.Allowed == b.Allowed); - - } } } diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs index 96d65f781..fa9e0e414 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using NzbDrone.Core.CustomFormats; -using System.Collections.Generic; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Profiles { @@ -30,6 +30,7 @@ namespace NzbDrone.Core.Test.Profiles } [Test] + //This confirms that new profiles are added only if no other profiles exists. //We don't want to keep adding them back if a user deleted them on purpose. public void Init_should_skip_if_any_profiles_already_exist() @@ -44,7 +45,6 @@ namespace NzbDrone.Core.Test.Profiles .Verify(v => v.Insert(It.IsAny()), Times.Never()); } - [Test] public void should_not_be_able_to_delete_profile_if_assigned_to_movie() { @@ -64,7 +64,6 @@ namespace NzbDrone.Core.Test.Profiles Assert.Throws(() => Subject.Delete(2)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] @@ -86,10 +85,8 @@ namespace NzbDrone.Core.Test.Profiles Assert.Throws(() => Subject.Delete(2)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } - [Test] public void should_delete_profile_if_not_assigned_to_movie_or_list() { diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs index 5e9d6c6a8..504fa1a3a 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs @@ -1,7 +1,7 @@ -using FluentAssertions; +using System.IO; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common; -using System.IO; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common; diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs index 071eb535b..163eadcb7 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs @@ -10,7 +10,6 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests { - public class GetVideoFilesFixture : CoreTest { private string[] _fileNames; diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs index 7f433f3ed..7fb282fa2 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs @@ -40,10 +40,10 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests Mocker.GetMock().SetupGet(s => s.RecycleBinCleanupDays).Returns(7); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.AllDirectories)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs index 3adb28208..bd4b8c4b0 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs @@ -70,7 +70,6 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests WithRecycleBin(); var path = @"C:\Test\TV\30 Rock\S01E01.avi".AsOsAgnostic(); - Mocker.Resolve().DeleteFile(path); Mocker.GetMock().Verify(v => v.FileSetLastWriteTime(@"C:\Test\Recycle Bin\S01E01.avi".AsOsAgnostic(), It.IsAny()), Times.Once()); diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs index 8a5b486cd..f061c1388 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs @@ -20,10 +20,10 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests Mocker.GetMock().SetupGet(s => s.RecycleBin).Returns(RecycleBin); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.TopDirectoryOnly)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] diff --git a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs index 170fffee7..c2417fa53 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs @@ -32,7 +32,7 @@ namespace NzbDrone.Core.Test.Qualities Subject.Handle(new ApplicationStartedEvent()); Mocker.GetMock() - .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count -1 )), Times.Once()); + .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count - 1)), Times.Once()); } [Test] @@ -59,7 +59,7 @@ namespace NzbDrone.Core.Test.Qualities .Setup(s => s.All()) .Returns(new List { - new QualityDefinition(new Quality{ Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } + new QualityDefinition(new Quality { Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } }); Subject.Handle(new ApplicationStartedEvent()); diff --git a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs index e64216ed9..201ec4b15 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Profiles; @@ -14,48 +14,52 @@ namespace NzbDrone.Core.Test.Qualities { public static object[] FromIntCases = { - new object[] {0, Quality.Unknown}, - new object[] {1, Quality.SDTV}, - new object[] {2, Quality.DVD}, - new object[] {3, Quality.WEBDL1080p}, - new object[] {4, Quality.HDTV720p}, - new object[] {5, Quality.WEBDL720p}, - new object[] {6, Quality.Bluray720p}, - new object[] {7, Quality.Bluray1080p}, - new object[] {8, Quality.WEBDL480p}, - new object[] {9, Quality.HDTV1080p}, + new object[] { 0, Quality.Unknown }, + new object[] { 1, Quality.SDTV }, + new object[] { 2, Quality.DVD }, + new object[] { 3, Quality.WEBDL1080p }, + new object[] { 4, Quality.HDTV720p }, + new object[] { 5, Quality.WEBDL720p }, + new object[] { 6, Quality.Bluray720p }, + new object[] { 7, Quality.Bluray1080p }, + new object[] { 8, Quality.WEBDL480p }, + new object[] { 9, Quality.HDTV1080p }, + //new object[] {10, Quality.RAWHD}, - new object[] {16, Quality.HDTV2160p}, - new object[] {18, Quality.WEBDL2160p}, - new object[] {19, Quality.Bluray2160p}, + new object[] { 16, Quality.HDTV2160p }, + new object[] { 18, Quality.WEBDL2160p }, + new object[] { 19, Quality.Bluray2160p }, }; public static object[] ToIntCases = { - new object[] {Quality.Unknown, 0}, - new object[] {Quality.SDTV, 1}, - new object[] {Quality.DVD, 2}, - new object[] {Quality.WEBDL1080p, 3}, - new object[] {Quality.HDTV720p, 4}, - new object[] {Quality.WEBDL720p, 5}, - new object[] {Quality.Bluray720p, 6}, - new object[] {Quality.Bluray1080p, 7}, - new object[] {Quality.WEBDL480p, 8}, - new object[] {Quality.HDTV1080p, 9}, + new object[] { Quality.Unknown, 0 }, + new object[] { Quality.SDTV, 1 }, + new object[] { Quality.DVD, 2 }, + new object[] { Quality.WEBDL1080p, 3 }, + new object[] { Quality.HDTV720p, 4 }, + new object[] { Quality.WEBDL720p, 5 }, + new object[] { Quality.Bluray720p, 6 }, + new object[] { Quality.Bluray1080p, 7 }, + new object[] { Quality.WEBDL480p, 8 }, + new object[] { Quality.HDTV1080p, 9 }, + //new object[] {Quality.RAWHD, 10}, - new object[] {Quality.HDTV2160p, 16}, - new object[] {Quality.WEBDL2160p, 18}, - new object[] {Quality.Bluray2160p, 19}, + new object[] { Quality.HDTV2160p, 16 }, + new object[] { Quality.WEBDL2160p, 18 }, + new object[] { Quality.Bluray2160p, 19 }, }; - [Test, TestCaseSource("FromIntCases")] + [Test] + [TestCaseSource("FromIntCases")] public void should_be_able_to_convert_int_to_qualityTypes(int source, Quality expected) { var quality = (Quality)source; quality.Should().Be(expected); } - [Test, TestCaseSource("ToIntCases")] + [Test] + [TestCaseSource("ToIntCases")] public void should_be_able_to_convert_qualityTypes_to_int(Quality source, int expected) { var i = (int)source; @@ -90,7 +94,9 @@ namespace NzbDrone.Core.Test.Qualities }; if (allowed.Length == 0) + { allowed = qualities.ToArray(); + } var items = qualities .Except(allowed) diff --git a/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs index 4c81d7f40..180580e0b 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs @@ -77,12 +77,12 @@ namespace NzbDrone.Core.Test.Qualities private void GivenDefaultProfileWithFormats() { - _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH"){Id=1}; - _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH"){Id=2}; + _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH") { Id = 1 }; + _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH") { Id = 2 }; CustomFormatsFixture.GivenCustomFormats(CustomFormats.CustomFormat.None, _customFormat1, _customFormat2); - Subject = new QualityModelComparer(new Profile {Items = QualityFixture.GetDefaultQualities(), FormatItems = CustomFormatsFixture.GetSampleFormatItems()}); + Subject = new QualityModelComparer(new Profile { Items = QualityFixture.GetDefaultQualities(), FormatItems = CustomFormatsFixture.GetSampleFormatItems() }); } [Test] @@ -142,8 +142,8 @@ namespace NzbDrone.Core.Test.Qualities { GivenDefaultProfileWithFormats(); - var first = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat1}}; - var second = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat2}}; + var first = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat1 } }; + var second = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat2 } }; var compare = Subject.Compare(first, second); @@ -155,8 +155,8 @@ namespace NzbDrone.Core.Test.Qualities { GivenDefaultProfileWithFormats(); - var first = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat2}}; - var second = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat1}}; + var first = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat2 } }; + var second = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat1 } }; var compare = Subject.Compare(first, second); diff --git a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs index e67640c58..5756ede70 100644 --- a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs @@ -134,10 +134,10 @@ namespace NzbDrone.Core.Test.Qualities [Test] public void operating_on_nulls() { - (null > new Revision()).Should().BeFalse(); - (null >= new Revision()).Should().BeFalse(); - (null < new Revision()).Should().BeTrue(); - (null <= new Revision()).Should().BeTrue(); + (new Revision() < null).Should().BeFalse(); + (new Revision() <= null).Should().BeFalse(); + (new Revision() > null).Should().BeTrue(); + (new Revision() >= null).Should().BeTrue(); (new Revision() > null).Should().BeTrue(); (new Revision() >= null).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs index 849e6493c..39ef9140b 100644 --- a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs +++ b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using NUnit.Framework; -using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Queue; -using NzbDrone.Core.Test.Framework; using FizzWare.NBuilder; using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Queue; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.QueueTests { diff --git a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs index 7b0777d12..47f023c1b 100644 --- a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; @@ -7,7 +8,6 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using FizzWare.NBuilder; namespace NzbDrone.Core.Test.RemotePathMappingsTests { @@ -128,7 +128,7 @@ namespace NzbDrone.Core.Test.RemotePathMappingsTests { Host = "my-server.localdomain", RemotePath = remotePath, - LocalPath = @"D:\mountedstorage\downloads\tv" .AsOsAgnostic() + LocalPath = @"D:\mountedstorage\downloads\tv".AsOsAgnostic() }; var result = Subject.Add(mapping); diff --git a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs index 84cbe5142..0909b69ef 100644 --- a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs @@ -7,11 +7,11 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Movies; using NzbDrone.Core.RootFolders; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Common.EnvironmentInfo; namespace NzbDrone.Core.Test.RootFolderTests { @@ -74,8 +74,7 @@ namespace NzbDrone.Core.Test.RootFolderTests public void invalid_folder_path_throws_on_add(string path) { Assert.Throws(() => - Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path }) - ); + Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path })); } [Test] @@ -117,7 +116,6 @@ namespace NzbDrone.Core.Test.RootFolderTests .Build(); } - var subFolders = new[] { "Series1", diff --git a/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs index 6d95bc4df..6107479e4 100644 --- a/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs @@ -7,7 +7,6 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ThingiProvider { - public class ProviderRepositoryFixture : DbTest { [Test] @@ -24,7 +23,7 @@ namespace NzbDrone.Core.Test.ThingiProvider var storedSetting = (NewznabSettings)storedProvider.Settings; - storedSetting.Should().BeEquivalentTo(newznabSettings, o=>o.IncludingAllRuntimeProperties()); + storedSetting.Should().BeEquivalentTo(newznabSettings, o => o.IncludingAllRuntimeProperties()); } } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs index 7de6c61b8..1faf6d750 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.ThingiProviderTests var storedSetting = (NewznabSettings)storedProvider.Settings; - storedSetting.Should().BeEquivalentTo(newznabSettings, o=>o.IncludingAllRuntimeProperties()); + storedSetting.Should().BeEquivalentTo(newznabSettings, o => o.IncludingAllRuntimeProperties()); } } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs index 80d533ed2..f9c0d4325 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs @@ -29,7 +29,6 @@ namespace NzbDrone.Core.Test.ThingiProviderTests public MockProviderStatusService(IMockProviderStatusRepository providerStatusRepository, IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, Logger logger) : base(providerStatusRepository, eventAggregator, runtimeInfo, logger) { - } } diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs index 8eed7f51f..947371229 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="NetCore")] + [Platform(Exclude = "NetCore")] public void finds_update_when_version_lower() { UseRealHttp(); @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.GetLatestUpdate("invalid_branch", new Version(0, 2)).Should().NotBeNull(); } - [Test] public void should_get_recent_updates() { diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs index 29c13762c..0d34816fa 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Test.UpdateTests Version = new Version("2.0.0.0") }; } - else { _updatePackage = new UpdatePackage @@ -115,7 +114,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.Execute(new ApplicationUpdateCommand()); - Mocker.GetMock().Verify(c => c.DeleteFolder(_sandboxFolder, true), Times.Never()); } @@ -166,7 +164,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.Execute(new ApplicationUpdateCommand()); - ExceptionVerification.AssertNoUnexpectedLogs(); } @@ -181,7 +178,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_run_script_if_configured() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -194,7 +191,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_not_set() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -208,7 +205,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_null() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -222,7 +219,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_path_does_not_exist() { const string scriptPath = "/tmp/nzbdrone/update.sh"; diff --git a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs index 94a48cc44..f33662704 100644 --- a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs +++ b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs @@ -3,11 +3,11 @@ using System.IO; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Validation.Paths; using NzbDrone.Test.Common; -using NzbDrone.Common.EnvironmentInfo; namespace NzbDrone.Core.Test.ValidationTests { diff --git a/src/NzbDrone.Core/Analytics/AnalyticsService.cs b/src/NzbDrone.Core/Analytics/AnalyticsService.cs index c16bfa0a6..9e962c0a0 100644 --- a/src/NzbDrone.Core/Analytics/AnalyticsService.cs +++ b/src/NzbDrone.Core/Analytics/AnalyticsService.cs @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Analytics _historyService = historyService; } - public bool IsEnabled => _configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction || RuntimeInfo.IsDevelopment; + public bool IsEnabled => (_configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction) || RuntimeInfo.IsDevelopment; public bool InstallIsActive { diff --git a/src/NzbDrone.Core/Authentication/UserService.cs b/src/NzbDrone.Core/Authentication/UserService.cs index 60f77df13..0559c2133 100644 --- a/src/NzbDrone.Core/Authentication/UserService.cs +++ b/src/NzbDrone.Core/Authentication/UserService.cs @@ -35,11 +35,11 @@ namespace NzbDrone.Core.Authentication public User Add(string username, string password) { return _repo.Insert(new User - { - Identifier = Guid.NewGuid(), - Username = username.ToLowerInvariant(), - Password = password.SHA256Hash() - }); + { + Identifier = Guid.NewGuid(), + Username = username.ToLowerInvariant(), + Password = password.SHA256Hash() + }); } public User Update(User user) diff --git a/src/NzbDrone.Core/Backup/BackupService.cs b/src/NzbDrone.Core/Backup/BackupService.cs index 31a2905b1..f19d83d33 100644 --- a/src/NzbDrone.Core/Backup/BackupService.cs +++ b/src/NzbDrone.Core/Backup/BackupService.cs @@ -104,11 +104,11 @@ namespace NzbDrone.Core.Backup if (_diskProvider.FolderExists(folder)) { backups.AddRange(GetBackupFiles(folder).Select(b => new Backup - { - Name = Path.GetFileName(b), - Type = backupType, - Time = _diskProvider.FileGetLastWrite(b) - })); + { + Name = Path.GetFileName(b), + Type = backupType, + Time = _diskProvider.FileGetLastWrite(b) + })); } } diff --git a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs index 1904b0bf9..961744127 100644 --- a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs +++ b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs @@ -26,9 +26,11 @@ namespace NzbDrone.Core.Backup { sourceConnectionString = db.ConnectionString; } + var backupConnectionStringBuilder = new SQLiteConnectionStringBuilder(sourceConnectionString); backupConnectionStringBuilder.DataSource = Path.Combine(targetDirectory, Path.GetFileName(backupConnectionStringBuilder.DataSource)); + // We MUST use journal mode instead of WAL coz WAL has issues when page sizes change. This should also automatically deal with the -journal and -wal files during restore. backupConnectionStringBuilder.JournalMode = SQLiteJournalModeEnum.Truncate; diff --git a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs index 3a06b1b1b..40c4d2216 100644 --- a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs +++ b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Backup { public class RestoreBackupFailedException : NzbDroneClientException { - public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) : base(statusCode, message, args) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) + : base(statusCode, message, args) { } - public RestoreBackupFailedException(HttpStatusCode statusCode, string message) : base(statusCode, message) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message) + : base(statusCode, message) { } } diff --git a/src/NzbDrone.Core/Blacklisting/Blacklist.cs b/src/NzbDrone.Core/Blacklisting/Blacklist.cs index 4000d404e..c041126cf 100644 --- a/src/NzbDrone.Core/Blacklisting/Blacklist.cs +++ b/src/NzbDrone.Core/Blacklisting/Blacklist.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Blacklisting { diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs index fc398d89b..6c93ec5d3 100644 --- a/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs +++ b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using Marr.Data.QGen; using NzbDrone.Core.Movies; namespace NzbDrone.Core.Blacklisting @@ -15,8 +15,8 @@ namespace NzbDrone.Core.Blacklisting public class BlacklistRepository : BasicRepository, IBlacklistRepository { - public BlacklistRepository(IMainDatabase database, IEventAggregator eventAggregator) : - base(database, eventAggregator) + public BlacklistRepository(IMainDatabase database, IEventAggregator eventAggregator) + : base(database, eventAggregator) { } diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs index 28a390f72..fb9bd3ad6 100644 --- a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs +++ b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies.Events; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Blacklisting { @@ -18,6 +18,7 @@ namespace NzbDrone.Core.Blacklisting PagingSpec Paged(PagingSpec pagingSpec); void Delete(int id); } + public class BlacklistService : IBlacklistService, IExecute, @@ -39,7 +40,10 @@ namespace NzbDrone.Core.Blacklisting { var torrentInfo = release as TorrentInfo; - if (torrentInfo == null) return false; + if (torrentInfo == null) + { + return false; + } if (torrentInfo.InfoHash.IsNullOrWhiteSpace()) { @@ -105,7 +109,10 @@ namespace NzbDrone.Core.Blacklisting private bool HasSamePublishedDate(Blacklist item, DateTime publishedDate) { - if (!item.PublishedDate.HasValue) return true; + if (!item.PublishedDate.HasValue) + { + return true; + } return item.PublishedDate.Value.AddMinutes(-2) <= publishedDate && item.PublishedDate.Value.AddMinutes(2) >= publishedDate; @@ -113,7 +120,10 @@ namespace NzbDrone.Core.Blacklisting private bool HasSameSize(Blacklist item, long size) { - if (!item.Size.HasValue) return true; + if (!item.Size.HasValue) + { + return true; + } var difference = Math.Abs(item.Size.Value - size); @@ -128,19 +138,19 @@ namespace NzbDrone.Core.Blacklisting public void Handle(DownloadFailedEvent message) { var blacklist = new Blacklist - { - MovieId = message.MovieId, - SourceTitle = message.SourceTitle, - Quality = message.Quality, - Date = DateTime.UtcNow, - PublishedDate = DateTime.Parse(message.Data.GetValueOrDefault("publishedDate")), - Size = long.Parse(message.Data.GetValueOrDefault("size", "0")), - Indexer = message.Data.GetValueOrDefault("indexer"), - Protocol = (DownloadProtocol)Convert.ToInt32(message.Data.GetValueOrDefault("protocol")), - Message = message.Message, - TorrentInfoHash = message.Data.GetValueOrDefault("torrentInfoHash"), - Languages = message.Languages - }; + { + MovieId = message.MovieId, + SourceTitle = message.SourceTitle, + Quality = message.Quality, + Date = DateTime.UtcNow, + PublishedDate = DateTime.Parse(message.Data.GetValueOrDefault("publishedDate")), + Size = long.Parse(message.Data.GetValueOrDefault("size", "0")), + Indexer = message.Data.GetValueOrDefault("indexer"), + Protocol = (DownloadProtocol)Convert.ToInt32(message.Data.GetValueOrDefault("protocol")), + Message = message.Message, + TorrentInfoHash = message.Data.GetValueOrDefault("torrentInfoHash"), + Languages = message.Languages + }; _blacklistRepository.Insert(blacklist); } diff --git a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs index ab2d94dc6..e6fae6394 100644 --- a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs +++ b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs @@ -101,7 +101,10 @@ namespace NzbDrone.Core.Configuration object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null) continue; + if (currentValue == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); @@ -260,7 +263,6 @@ namespace NzbDrone.Core.Configuration { parentContainer.Add(new XElement(key, valueString)); } - else { parentContainer.Descendants(key).Single().Value = valueString; @@ -334,7 +336,6 @@ namespace NzbDrone.Core.Configuration return xDoc; } } - catch (XmlException ex) { throw new InvalidConfigFileException($"{_configFile} is corrupt is invalid. Please delete the config file and Radarr will recreate it.", ex); diff --git a/src/NzbDrone.Core/Configuration/ConfigRepository.cs b/src/NzbDrone.Core/Configuration/ConfigRepository.cs index 23d3cbd7b..c8ae80c21 100644 --- a/src/NzbDrone.Core/Configuration/ConfigRepository.cs +++ b/src/NzbDrone.Core/Configuration/ConfigRepository.cs @@ -2,7 +2,6 @@ using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Configuration { public interface IConfigRepository : IBasicRepository @@ -18,7 +17,6 @@ namespace NzbDrone.Core.Configuration { } - public Config Get(string key) { return Query.Where(c => c.Key == key).SingleOrDefault(); @@ -30,7 +28,7 @@ namespace NzbDrone.Core.Configuration if (dbValue == null) { - return Insert(new Config {Key = key, Value = value}); + return Insert(new Config { Key = key, Value = value }); } dbValue.Value = value; diff --git a/src/NzbDrone.Core/Configuration/ConfigService.cs b/src/NzbDrone.Core/Configuration/ConfigService.cs index 5d4b9d2cc..664978595 100644 --- a/src/NzbDrone.Core/Configuration/ConfigService.cs +++ b/src/NzbDrone.Core/Configuration/ConfigService.cs @@ -4,12 +4,12 @@ using System.Globalization; using System.Linq; using NLog; using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Common.Http.Proxy; -using NzbDrone.Core.Security; using NzbDrone.Core.Parser; +using NzbDrone.Core.Security; namespace NzbDrone.Core.Configuration { @@ -57,7 +57,10 @@ namespace NzbDrone.Core.Configuration { object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null || configValue.Value == null) continue; + if (currentValue == null || configValue.Value == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); diff --git a/src/NzbDrone.Core/Configuration/IConfigService.cs b/src/NzbDrone.Core/Configuration/IConfigService.cs index 4b3cf0978..8da36b895 100644 --- a/src/NzbDrone.Core/Configuration/IConfigService.cs +++ b/src/NzbDrone.Core/Configuration/IConfigService.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.MediaFiles; using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser; using NzbDrone.Core.Security; diff --git a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs index 1251cf30a..4bed2f2a2 100644 --- a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs +++ b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Configuration { public class InvalidConfigFileException : NzbDroneException { - public InvalidConfigFileException(string message) : base(message) + public InvalidConfigFileException(string message) + : base(message) { } - public InvalidConfigFileException(string message, Exception innerException) : base(message, innerException) + public InvalidConfigFileException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormat.cs b/src/NzbDrone.Core/CustomFormats/CustomFormat.cs index 3aa08fda7..8e2e2e270 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormat.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormat.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Core.CustomFormats { public CustomFormat() { - } public CustomFormat(string name, params string[] tags) @@ -31,17 +30,37 @@ namespace NzbDrone.Core.CustomFormats public bool Equals(CustomFormat other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return int.Equals(Id, other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((CustomFormat) obj); + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != GetType()) + { + return false; + } + + return Equals((CustomFormat)obj); } public override int GetHashCode() @@ -60,9 +79,12 @@ namespace NzbDrone.Core.CustomFormats public static List WithNone(this IEnumerable formats) { var list = formats.ToList(); - if (list.Any()) return list; + if (list.Any()) + { + return list; + } - return new List{CustomFormat.None}; + return new List { CustomFormat.None }; } } } diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs b/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs index 205bdec36..0a8e868d9 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.CustomFormats { public interface ICustomFormatRepository : IBasicRepository { - } public class CustomFormatRepository : BasicRepository, ICustomFormatRepository diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs b/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs index 82bf3b355..3846f8d51 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs @@ -23,12 +23,11 @@ namespace NzbDrone.Core.CustomFormats void Delete(int id); } - public class CustomFormatService : ICustomFormatService, IHandle { private readonly ICustomFormatRepository _formatRepository; - private IProfileService _profileService; private readonly IHistoryService _historyService; + private IProfileService _profileService; public IProfileService ProfileService { @@ -49,8 +48,10 @@ namespace NzbDrone.Core.CustomFormats public static Dictionary AllCustomFormats; - public CustomFormatService(ICustomFormatRepository formatRepository, ICacheManager cacheManager, - IContainer container, IHistoryService historyService, + public CustomFormatService(ICustomFormatRepository formatRepository, + ICacheManager cacheManager, + IContainer container, + IHistoryService historyService, Logger logger) { _formatRepository = formatRepository; @@ -79,6 +80,7 @@ namespace NzbDrone.Core.CustomFormats _formatRepository.Delete(ret); throw; } + _cache.Clear(); return ret; } @@ -90,27 +92,36 @@ namespace NzbDrone.Core.CustomFormats { //First history: var historyRepo = _container.Resolve(); - DeleteInRepo(historyRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(historyRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then Blacklist: var blacklistRepo = _container.Resolve(); - DeleteInRepo(blacklistRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(blacklistRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then MovieFiles: var moviefileRepo = _container.Resolve(); - DeleteInRepo(moviefileRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(moviefileRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then Profiles ProfileService.DeleteCustomFormat(id); @@ -127,8 +138,11 @@ namespace NzbDrone.Core.CustomFormats _cache.Clear(); } - private void DeleteInRepo(IBasicRepository repository, Func> queryFunc, - Func, TModel> updateFunc, int customFormatId) where TModel : ModelBase, new() + private void DeleteInRepo(IBasicRepository repository, + Func> queryFunc, + Func, TModel> updateFunc, + int customFormatId) + where TModel : ModelBase, new() { var allItems = repository.All(); diff --git a/src/NzbDrone.Core/CustomFormats/FormatTag.cs b/src/NzbDrone.Core/CustomFormats/FormatTag.cs index 63d896541..a9de543bb 100644 --- a/src/NzbDrone.Core/CustomFormats/FormatTag.cs +++ b/src/NzbDrone.Core/CustomFormats/FormatTag.cs @@ -37,13 +37,16 @@ namespace NzbDrone.Core.CustomFormats // This function is needed for json deserialization to work. private FormatTag() { - } public bool DoesItMatch(ParsedMovieInfo movieInfo) { var match = DoesItMatchWithoutMods(movieInfo); - if (TagModifier.HasFlag(TagModifier.Not)) match = !match; + if (TagModifier.HasFlag(TagModifier.Not)) + { + match = !match; + } + return match; } @@ -62,31 +65,33 @@ namespace NzbDrone.Core.CustomFormats { compared = movieInfo.Edition; } + if (TagModifier.HasFlag(TagModifier.Regex)) { - Regex regexValue = (Regex) Value; + Regex regexValue = (Regex)Value; return regexValue.IsMatch(compared); } else { - string stringValue = (string) Value; + string stringValue = (string)Value; return compared.ToLower().Contains(stringValue.Replace(" ", string.Empty).ToLower()); } + case TagType.Language: return movieInfo.Languages.Contains((Language)Value); case TagType.Resolution: - return movieInfo.Quality.Quality.Resolution == (int)(Resolution) Value; + return movieInfo.Quality.Quality.Resolution == (int)(Resolution)Value; case TagType.Modifier: - return movieInfo.Quality.Quality.Modifier == (Modifier) Value; + return movieInfo.Quality.Quality.Modifier == (Modifier)Value; case TagType.Source: - return movieInfo.Quality.Quality.Source == (Source) Value; + return movieInfo.Quality.Quality.Source == (Source)Value; case TagType.Size: var size = (movieInfo.ExtraInfo.GetValueOrDefault("Size", 0.0) as long?) ?? 0; var tuple = Value as (long, long)? ?? (0, 0); return size > tuple.Item1 && size < tuple.Item2; case TagType.Indexer: #if !LIBRARY - return (movieInfo.ExtraInfo.GetValueOrDefault("IndexerFlags") as IndexerFlags?)?.HasFlag((IndexerFlags) Value) == true; + return (movieInfo.ExtraInfo.GetValueOrDefault("IndexerFlags") as IndexerFlags?)?.HasFlag((IndexerFlags)Value) == true; #endif default: return false; @@ -98,9 +103,20 @@ namespace NzbDrone.Core.CustomFormats var type = match.Groups["type"].Value.ToLower(); var value = match.Groups["value"].Value.ToLower(); - if (match.Groups["m_re"].Success) TagModifier |= TagModifier.AbsolutelyRequired; - if (match.Groups["m_r"].Success) TagModifier |= TagModifier.Regex; - if (match.Groups["m_n"].Success) TagModifier |= TagModifier.Not; + if (match.Groups["m_re"].Success) + { + TagModifier |= TagModifier.AbsolutelyRequired; + } + + if (match.Groups["m_r"].Success) + { + TagModifier |= TagModifier.Regex; + } + + if (match.Groups["m_n"].Success) + { + TagModifier |= TagModifier.Not; + } switch (type) { @@ -124,6 +140,7 @@ namespace NzbDrone.Core.CustomFormats Value = Resolution.R480p; break; } + break; case "s": TagType = TagType.Source; @@ -154,6 +171,7 @@ namespace NzbDrone.Core.CustomFormats Value = Source.BLURAY; break; } + break; case "m": TagType = TagType.Modifier; @@ -175,6 +193,7 @@ namespace NzbDrone.Core.CustomFormats Value = Modifier.REMUX; break; } + break; case "e": TagType = TagType.Edition; @@ -186,6 +205,7 @@ namespace NzbDrone.Core.CustomFormats { Value = value; } + break; case "l": TagType = TagType.Language; @@ -199,7 +219,11 @@ namespace NzbDrone.Core.CustomFormats foreach (IndexerFlags flagValue in flagValues) { var flagString = flagValue.ToString(); - if (flagString.ToLower().Replace("_", string.Empty) != value.ToLower().Replace("_", string.Empty)) continue; + if (flagString.ToLower().Replace("_", string.Empty) != value.ToLower().Replace("_", string.Empty)) + { + continue; + } + Value = flagValue; break; } @@ -223,10 +247,10 @@ namespace NzbDrone.Core.CustomFormats { Value = value; } + break; } } - } public enum TagType diff --git a/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs b/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs index d31fbd7bd..ecb14dbd7 100644 --- a/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs +++ b/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs @@ -9,6 +9,7 @@ namespace NzbDrone.Core.CustomFormats { GroupMatches = new List(); } + public CustomFormat CustomFormat { get; set; } public List GroupMatches { get; set; } public bool GoodMatch { get; set; } @@ -37,6 +38,7 @@ namespace NzbDrone.Core.CustomFormats Matches.All(m => m.Value == false)); } } + public Dictionary Matches { get; set; } } } diff --git a/src/NzbDrone.Core/Datastore/BasicRepository.cs b/src/NzbDrone.Core/Datastore/BasicRepository.cs index 344ec01da..ea70a8db2 100644 --- a/src/NzbDrone.Core/Datastore/BasicRepository.cs +++ b/src/NzbDrone.Core/Datastore/BasicRepository.cs @@ -12,7 +12,8 @@ using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Datastore { - public interface IBasicRepository where TModel : ModelBase, new() + public interface IBasicRepository + where TModel : ModelBase, new() { IEnumerable All(); int Count(); @@ -35,7 +36,8 @@ namespace NzbDrone.Core.Datastore PagingSpec GetPaged(PagingSpec pagingSpec); } - public class BasicRepository : IBasicRepository where TModel : ModelBase, new() + public class BasicRepository : IBasicRepository + where TModel : ModelBase, new() { private readonly IDatabase _database; private readonly IEventAggregator _eventAggregator; @@ -183,6 +185,7 @@ namespace NzbDrone.Core.Datastore Insert(model); return model; } + Update(model); return model; } diff --git a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs index d2ee3dc6b..bf68e751a 100644 --- a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - var val = (Nullable)clrValue; + var val = (bool?)clrValue; switch (val) { diff --git a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs index 0bb97f23a..a6c641206 100644 --- a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Datastore.Converters var ordinal = context.DataRecord.GetOrdinal("Name"); var contract = context.DataRecord.GetString(ordinal); - var impType = typeof (Command).Assembly.FindTypeByName(contract + "Command"); + var impType = typeof(Command).Assembly.FindTypeByName(contract + "Command"); if (impType == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs index 237d6bcd4..f6dfc810d 100644 --- a/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs @@ -38,14 +38,17 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - if(clrValue == DBNull.Value) return null; + if (clrValue == DBNull.Value) + { + return null; + } - if(!(clrValue is CustomFormat)) + if (!(clrValue is CustomFormat)) { throw new InvalidOperationException("Attempted to save a quality definition that isn't really a quality definition"); } - var quality = (CustomFormat) clrValue; + var quality = (CustomFormat)clrValue; if (CustomFormatService.AllCustomFormats?.ContainsKey(quality.Id) == false) { diff --git a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs index 82d00756d..045ba64e2 100644 --- a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs @@ -2,18 +2,18 @@ using Marr.Data.Converters; using Marr.Data.Mapping; using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; namespace NzbDrone.Core.Datastore.Converters { public class EmbeddedDocumentConverter : IConverter { - private readonly JsonSerializerSettings SerializerSetting; + private readonly JsonSerializerSettings _serializerSetting; public EmbeddedDocumentConverter(params JsonConverter[] converters) { - SerializerSetting = new JsonSerializerSettings + _serializerSetting = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, @@ -22,12 +22,12 @@ namespace NzbDrone.Core.Datastore.Converters ContractResolver = new CamelCasePropertyNamesContractResolver() }; - SerializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); - SerializerSetting.Converters.Add(new VersionConverter()); + _serializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); + _serializerSetting.Converters.Add(new VersionConverter()); foreach (var converter in converters) { - SerializerSetting.Converters.Add(converter); + _serializerSetting.Converters.Add(converter); } } @@ -44,7 +44,8 @@ namespace NzbDrone.Core.Datastore.Converters { return null; } - return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, SerializerSetting); + + return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, _serializerSetting); } public object FromDB(ColumnMap map, object dbValue) @@ -54,10 +55,17 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - if (clrValue == null) return null; - if (clrValue == DBNull.Value) return DBNull.Value; + if (clrValue == null) + { + return null; + } - return JsonConvert.SerializeObject(clrValue, SerializerSetting); + if (clrValue == DBNull.Value) + { + return DBNull.Value; + } + + return JsonConvert.SerializeObject(clrValue, _serializerSetting); } public Type DbType => typeof(string); diff --git a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs index 58f26970e..f0c4d705b 100644 --- a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs @@ -27,7 +27,10 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Language == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs index c2e2efd18..17590c4f1 100644 --- a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs @@ -25,8 +25,7 @@ namespace NzbDrone.Core.Datastore.Converters var ordinal = context.DataRecord.GetOrdinal("ConfigContract"); var contract = context.DataRecord.GetString(ordinal); - - var impType = typeof (IProviderConfig).Assembly.FindTypeByName(contract); + var impType = typeof(IProviderConfig).Assembly.FindTypeByName(contract); if (impType == null) { @@ -35,6 +34,5 @@ namespace NzbDrone.Core.Datastore.Converters return Json.Deserialize(stringValue, impType); } - } } diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs index 72a3cb53a..8487780de 100644 --- a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs @@ -1,8 +1,8 @@ using System; using Marr.Data.Converters; using Marr.Data.Mapping; -using NzbDrone.Core.Qualities; using Newtonsoft.Json; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Converters { @@ -27,7 +27,10 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Quality == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs index de8df90ba..ea2e8ea72 100644 --- a/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs @@ -27,14 +27,17 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - if(clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } - if(!(clrValue is FormatTag)) + if (!(clrValue is FormatTag)) { throw new InvalidOperationException("Attempted to save a quality tag that isn't really a quality tag"); } - var quality = (FormatTag) clrValue; + var quality = (FormatTag)clrValue; return quality.Raw; } diff --git a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs index 4493ca1b5..c6763a774 100644 --- a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs +++ b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Datastore { public class CorruptDatabaseException : RadarrStartupException { - public CorruptDatabaseException(string message, params object[] args) : base(message, args) + public CorruptDatabaseException(string message, params object[] args) + : base(message, args) { } - public CorruptDatabaseException(string message) : base(message) + public CorruptDatabaseException(string message) + : base(message) { } - public CorruptDatabaseException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CorruptDatabaseException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CorruptDatabaseException(string message, Exception innerException) : base(message, innerException) + public CorruptDatabaseException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Datastore/Database.cs b/src/NzbDrone.Core/Datastore/Database.cs index 1ff4fba49..047cac773 100644 --- a/src/NzbDrone.Core/Datastore/Database.cs +++ b/src/NzbDrone.Core/Datastore/Database.cs @@ -62,6 +62,7 @@ namespace NzbDrone.Core.Datastore { db.ExecuteNonQuery("Vacuum;"); } + _logger.Info("{0} database compressed", _databaseName); } catch (Exception e) diff --git a/src/NzbDrone.Core/Datastore/DbFactory.cs b/src/NzbDrone.Core/Datastore/DbFactory.cs index 07e406595..1aeb21ff8 100644 --- a/src/NzbDrone.Core/Datastore/DbFactory.cs +++ b/src/NzbDrone.Core/Datastore/DbFactory.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Exceptions; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore.Migration.Framework; - namespace NzbDrone.Core.Datastore { public interface IDbFactory @@ -83,6 +82,7 @@ namespace NzbDrone.Core.Datastore break; } + case MigrationType.Log: { connectionString = _connectionStringFactory.LogDbConnectionString; @@ -90,6 +90,7 @@ namespace NzbDrone.Core.Datastore break; } + default: { throw new ArgumentException("Invalid MigrationType"); diff --git a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs index fe87d1676..d5b02c8cb 100644 --- a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs +++ b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs @@ -2,7 +2,7 @@ namespace NzbDrone.Core.Datastore.Events { - public class ModelEvent : IEvent + public class ModelEvent : IEvent { public TModel Model { get; set; } public ModelAction Action { get; set; } diff --git a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs index 39a831a09..96cdd9c0d 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs @@ -8,20 +8,22 @@ namespace NzbDrone.Core.Datastore.Extensions { public static class MappingExtensions { - - public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) where T : ResultSet, new() + public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) + where T : ResultSet, new() { return mapBuilder .Columns .AutoMapPropertiesWhere(IsMappableProperty); } - public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ProviderDefinition, new() + public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ProviderDefinition, new() { return RegisterModel(mapBuilder, tableName).Ignore(c => c.ImplementationName); } - public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ModelBase, new() + public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ModelBase, new() { return mapBuilder.Table.MapTable(tableName) .Columns @@ -37,15 +39,17 @@ namespace NzbDrone.Core.Datastore.Extensions { return mapBuilder.Relationships.AutoMapPropertiesWhere(m => m.MemberType == MemberTypes.Property && - typeof(ModelBase).IsAssignableFrom(((PropertyInfo) m).PropertyType)); + typeof(ModelBase).IsAssignableFrom(((PropertyInfo)m).PropertyType)); } public static bool IsMappableProperty(MemberInfo memberInfo) { var propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo == null) return false; - + if (propertyInfo == null) + { + return false; + } if (!propertyInfo.IsReadable() || !propertyInfo.IsWritable()) { diff --git a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs index f81aacad3..46d217585 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs @@ -13,12 +13,15 @@ namespace NzbDrone.Core.Datastore.Extensions public static int PagingOffset(this PagingSpec pagingSpec) { - return (pagingSpec.Page - 1)*pagingSpec.PageSize; + return (pagingSpec.Page - 1) * pagingSpec.PageSize; } public static Marr.Data.QGen.SortDirection ToSortDirection(this PagingSpec pagingSpec) { - if (pagingSpec.SortDirection == SortDirection.Descending) return Marr.Data.QGen.SortDirection.Desc; + if (pagingSpec.SortDirection == SortDirection.Descending) + { + return Marr.Data.QGen.SortDirection.Desc; + } return Marr.Data.QGen.SortDirection.Asc; } @@ -41,4 +44,3 @@ namespace NzbDrone.Core.Datastore.Extensions } } } - diff --git a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs index 7c91fec6a..490bb49b4 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs @@ -19,8 +19,7 @@ namespace NzbDrone.Core.Datastore.Extensions { var id = childIdSelector(parent); return db.Query().Where(c => c.Id == id).SingleOrDefault(); - } - ); + }); } public static RelationshipBuilder Relationship(this ColumnMapBuilder mapBuilder) diff --git a/src/NzbDrone.Core/Datastore/LazyList.cs b/src/NzbDrone.Core/Datastore/LazyList.cs index ebbc51b8a..193a11812 100644 --- a/src/NzbDrone.Core/Datastore/LazyList.cs +++ b/src/NzbDrone.Core/Datastore/LazyList.cs @@ -8,13 +8,11 @@ namespace NzbDrone.Core.Datastore public LazyList() : this(new List()) { - } public LazyList(IEnumerable items) : base(new List(items)) { - } public static implicit operator LazyList(List val) diff --git a/src/NzbDrone.Core/Datastore/LogDatabase.cs b/src/NzbDrone.Core/Datastore/LogDatabase.cs index e1c9c3a20..6608a144f 100644 --- a/src/NzbDrone.Core/Datastore/LogDatabase.cs +++ b/src/NzbDrone.Core/Datastore/LogDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface ILogDatabase : IDatabase { - } public class LogDatabase : ILogDatabase diff --git a/src/NzbDrone.Core/Datastore/MainDatabase.cs b/src/NzbDrone.Core/Datastore/MainDatabase.cs index 869c3a6da..5faf4497c 100644 --- a/src/NzbDrone.Core/Datastore/MainDatabase.cs +++ b/src/NzbDrone.Core/Datastore/MainDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface IMainDatabase : IDatabase { - } public class MainDatabase : IMainDatabase diff --git a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs index 0042de064..44f28ce92 100644 --- a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs +++ b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs @@ -66,7 +66,6 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("Certification").AsString().Nullable() .WithColumn("AddOptions").AsString().Nullable(); - Create.TableForModel("Seasons") .WithColumn("SeriesId").AsInt32() .WithColumn("SeasonNumber").AsInt32() @@ -143,7 +142,6 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("TvdbId").AsInt32() .WithColumn("SeasonNumber").AsInt32(); - Create.TableForModel("NamingConfig") .WithColumn("UseSceneName").AsBoolean() .WithColumn("Separator").AsString() diff --git a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs index 5ebc51ac8..0eaf4da5b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs +++ b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Datastore.Migration { Delete.Table("History"); - Create.TableForModel("History") .WithColumn("EpisodeId").AsInt32() .WithColumn("SeriesId").AsInt32() diff --git a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs index d788dd7dc..dbe11a6a9 100644 --- a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs +++ b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs @@ -1,9 +1,9 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Linq; -using System.Data; +using System; using System.Collections.Generic; -using System; +using System.Data; +using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs index bf70a9532..776371f94 100644 --- a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs +++ b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs @@ -17,6 +17,5 @@ namespace NzbDrone.Core.Datastore.Migration Create.Index().OnTable("Series").OnColumn("TitleSlug").Unique(); Create.Index().OnTable("Episodes").OnColumn("TvDbEpisodeId").Unique(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs index 0e2136141..bfbf78a77 100644 --- a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs +++ b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs @@ -54,7 +54,7 @@ namespace NzbDrone.Core.Datastore.Migration using (IDbCommand updateCmd = conn.CreateCommand()) { - var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson() , seriesId); + var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson(), seriesId); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs index d7b8b31fc..daa6699bc 100644 --- a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs @@ -9,12 +9,12 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Update.Table("Indexers") - .Set(new {ConfigContract = "OmgwtfnzbsSettings"}) - .Where(new {Implementation = "Omgwtfnzbs"}); + .Set(new { ConfigContract = "OmgwtfnzbsSettings" }) + .Where(new { Implementation = "Omgwtfnzbs" }); Update.Table("Indexers") - .Set(new {Settings = "{}"}) - .Where(new {Implementation = "Omgwtfnzbs", Settings = (string) null}); + .Set(new { Settings = "{}" }) + .Where(new { Implementation = "Omgwtfnzbs", Settings = (string)null }); Update.Table("Indexers") .Set(new { Settings = "{}" }) diff --git a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs index 1bce60081..ca8c3e2c1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs @@ -53,7 +53,6 @@ namespace NzbDrone.Core.Datastore.Migration { seriesTitlePattern = "{Series.Title}"; } - else { seriesTitlePattern = "{Series Title}"; @@ -70,20 +69,21 @@ namespace NzbDrone.Core.Datastore.Migration { episodeTitlePattern += "{Episode.Title}"; } - else { episodeTitlePattern += "{Episode Title}"; } } - var standardEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - GetNumberStyle(numberStyle).Pattern, - episodeTitlePattern); + var standardEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + GetNumberStyle(numberStyle).Pattern, + episodeTitlePattern); - var dailyEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - dailyEpisodePattern, - episodeTitlePattern); + var dailyEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + dailyEpisodePattern, + episodeTitlePattern); if (includeQuality) { @@ -121,7 +121,6 @@ namespace NzbDrone.Core.Datastore.Migration Name = "1x05", Pattern = "{season}x{episode:00}", EpisodeSeparator = "x" - }, new { diff --git a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs index 670d1f8ab..edd93183b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs +++ b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs @@ -44,8 +44,8 @@ namespace NzbDrone.Core.Datastore.Migration var text = string.Format("UPDATE Notifications " + "SET Settings = '{0}'" + "WHERE Id = {1}", - settings.ToJson(), id - ); + settings.ToJson(), + id); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs index e98e667a8..f7d3cf386 100644 --- a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs +++ b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs @@ -1,12 +1,12 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; +using System.Collections.Generic; using System.Data; using System.Linq; +using FluentMigrator; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using System.Collections.Generic; -using NzbDrone.Core.Datastore.Converters; namespace NzbDrone.Core.Datastore.Migration { @@ -90,10 +90,10 @@ namespace NzbDrone.Core.Datastore.Migration } var qualityNewJson = qualityModelConverter.ToDB(new DestinationQualityModel036 - { - Quality = sourceQuality.Quality.Id, - Proper = sourceQuality.Proper - }); + { + Quality = sourceQuality.Quality.Id, + Proper = sourceQuality.Proper + }); using (IDbCommand updateCmd = conn.CreateCommand()) { diff --git a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs index 2e272db09..75f08ff34 100644 --- a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs +++ b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs @@ -1,7 +1,7 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; +using System.Data; using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Migration diff --git a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs index 505962776..62c3fb7c3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs +++ b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs @@ -48,21 +48,20 @@ namespace NzbDrone.Core.Datastore.Migration if (client.Equals("sabnzbd", StringComparison.InvariantCultureIgnoreCase)) { var settings = new ClientSettingsForMigration - { - Host = GetConfigValue(config, "SabHost", "localhost"), - Port = GetConfigValue(config, "SabPort", 8080), - ApiKey = GetConfigValue(config, "SabApiKey", ""), - Username = GetConfigValue(config, "SabUsername", ""), - Password = GetConfigValue(config, "SabPassword", ""), - TvCategory = GetConfigValue(config, "SabTvCategory", "tv"), - RecentTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Default")), - OlderTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Default")), - UseSsl = GetConfigValue(config, "SabUseSsl", false) - }; + { + Host = GetConfigValue(config, "SabHost", "localhost"), + Port = GetConfigValue(config, "SabPort", 8080), + ApiKey = GetConfigValue(config, "SabApiKey", ""), + Username = GetConfigValue(config, "SabUsername", ""), + Password = GetConfigValue(config, "SabPassword", ""), + TvCategory = GetConfigValue(config, "SabTvCategory", "tv"), + RecentTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Default")), + OlderTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Default")), + UseSsl = GetConfigValue(config, "SabUseSsl", false) + }; AddDownloadClient(conn, tran, "Sabnzbd", "Sabnzbd", settings.ToJson(), "SabnzbdSettings", 1); } - else if (client.Equals("nzbget", StringComparison.InvariantCultureIgnoreCase)) { var settings = new ClientSettingsForMigration @@ -78,17 +77,15 @@ namespace NzbDrone.Core.Datastore.Migration AddDownloadClient(conn, tran, "Nzbget", "Nzbget", settings.ToJson(), "NzbgetSettings", 1); } - else if (client.Equals("pneumatic", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration - { - Folder = GetConfigValue(config, "PneumaticFolder", "") - }; + { + Folder = GetConfigValue(config, "PneumaticFolder", "") + }; AddDownloadClient(conn, tran, "Pneumatic", "Pneumatic", settings.ToJson(), "FolderSettings", 1); } - else if (client.Equals("blackhole", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration @@ -108,14 +105,19 @@ namespace NzbDrone.Core.Datastore.Migration if (config.ContainsKey(key)) { - return (T) Convert.ChangeType(config[key], typeof (T)); + return (T)Convert.ChangeType(config[key], typeof(T)); } return defaultValue; } - private void AddDownloadClient(IDbConnection conn, IDbTransaction tran, string name, string implementation, string settings, - string configContract, int protocol) + private void AddDownloadClient(IDbConnection conn, + IDbTransaction tran, + string name, + string implementation, + string settings, + string configContract, + int protocol) { using (IDbCommand updateCmd = conn.CreateCommand()) { diff --git a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs index 4a2e94bbf..af5c7359c 100644 --- a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs index 8986a7fba..7f97ec993 100644 --- a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs +++ b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs index ff81b765e..2c314bd73 100644 --- a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs +++ b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs @@ -1,13 +1,13 @@ using System; -using System.Data; -using System.Linq; using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; using FluentMigrator; using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration.Framework; -using System.IO; namespace NzbDrone.Core.Datastore.Migration { @@ -148,15 +148,15 @@ namespace NzbDrone.Core.Datastore.Migration while (historyRead.Read()) { historyItems.Add(new MigrationHistoryItem - { - Id = historyRead.GetInt32(0), - EpisodeId = historyRead.GetInt32(1), - SeriesId = historyRead.GetInt32(2), - SourceTitle = historyRead.GetString(3), - Date = historyRead.GetDateTime(4), - Data = Json.Deserialize>(historyRead.GetString(5)), - EventType = (MigrationHistoryEventType)historyRead.GetInt32(6) - }); + { + Id = historyRead.GetInt32(0), + EpisodeId = historyRead.GetInt32(1), + SeriesId = historyRead.GetInt32(2), + SourceTitle = historyRead.GetString(3), + Date = historyRead.GetDateTime(4), + Data = Json.Deserialize>(historyRead.GetString(5)), + EventType = (MigrationHistoryEventType)historyRead.GetInt32(6) + }); } } } @@ -180,12 +180,19 @@ namespace NzbDrone.Core.Datastore.Migration for (int i = 0; i < list.Count - 1; i++) { var grabbedEvent = list[i]; - if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) continue; - if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) continue; + if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) + { + continue; + } + + if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) + { + continue; + } // Check if it is already associated with a failed/imported event. int j; - for (j = i + 1; j < list.Count;j++) + for (j = i + 1; j < list.Count; j++) { if (list[j].EventType != MigrationHistoryEventType.DownloadFolderImported && list[j].EventType != MigrationHistoryEventType.DownloadFailed) @@ -208,7 +215,10 @@ namespace NzbDrone.Core.Datastore.Migration } var importedEvent = list[i + 1]; - if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) continue; + if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) + { + continue; + } var droppedPath = importedEvent.Data.GetValueOrDefault("droppedPath"); if (droppedPath != null && new FileInfo(droppedPath).Directory.Name == grabbedEvent.SourceTitle) diff --git a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs index e781ca010..e0dba2496 100644 --- a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs +++ b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs b/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs index a1bf307fd..7fcd9c31d 100644 --- a/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs +++ b/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs @@ -14,7 +14,6 @@ namespace NzbDrone.Core.Datastore.Migration //TODO: Add unique contraint for series ID and Relative Path //TODO: Warn if multiple series share the same path - Execute.WithConnection(UpdateRelativePaths); } diff --git a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs index cc9cea68a..0087345db 100644 --- a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs +++ b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs @@ -46,7 +46,10 @@ namespace NzbDrone.Core.Datastore.Migration var newQualityModel = new QualityModel062 { Quality = quality.Quality, Revision = new Revision() }; if (quality.Proper) + { newQualityModel.Revision.Version = 2; + } + var newQualityJson = newQualityModel.ToJson(); qualitiesToUpdate.Add(qualityJson, newQualityJson); diff --git a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs index 9db5f2955..6185e0fd1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs @@ -60,7 +60,7 @@ namespace NzbDrone.Core.Datastore.Migration foreach (Match match in matches) { var tokenMatch = GetTokenMatch(match); - var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); ; + var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t))) { @@ -80,12 +80,12 @@ namespace NzbDrone.Core.Datastore.Migration private TokenMatch69 GetTokenMatch(Match match) { return new TokenMatch69 - { - Prefix = match.Groups["prefix"].Value, - Token = match.Groups["token"].Value, - Separator = match.Groups["separator"].Value, - Suffix = match.Groups["suffix"].Value, - }; + { + Prefix = match.Groups["prefix"].Value, + Token = match.Groups["token"].Value, + Separator = match.Groups["separator"].Value, + Suffix = match.Groups["suffix"].Value, + }; } private class TokenMatch69 diff --git a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs index 11c92ce0c..e77f5f9f7 100644 --- a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs @@ -24,15 +24,15 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("Tags").AsString().NotNullable(); Insert.IntoTable("DelayProfiles").Row(new - { - EnableUsenet = 1, - EnableTorrent = 1, - PreferredProtocol = 1, - UsenetDelay = 0, - TorrentDelay = 0, - Order = int.MaxValue, - Tags = "[]" - }); + { + EnableUsenet = 1, + EnableTorrent = 1, + PreferredProtocol = 1, + UsenetDelay = 0, + TorrentDelay = 0, + Order = int.MaxValue, + Tags = "[]" + }); Execute.WithConnection(ConvertProfile); @@ -48,7 +48,10 @@ namespace NzbDrone.Core.Datastore.Migration foreach (var profileClosure in profiles.DistinctBy(p => p.GrabDelay)) { var profile = profileClosure; - if (profile.GrabDelay == 0) continue; + if (profile.GrabDelay == 0) + { + continue; + } var tag = string.Format("delay-{0}", profile.GrabDelay); var tagId = InsertTag(conn, tran, tag); diff --git a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs index 6421f1ecb..ab500282b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs @@ -24,6 +24,7 @@ namespace NzbDrone.Core.Datastore.Migration updater.Commit(); } } + public class Profile70 { public int Id { get; set; } @@ -88,7 +89,10 @@ namespace NzbDrone.Core.Datastore.Migration { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Insert(0, new ProfileItem70 { @@ -104,7 +108,10 @@ namespace NzbDrone.Core.Datastore.Migration { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Add(new ProfileItem70 { @@ -120,7 +127,10 @@ namespace NzbDrone.Core.Datastore.Migration { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); @@ -143,7 +153,10 @@ namespace NzbDrone.Core.Datastore.Migration { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); @@ -171,7 +184,7 @@ namespace NzbDrone.Core.Datastore.Migration { int id = definitionsReader.GetInt32(0); int quality = definitionsReader.GetInt32(1); - definitions.Add(new QualityDefinition70 {Id = id, Quality = quality}); + definitions.Add(new QualityDefinition70 { Id = id, Quality = quality }); } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs index 23523808f..40eece1a0 100644 --- a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs +++ b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs @@ -57,7 +57,6 @@ namespace NzbDrone.Core.Datastore.Migration updateHistoryCmd.AddParameter(id); updateHistoryCmd.ExecuteNonQuery(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs index ef9c4074f..b1b547b60 100644 --- a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Update.Table("Series") - .Set(new {Ratings = "{}"}) + .Set(new { Ratings = "{}" }) .AllRows(); Update.Table("Episodes") diff --git a/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs b/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs index b786747a2..6b753635a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs +++ b/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs @@ -85,10 +85,10 @@ namespace NzbDrone.Core.Datastore.Migration var tags = tagReader.GetString(1); tagged.Add(new TaggedModel079 - { - Id = id, - Tags = Json.Deserialize>(tags) - }); + { + Id = id, + Tags = Json.Deserialize>(tags) + }); } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs index 4855c6a3d..8ef73a2e4 100644 --- a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs +++ b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs @@ -7,7 +7,9 @@ using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(85)] public class expand_transmission_urlbase : NzbDroneMigrationBase diff --git a/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs b/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs index 1e7cced76..9d1962616 100644 --- a/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs +++ b/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs @@ -8,7 +8,9 @@ using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(86)] public class pushbullet_device_ids : NzbDroneMigrationBase diff --git a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs index e4760fe79..cd55fb831 100644 --- a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs +++ b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs @@ -8,7 +8,9 @@ using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(88)] public class pushbullet_devices_channels_list : NzbDroneMigrationBase @@ -51,7 +53,7 @@ namespace NzbDrone.Core.Datastore.Migration if (channelTagsString.IsNotNullOrWhiteSpace()) { - var channelTags = channelTagsString.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); + var channelTags = channelTagsString.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); settings["channelTags"] = channelTags; } diff --git a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs index ec96f48dc..bc22b3258 100644 --- a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs +++ b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs @@ -12,8 +12,7 @@ namespace NzbDrone.Core.Datastore.Migration Execute.Sql( "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.so', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.to', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + - "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';" - ); + "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';"); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs b/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs index f192b7709..29c230481 100644 --- a/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs @@ -20,8 +20,6 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("RelativePath").AsString().Nullable(); Alter.Table("Movies").AddColumn("MovieFileId").AsInt32().WithDefaultValue(0); - - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs b/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs index 786977b2c..ca7f447a5 100644 --- a/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs @@ -1,6 +1,6 @@ -using FluentMigrator; +using System.Data; +using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; namespace NzbDrone.Core.Datastore.Migration { @@ -17,14 +17,12 @@ namespace NzbDrone.Core.Datastore.Migration private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { - using (IDbCommand namingConfigCmd = conn.CreateCommand()) { namingConfigCmd.Transaction = tran; namingConfigCmd.CommandText = @"SELECT * FROM NamingConfig LIMIT 1"; using (IDataReader namingConfigReader = namingConfigCmd.ExecuteReader()) { - while (namingConfigReader.Read()) { // Output Settings @@ -34,13 +32,10 @@ namespace NzbDrone.Core.Datastore.Migration movieTitlePattern = "{Movie Title}"; - var standardMovieFormat = string.Format("{0} {1} {2}", movieTitlePattern, - movieYearPattern, - qualityFormat); + var standardMovieFormat = string.Format("{0} {1} {2}", movieTitlePattern, movieYearPattern, qualityFormat); var movieFolderFormat = string.Format("{0} {1}", movieTitlePattern, movieYearPattern); - using (IDbCommand updateCmd = conn.CreateCommand()) { var text = string.Format("UPDATE NamingConfig " + diff --git a/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs b/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs index b4412bb32..e1f9a7e83 100644 --- a/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs @@ -9,10 +9,6 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Alter.Table("Movies").AddColumn("PhysicalRelease").AsDateTime().Nullable(); - } - - - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs b/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs index ba5ed3045..6e157b9bc 100644 --- a/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs +++ b/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs @@ -10,6 +10,7 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Create.Column("Edition").OnTable("MovieFiles").AsString().Nullable(); + //Execute.WithConnection(SetSortTitles); } diff --git a/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs b/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs index 5b1ee7f6b..a8ea90163 100644 --- a/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs +++ b/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs @@ -9,8 +9,6 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Alter.Table("Movies").AddColumn("YouTubeTrailerId").AsString().Nullable(); - } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs b/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs index f5c4dc36e..202005901 100644 --- a/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs @@ -10,6 +10,5 @@ namespace NzbDrone.Core.Datastore.Migration { Alter.Table("Movies").AddColumn("Studio").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs b/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs index 0e548b723..8478360bd 100644 --- a/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs @@ -1,8 +1,8 @@ using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; using System.Text; using System.Text.RegularExpressions; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs b/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs index 8f6ebb9e2..f0002017f 100644 --- a/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs +++ b/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs @@ -12,6 +12,5 @@ namespace NzbDrone.Core.Datastore.Migration Alter.Table("Blacklist").AlterColumn("SeriesId").AsInt32().Nullable(); Alter.Table("Blacklist").AlterColumn("EpisodeIds").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs b/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs index 86a602917..91af60e36 100644 --- a/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Datastore.Migration { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("NetImport").Exists()) + if (!Schema.Schema("dbo").Table("NetImport").Exists()) { Create.TableForModel("NetImport") .WithColumn("Enabled").AsBoolean() diff --git a/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs b/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs index 3ab1c2641..aa7133479 100644 --- a/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs @@ -10,6 +10,5 @@ namespace NzbDrone.Core.Datastore.Migration { Alter.Table("Profiles").AddColumn("PreferredTags").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs b/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs index 1b6f4b3f3..fdbcdcd06 100644 --- a/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs +++ b/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs @@ -1,6 +1,6 @@ -using FluentMigrator; +using System.Data; +using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; namespace NzbDrone.Core.Datastore.Migration { @@ -22,6 +22,5 @@ namespace NzbDrone.Core.Datastore.Migration getSeriesCmd.ExecuteNonQuery(); } } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs b/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs index 84909dd6c..b162040f8 100644 --- a/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs +++ b/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs @@ -1,4 +1,5 @@ using FluentMigrator; + //using FluentMigrator.Expressions; using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Movies; @@ -10,11 +11,12 @@ namespace NzbDrone.Core.Datastore.Migration { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("NetImport").Column("MinimumAvailability").Exists()) + if (!Schema.Schema("dbo").Table("NetImport").Column("MinimumAvailability").Exists()) { Alter.Table("NetImport").AddColumn("MinimumAvailability").AsInt32().WithDefaultValue(MovieStatusType.PreDB); } - if (!this.Schema.Schema("dbo").Table("Movies").Column("MinimumAvailability").Exists()) + + if (!Schema.Schema("dbo").Table("Movies").Column("MinimumAvailability").Exists()) { Alter.Table("Movies").AddColumn("MinimumAvailability").AsInt32().WithDefaultValue(MovieStatusType.PreDB); } diff --git a/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs b/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs index 2e1be0307..25b68583a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs @@ -1,10 +1,10 @@ using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; +using System.Globalization; using System.Linq; using System.Text.RegularExpressions; -using System.Globalization; +using FluentMigrator; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { @@ -13,13 +13,14 @@ namespace NzbDrone.Core.Datastore.Migration { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("ImportExclusions").Exists()) + if (!Schema.Schema("dbo").Table("ImportExclusions").Exists()) { Create.TableForModel("ImportExclusions") .WithColumn("TmdbId").AsInt64().NotNullable().Unique().PrimaryKey() .WithColumn("MovieTitle").AsString().Nullable() .WithColumn("MovieYear").AsInt64().Nullable().WithDefaultValue(0); } + Execute.WithConnection(AddExisting); } @@ -34,12 +35,14 @@ namespace NzbDrone.Core.Datastore.Migration { while (seriesReader.Read()) { - var Key = seriesReader.GetString(0); - var Value = seriesReader.GetString(1); + var key = seriesReader.GetString(0); + var value = seriesReader.GetString(1); - var importExclusions = Value.Split(',').Select(x => { - return string.Format("(\"{0}\", \"{1}\")", Regex.Replace(x, @"^.*\-(.*)$", "$1"), - textInfo.ToTitleCase(string.Join(" ", x.Split('-').DropLast(1)))); + var importExclusions = value.Split(',').Select(x => + { + return string.Format("(\"{0}\", \"{1}\")", + Regex.Replace(x, @"^.*\-(.*)$", "$1"), + textInfo.ToTitleCase(string.Join(" ", x.Split('-').DropLast(1)))); }).ToList(); using (IDbCommand updateCmd = conn.CreateCommand()) diff --git a/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs b/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs index 64f9dd009..55712d9bf 100644 --- a/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Datastore.Migration { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("alternative_titles").Exists()) + if (!Schema.Schema("dbo").Table("alternative_titles").Exists()) { Create.TableForModel("AlternativeTitles") .WithColumn("MovieId").AsInt64().NotNullable() diff --git a/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs b/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs index faaa8424e..dd09aa4a6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs +++ b/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.Datastore.Migration cmd.CommandText = "DELETE FROM AlternativeTitles WHERE rowid NOT IN ( SELECT MIN(rowid) FROM AlternativeTitles GROUP BY CleanTitle )"; cmd.ExecuteNonQuery(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs b/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs index fb90202d9..71a182e76 100644 --- a/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs +++ b/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Datastore.Migration { Alter.Table("IndexerStatus").AddColumn("Cookies").AsString().Nullable() .AddColumn("CookiesExpirationDate").AsDateTime().Nullable(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs b/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs index af13aeefe..d122b43d3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs +++ b/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.Datastore.Migration private void AddCustomFormatsToProfile(IDbConnection conn, IDbTransaction tran) { - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs b/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs index ab006cb91..18ba36813 100644 --- a/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs +++ b/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs @@ -25,10 +25,26 @@ namespace NzbDrone.Core.Datastore.Migration updater.ReplaceInTags(OriginalRegex, match => { var modifiers = ""; - if (match.Groups["m_n"].Success) modifiers += "N"; - if (match.Groups["m_r"].Success) modifiers += "RX"; - if (match.Groups["m_re"].Success) modifiers += "RQ"; - if (modifiers != "") modifiers = "_" + modifiers; + if (match.Groups["m_n"].Success) + { + modifiers += "N"; + } + + if (match.Groups["m_r"].Success) + { + modifiers += "RX"; + } + + if (match.Groups["m_re"].Success) + { + modifiers += "RQ"; + } + + if (modifiers != "") + { + modifiers = "_" + modifiers; + } + return $"{match.Groups["type"].Value}{modifiers}_{match.Groups["value"].Value}"; }); diff --git a/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs b/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs index 4013e3d19..a5a7d66de 100644 --- a/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs +++ b/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs @@ -1,16 +1,18 @@ -using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Languages; using System; using System.Collections.Generic; +using System.Data; using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; +using NzbDrone.Core.Languages; namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(154)] public class add_language_to_files_history_blacklist : NzbDroneMigrationBase @@ -31,7 +33,7 @@ namespace NzbDrone.Core.Datastore.Migration private void UpdateLanguage(IDbConnection conn, IDbTransaction tran) { - var LanguageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); + var languageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); var profileLanguages = new Dictionary(); using (IDbCommand getProfileCmd = conn.CreateCommand()) @@ -77,7 +79,7 @@ namespace NzbDrone.Core.Datastore.Migration foreach (var group in movieLanguages.GroupBy(v => v.Value, v => v.Key)) { - var languageJson = LanguageConverter.ToDB(new List { Language.FindById(group.Key) }); + var languageJson = languageConverter.ToDB(new List { Language.FindById(group.Key) }); var movieIds = group.Select(v => v.ToString()).Join(","); diff --git a/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs b/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs index fd08c8631..8d7349b5d 100644 --- a/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs +++ b/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Datastore.Migration { Alter.Table("DownloadClients").AddColumn("Priority").AsInt32().WithDefaultValue(1); Execute.WithConnection(InitPriorityForBackwardCompatibility); - } private void InitPriorityForBackwardCompatibility(IDbConnection conn, IDbTransaction tran) diff --git a/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs b/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs index effa7b520..fc5f120e7 100644 --- a/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs +++ b/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs @@ -20,10 +20,10 @@ namespace NzbDrone.Core.Datastore.Migration { var updater = new ProfileUpdater159(conn, tran); - updater.CreateGroupAt(8, "WEB 480p", new int[]{12}); // Group WEBRip480p with WEBDL480p - updater.CreateGroupAt(5, "WEB 720p", new int[]{14}); // Group WEBRip720p with WEBDL720p - updater.CreateGroupAt(3, "WEB 1080p", new int[]{15}); // Group WEBRip1080p with WEBDL1080p - updater.CreateGroupAt(18, "WEB 2160p", new int[]{17}); // Group WEBRip2160p with WEBDL2160p + updater.CreateGroupAt(8, "WEB 480p", new int[] { 12 }); // Group WEBRip480p with WEBDL480p + updater.CreateGroupAt(5, "WEB 720p", new int[] { 14 }); // Group WEBRip720p with WEBDL720p + updater.CreateGroupAt(3, "WEB 1080p", new int[] { 15 }); // Group WEBRip1080p with WEBDL1080p + updater.CreateGroupAt(18, "WEB 2160p", new int[] { 17 }); // Group WEBRip2160p with WEBDL2160p updater.Commit(); } @@ -108,7 +108,6 @@ namespace NzbDrone.Core.Datastore.Migration } } - var findIndex = profile.Items.FindIndex(v => { return v.Quality == find || (v.Items != null && v.Items.Any(b => b.Quality == find)); @@ -116,7 +115,6 @@ namespace NzbDrone.Core.Datastore.Migration var isGrouped = !profile.Items.Any(p => p.Quality == find); - if (findIndex > -1 && !isGrouped) { var findQuality = profile.Items[findIndex]; @@ -163,7 +161,6 @@ namespace NzbDrone.Core.Datastore.Migration else { // If the ID isn't found for some reason (mangled migration 71?) - var groupItems = new List(); foreach (var newQuality in newQualities) diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs index b90d3de7c..e49b7b493 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs @@ -42,10 +42,11 @@ namespace NzbDrone.Core.Datastore.Migration.Framework .WithGlobalConnectionString(connectionString) .WithMigrationsIn(Assembly.GetExecutingAssembly())) .Configure(opt => opt.Namespace = "NzbDrone.Core.Datastore.Migration") - .Configure(opt => { - opt.PreviewOnly = false; - opt.Timeout = TimeSpan.FromSeconds(60); - }) + .Configure(opt => + { + opt.PreviewOnly = false; + opt.Timeout = TimeSpan.FromSeconds(60); + }) .BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs index e6ad4dd52..57b984c5a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs @@ -38,7 +38,9 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { var table = new TableDefinition(); - while (reader.Read() != SqliteSyntaxReader.TokenType.StringToken || reader.ValueToUpper != "TABLE") ; + while (reader.Read() != SqliteSyntaxReader.TokenType.StringToken || reader.ValueToUpper != "TABLE") + { + } if (reader.Read() == SqliteSyntaxReader.TokenType.StringToken && reader.ValueToUpper == "IF") { @@ -114,7 +116,10 @@ namespace NzbDrone.Core.Datastore.Migration.Framework reader.Read(); index.IsUnique = reader.ValueToUpper == "UNIQUE"; - while (reader.ValueToUpper != "INDEX") reader.Read(); + while (reader.ValueToUpper != "INDEX") + { + reader.Read(); + } if (reader.Read() == SqliteSyntaxReader.TokenType.StringToken && reader.ValueToUpper == "IF") { @@ -175,22 +180,19 @@ namespace NzbDrone.Core.Datastore.Migration.Framework return reader.Value; } - #region ISchemaDumper Members - public virtual IList ReadDbSchema() { IList tables = ReadTables(); foreach (var table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); + //table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables; } - #endregion - protected virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); @@ -210,6 +212,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework tableDefinitionList.Add(table); } + return tableDefinitionList; } @@ -252,6 +255,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework var index = ReadIndexSchema(sql); indexes.Add(index); } + return indexes; } } diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs index b2556fee1..6c76fbdc1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs @@ -5,7 +5,6 @@ using System.Text; namespace NzbDrone.Core.Datastore.Migration.Framework { - public class SqliteSyntaxReader { public string Buffer { get; private set; } @@ -48,18 +47,25 @@ namespace NzbDrone.Core.Datastore.Migration.Framework public void SkipWhitespace() { - while (!IsEndOfFile && char.IsWhiteSpace(Buffer[Index])) Index++; + while (!IsEndOfFile && char.IsWhiteSpace(Buffer[Index])) + { + Index++; + } } public void SkipTillToken(TokenType tokenType) { if (IsEndOfFile) + { return; + } while (Read() != tokenType) { if (Type == TokenType.ListStart) + { SkipTillToken(TokenType.ListEnd); + } } } @@ -148,7 +154,10 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { var start = Index; var end = start + 1; - while (end < Buffer.Length && (char.IsLetter(Buffer[end]) || char.IsNumber(Buffer[end]) || Buffer[end] == '_' || Buffer[end] == '(')) end++; + while (end < Buffer.Length && (char.IsLetter(Buffer[end]) || char.IsNumber(Buffer[end]) || Buffer[end] == '_' || Buffer[end] == '(')) + { + end++; + } if (end >= Buffer.Length || Buffer[end] == ',' || Buffer[end] == ')' || char.IsWhiteSpace(Buffer[end])) { @@ -164,6 +173,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { throw CreateSyntaxException("Unexpected sequence."); } + Type = TokenType.StringToken; Value = Buffer.Substring(start, end - start); return Type; @@ -191,6 +201,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { throw CreateSyntaxException("Expected ListEnd first"); } + if (Type == TokenType.ListStart) { SkipTillToken(TokenType.ListEnd); @@ -215,7 +226,10 @@ namespace NzbDrone.Core.Datastore.Migration.Framework var start = Index + 1; var end = Buffer.IndexOf(terminator, Index); - if (end == -1) throw new SyntaxErrorException(); + if (end == -1) + { + throw new SyntaxErrorException(); + } Index = end + 1; return Buffer.Substring(start, end - start); @@ -230,12 +244,18 @@ namespace NzbDrone.Core.Datastore.Migration.Framework var start = Index + 1; var end = Buffer.IndexOf(escape, start); - if (end == -1) throw new SyntaxErrorException(); + if (end == -1) + { + throw new SyntaxErrorException(); + } Index = end + 1; identifier.Append(Buffer.Substring(start, end - start)); - if (Buffer[Index] != escape) break; + if (Buffer[Index] != escape) + { + break; + } identifier.Append(escape); } diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs index 1a680f0d8..0e7d78f13 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs @@ -1,5 +1,3 @@ -#region License -// // Copyright (c) 2007-2009, Sean Chambers // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/NzbDrone.Core/Datastore/ModelConflictException.cs b/src/NzbDrone.Core/Datastore/ModelConflictException.cs index b9e5687be..f313e3444 100644 --- a/src/NzbDrone.Core/Datastore/ModelConflictException.cs +++ b/src/NzbDrone.Core/Datastore/ModelConflictException.cs @@ -8,13 +8,11 @@ namespace NzbDrone.Core.Datastore public ModelConflictException(Type modelType, int modelId) : base("{0} with ID {1} cannot be modified", modelType.Name, modelId) { - } public ModelConflictException(Type modelType, int modelId, string message) : base("{0} with ID {1} {2}", modelType.Name, modelId, message) { - } } } diff --git a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs index 6f889dfd7..b9ad28da9 100644 --- a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs +++ b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Datastore public ModelNotFoundException(Type modelType, int modelId) : base("{0} with ID {1} does not exist", modelType.Name, modelId) { - } } } diff --git a/src/NzbDrone.Core/Datastore/TableMapping.cs b/src/NzbDrone.Core/Datastore/TableMapping.cs index 4a8afc288..c033e6410 100644 --- a/src/NzbDrone.Core/Datastore/TableMapping.cs +++ b/src/NzbDrone.Core/Datastore/TableMapping.cs @@ -2,42 +2,42 @@ using System; using System.Collections.Generic; using Marr.Data; using Marr.Data.Mapping; +using NzbDrone.Common.Disk; using NzbDrone.Common.Reflection; +using NzbDrone.Core.Authentication; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFilters; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Datastore.Converters; using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Instrumentation; -using NzbDrone.Core.Jobs; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.Notifications; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Restrictions; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.Tags; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; -using NzbDrone.Common.Disk; -using NzbDrone.Core.Authentication; -using NzbDrone.Core.CustomFilters; -using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Instrumentation; +using NzbDrone.Core.Jobs; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.NetImport; using NzbDrone.Core.NetImport.ImportExclusions; -using NzbDrone.Core.Movies.AlternativeTitles; -using NzbDrone.Core.Languages; +using NzbDrone.Core.Notifications; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Restrictions; +using NzbDrone.Core.RootFolders; +using NzbDrone.Core.Tags; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Datastore { @@ -87,28 +87,27 @@ namespace NzbDrone.Core.Datastore Mapper.Entity().RegisterModel("History") .AutoMapChildModels(); - Mapper.Entity().RegisterModel("MovieFiles") - .Ignore(f => f.Path) - .Relationships.AutoMapICollectionOrComplexProperties() - .For("Movie") - .LazyLoad(condition: parent => parent.Id > 0, - query: (db, parent) => db.Query().Where(c => c.MovieFileId == parent.Id).ToList()) - .HasOne(file => file.Movie, file => file.MovieId); + Mapper.Entity().RegisterModel("MovieFiles") + .Ignore(f => f.Path) + .Relationships.AutoMapICollectionOrComplexProperties() + .For("Movie") + .LazyLoad(condition: parent => parent.Id > 0, + query: (db, parent) => db.Query().Where(c => c.MovieFileId == parent.Id).ToList()) + .HasOne(file => file.Movie, file => file.MovieId); Mapper.Entity().RegisterModel("Movies") .Ignore(s => s.RootFolderPath) .Ignore(m => m.Actors) .Relationship() .HasOne(s => s.Profile, s => s.ProfileId); - //.HasOne(m => m.MovieFile, m => m.MovieFileId); + //.HasOne(m => m.MovieFile, m => m.MovieFileId); Mapper.Entity().RegisterModel("AlternativeTitles") .For(t => t.Id) .SetAltName("AltTitle_Id") .Relationship() .HasOne(t => t.Movie, t => t.MovieId); - Mapper.Entity().RegisterModel("ImportExclusions"); Mapper.Entity().RegisterModel("QualityDefinitions") diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs index a4e171dff..b1f0213d9 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.DecisionEngine @@ -74,7 +74,7 @@ namespace NzbDrone.Core.DecisionEngine var right = y.RemoteMovie.ParsedMovieInfo.Quality.CustomFormats; var leftIndicies = QualityModelComparer.GetIndicies(left, x.RemoteMovie.Movie.Profile.Value); - var rightIndicies = QualityModelComparer.GetIndicies(right, y.RemoteMovie.Movie.Profile.Value); + var rightIndicies = QualityModelComparer.GetIndicies(right, y.RemoteMovie.Movie.Profile.Value); var leftTotal = leftIndicies.Sum(); var rightTotal = rightIndicies.Sum(); @@ -98,7 +98,6 @@ namespace NzbDrone.Core.DecisionEngine var num = preferredWords.AsEnumerable().Count(w => title.ToLower().Contains(w.ToLower())); return num; - }); } @@ -189,7 +188,6 @@ namespace NzbDrone.Core.DecisionEngine private int CompareSize(DownloadDecision x, DownloadDecision y) { // TODO: Is smaller better? Smaller for usenet could mean no par2 files. - return CompareBy(x.RemoteMovie, y.RemoteMovie, remoteEpisode => remoteEpisode.Release.Size.Round(200.Megabytes())); } diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs index 88ad820a9..ab4cbeead 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs @@ -6,12 +6,12 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Common.Serializer; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.DecisionEngine { @@ -30,8 +30,10 @@ namespace NzbDrone.Core.DecisionEngine private readonly Logger _logger; public DownloadDecisionMaker(IEnumerable specifications, - IParsingService parsingService, IConfigService configService, - IQualityDefinitionService qualityDefinitionService, Logger logger) + IParsingService parsingService, + IConfigService configService, + IQualityDefinitionService qualityDefinitionService, + Logger logger) { _specifications = specifications; _parsingService = parsingService; @@ -56,7 +58,6 @@ namespace NzbDrone.Core.DecisionEngine { _logger.ProgressInfo("Processing {0} releases", reports.Count); } - else { _logger.ProgressInfo("No results found"); @@ -71,8 +72,7 @@ namespace NzbDrone.Core.DecisionEngine try { - - var parsedMovieInfo = _parsingService.ParseMovieInfo(report.Title, new List{report}); + var parsedMovieInfo = _parsingService.ParseMovieInfo(report.Title, new List { report }); MappingResult result = null; @@ -83,7 +83,7 @@ namespace NzbDrone.Core.DecisionEngine { MovieTitle = report.Title, Year = 1290, - Languages = new List{Language.Unknown}, + Languages = new List { Language.Unknown }, Quality = new QualityModel(), }; @@ -94,11 +94,10 @@ namespace NzbDrone.Core.DecisionEngine if (result == null || result.MappingResultType != MappingResultType.SuccessLenientMapping) { - result = new MappingResult {MappingResultType = MappingResultType.NotParsable}; + result = new MappingResult { MappingResultType = MappingResultType.NotParsable }; result.Movie = null; //To ensure we have a remote movie, else null exception on next line! result.RemoteMovie.ParsedMovieInfo = parsedMovieInfo; } - } else { @@ -115,7 +114,6 @@ namespace NzbDrone.Core.DecisionEngine { var rejection = result.ToRejection(); decision = new DownloadDecision(remoteMovie, rejection); - } else { @@ -146,7 +144,6 @@ namespace NzbDrone.Core.DecisionEngine remoteMovie.DownloadAllowed = remoteMovie.Movie != null; decision = GetDecisionForReport(remoteMovie, searchCriteria); } - } } catch (Exception e) @@ -165,7 +162,6 @@ namespace NzbDrone.Core.DecisionEngine { _logger.Debug("Release rejected for the following reasons: {0}", string.Join(", ", decision.Rejections)); } - else { _logger.Debug("Release accepted"); diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs index 3b3acbb72..163ff7a9f 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs @@ -1,8 +1,8 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Parser; +using NzbDrone.Core.Profiles.Delay; namespace NzbDrone.Core.DecisionEngine { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs index 98e7237f4..f7a50c41c 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs @@ -56,6 +56,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Reject("{0} is smaller than minimum allowed {1} (for {2})", subject.Release.Size.SizeSuffix(), minSize.SizeSuffix(), runtimeMessage); } } + if (!qualityDefinition.MaxSize.HasValue || qualityDefinition.MaxSize.Value == 0) { _logger.Debug("Max size is unlimited - skipping check."); @@ -69,8 +70,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications //If the parsed size is greater than maxSize we don't want it if (subject.Release.Size > maxSize) - {; - + { _logger.Debug("Item: {0}, Size: {1} is greater than maximum allowed size ({2} for {3}), rejecting.", subject, subject.Release.Size, maxSize, subject.Movie.Title); return Decision.Reject("{0} is larger than maximum allowed {1} (for {2})", subject.Release.Size.SizeSuffix(), maxSize.SizeSuffix(), subject.Movie.Title); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs index 595b9fb3c..5492ea2f4 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs @@ -86,9 +86,8 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } } - // Only based on title because a release with the same title on another indexer/released at + // Only based on title because a release with the same title on another indexer/released at // a different time very likely has the exact same content and we don't need to also try it. - if (release.Title.Equals(lastGrabbed.SourceTitle, StringComparison.InvariantCultureIgnoreCase)) { _logger.Debug("Has same release name as a grabbed and imported release"); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs index c0138c3cb..eb74b5023 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCriteria) { - if (_blacklistService.Blacklisted(subject.Movie.Id, subject.Release)) { _logger.Debug("{0} is blacklisted, rejecting.", subject.Release.Title); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs index d21cb6efc..53e228de0 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs @@ -38,7 +38,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Accept(); } - _logger.Debug("Checking if report meets minimum age requirements. {0}", ageRounded); if (age < minimumAge) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs index 7edb8c150..55e6b3cb5 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCriteria) { - var queue = _queueService.GetQueue(); var matchingMovies = queue.Where(q => q.RemoteMovie?.Movie != null && q.RemoteMovie.Movie.Id == subject.Movie.Id) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs index f75c22d94..c19181eb1 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs @@ -50,10 +50,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications { _logger.Debug( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); return Decision.Reject( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); } } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs index 34b720930..91a682fd6 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs @@ -25,9 +25,9 @@ namespace NzbDrone.Core.DecisionEngine.Specifications { var torrentInfo = subject.Release; - IIndexerSettings indexerSettings = null; - try { + try + { indexerSettings = _indexerFactory.Get(subject.Release.IndexerId)?.Settings as IIndexerSettings; } catch (Exception) @@ -43,7 +43,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications if (indexerSettings is ITorrentIndexerSettings torrentIndexerSettings) { var requiredFlags = torrentIndexerSettings.RequiredFlags; - var requiredFlag = (IndexerFlags) 0; + var requiredFlag = (IndexerFlags)0; if (requiredFlags == null || !requiredFlags.Any()) { @@ -56,6 +56,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications { return Decision.Accept(); } + requiredFlag |= (IndexerFlags)flag; } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs index 44d1c137b..704145dbb 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs @@ -1,7 +1,7 @@ using NLog; +using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { @@ -29,6 +29,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync return Decision.Accept(); } } + if (!subject.Movie.IsAvailable(_settingsService.AvailabilityDelay)) { return Decision.Reject("Movie {0} will only be considered available {1} days after {2}", subject.Movie, _settingsService.AvailabilityDelay, subject.Movie.MinimumAvailability.ToString()); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs index 77ea89651..acfe1c058 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs @@ -67,32 +67,30 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync if (isPreferredProtocol && (subject.Movie.MovieFileId != 0 && subject.Movie.MovieFile != null) && (preferredCount > 0 || preferredWords == null)) { - var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); + var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); - if (upgradable) + if (upgradable) + { + var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); + + if (revisionUpgrade) { - var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); - - if (revisionUpgrade) - { - _logger.Debug("New quality is a better revision for existing quality and preferred word count is {0}, skipping delay", preferredCount); - return Decision.Accept(); - } + _logger.Debug("New quality is a better revision for existing quality and preferred word count is {0}, skipping delay", preferredCount); + return Decision.Accept(); } - + } } // If quality meets or exceeds the best allowed quality in the profile accept it immediately var bestQualityInProfile = profile.LastAllowedQuality(); var isBestInProfile = comparer.Compare(subject.ParsedMovieInfo.Quality.Quality, bestQualityInProfile) >= 0; - if (isBestInProfile && isPreferredProtocol && (preferredCount > 0 || preferredWords == null)) + if (isBestInProfile && isPreferredProtocol && (preferredCount > 0 || preferredWords == null)) { _logger.Debug("Quality is highest in profile for preferred protocol and preferred word count is {0}, will not delay.", preferredCount); return Decision.Accept(); } - var oldest = _pendingReleaseService.OldestPendingRelease(subject.Movie.Id); if (oldest != null && oldest.Release.AgeMinutes > delay) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs index 09f451572..eefe79c6d 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs @@ -39,42 +39,41 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync var cdhEnabled = _configService.EnableCompletedDownloadHandling; - _logger.Debug("Performing history status check on report"); - _logger.Debug("Checking current status of movie [{0}] in history", subject.Movie.Id); - var mostRecent = _historyService.MostRecentForMovie(subject.Movie.Id); + _logger.Debug("Performing history status check on report"); + _logger.Debug("Checking current status of movie [{0}] in history", subject.Movie.Id); + var mostRecent = _historyService.MostRecentForMovie(subject.Movie.Id); - if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) + if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) + { + var recent = mostRecent.Date.After(DateTime.UtcNow.AddHours(-12)); + var cutoffUnmet = _qualityUpgradableSpecification.CutoffNotMet(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); + var upgradeable = _qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); + + if (!recent && cdhEnabled) { - var recent = mostRecent.Date.After(DateTime.UtcNow.AddHours(-12)); - var cutoffUnmet = _qualityUpgradableSpecification.CutoffNotMet(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); - var upgradeable = _qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); - - if (!recent && cdhEnabled) - { - return Decision.Accept(); - } - - if (!cutoffUnmet) - { - if (recent) - { - return Decision.Reject("Recent grab event in history already meets cutoff: {0}", mostRecent.Quality); - } - - return Decision.Reject("CDH is disabled and grab event in history already meets cutoff: {0}", mostRecent.Quality); - } - - if (!upgradeable) - { - if (recent) - { - return Decision.Reject("Recent grab event in history is of equal or higher quality: {0}", mostRecent.Quality); - } - - return Decision.Reject("CDH is disabled and grab event in history is of equal or higher quality: {0}", mostRecent.Quality); - } + return Decision.Accept(); } + if (!cutoffUnmet) + { + if (recent) + { + return Decision.Reject("Recent grab event in history already meets cutoff: {0}", mostRecent.Quality); + } + + return Decision.Reject("CDH is disabled and grab event in history already meets cutoff: {0}", mostRecent.Quality); + } + + if (!upgradeable) + { + if (recent) + { + return Decision.Reject("Recent grab event in history is of equal or higher quality: {0}", mostRecent.Quality); + } + + return Decision.Reject("CDH is disabled and grab event in history is of equal or higher quality: {0}", mostRecent.Quality); + } + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs index 3cd8af9a6..7f22ed761 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs @@ -36,21 +36,20 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync var file = subject.Movie.MovieFile; - if (_qualityUpgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedMovieInfo.Quality)) + if (_qualityUpgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedMovieInfo.Quality)) + { + if (file.DateAdded < DateTime.Today.AddDays(-7)) { - if (file.DateAdded < DateTime.Today.AddDays(-7)) - { - _logger.Debug("Proper for old file, rejecting: {0}", subject); - return Decision.Reject("Proper for old file"); - } - - if (!_configService.AutoDownloadPropers) - { - _logger.Debug("Auto downloading of propers is disabled"); - return Decision.Reject("Proper downloading is disabled"); - } + _logger.Debug("Proper for old file, rejecting: {0}", subject); + return Decision.Reject("Proper for old file"); } + if (!_configService.AutoDownloadPropers) + { + _logger.Debug("Auto downloading of propers is disabled"); + return Decision.Reject("Proper downloading is disabled"); + } + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs index b91283861..dcedb23db 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs @@ -66,7 +66,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } return false; - } public bool IsRevisionUpgrade(QualityModel currentQuality, QualityModel newQuality) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs index b183f2426..8dfb6eae7 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs @@ -26,13 +26,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } var file = subject.Movie.MovieFile; - _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality); - - if (!_qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, file.Quality, subject.ParsedMovieInfo.Quality)) - { - return Decision.Reject("Quality for existing file on disk is of equal or higher preference: {0}", file.Quality); - } + _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality); + if (!_qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, file.Quality, subject.ParsedMovieInfo.Quality)) + { + return Decision.Reject("Quality for existing file on disk is of equal or higher preference: {0}", file.Quality); + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs index 63402605c..3a6395b69 100644 --- a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs +++ b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.RegularExpressions; using NLog; @@ -73,11 +73,11 @@ namespace NzbDrone.Core.DiskSpace } diskSpace = new DiskSpace - { - Path = path, - FreeSpace = freeSpace.Value, - TotalSpace = totalSpace.Value - }; + { + Path = path, + FreeSpace = freeSpace.Value, + TotalSpace = totalSpace.Value + }; diskSpace.Label = _diskProvider.GetVolumeLabel(path); } diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs index fe69586d2..6fef92d30 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Download.Clients.Blackhole private readonly IDiskProvider _diskProvider; private readonly IDiskScanService _diskScanService; private readonly INamingConfigService _namingConfigService; - private readonly ICached> _watchFolderItemCache; + private readonly ICached> _watchFolderItemCache; public ScanWatchFolder(ICacheManager cacheManager, IDiskScanService diskScanService, INamingConfigService namingConfigService, IDiskProvider diskProvider, Logger logger) { diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs index 554aa82b5..bba855d0d 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs @@ -1,9 +1,8 @@ -using NzbDrone.Common.Disk; -using System; +using System; +using NzbDrone.Common.Disk; namespace NzbDrone.Core.Download.Clients.Blackhole { - public class WatchFolderItem { public string DownloadId { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs index a5df89276..a1f97e5c8 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs @@ -46,7 +46,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge catch (DownloadClientUnavailableException) { _logger.Warn("Failed to set torrent post-import label \"{0}\" for {1} in Deluge. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + Settings.MovieImportedCategory, + downloadClientItem.Title); } } } @@ -69,8 +70,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -96,8 +97,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -124,7 +125,10 @@ namespace NzbDrone.Core.Download.Clients.Deluge foreach (var torrent in torrents) { - if (torrent.Hash == null) continue; + if (torrent.Hash == null) + { + continue; + } var item = new DownloadClientItem(); item.DownloadId = torrent.Hash.ToUpper(); @@ -218,7 +222,11 @@ namespace NzbDrone.Core.Download.Clients.Deluge protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestGetTorrents()); } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs index 764662547..45df09c8c 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs @@ -5,7 +5,7 @@ public int Code { get; set; } public DelugeException(string message, int code) - :base (message + " (code " + code + ")") + : base(message + " (code " + code + ")") { Code = code; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs index f3068c497..f8a331de9 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs @@ -31,7 +31,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge public class DelugeProxy : IDelugeProxy { - private static readonly string[] requiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; + private static readonly string[] RequiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -82,7 +82,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge // TODO: get_torrents_status returns the files as well, which starts to cause deluge timeouts when you get enough season packs. //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -93,7 +93,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge filter.Add("label", label); //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -101,10 +101,10 @@ namespace NzbDrone.Core.Download.Clients.Deluge public string AddTorrentFromMagnet(string magnetLink, DelugeSettings settings) { var options = new - { - add_paused = settings.AddPaused, - remove_at_ratio = false - }; + { + add_paused = settings.AddPaused, + remove_at_ratio = false + }; var response = ProcessRequest(settings, "core.add_torrent_magnet", magnetLink, options); @@ -114,10 +114,10 @@ namespace NzbDrone.Core.Download.Clients.Deluge public string AddTorrentFromFile(string filename, byte[] fileContent, DelugeSettings settings) { var options = new - { - add_paused = settings.AddPaused, - remove_at_ratio = false - }; + { + add_paused = settings.AddPaused, + remove_at_ratio = false + }; var response = ProcessRequest(settings, "core.add_torrent_file", filename, fileContent, options); @@ -167,7 +167,10 @@ namespace NzbDrone.Core.Download.Clients.Deluge public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, DelugeSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var ratioArguments = new Dictionary(); @@ -224,6 +227,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge { return response.Result; } + error = response.Error.ToObject(); throw new DownloadClientAuthenticationException(error.Message); @@ -294,6 +298,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge _logger.Debug("Deluge authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with Deluge."); } + _logger.Debug("Deluge authentication succeeded."); cookies = response.GetCookies(); @@ -326,7 +331,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge if (resultHosts.Result != null) { // The returned list contains the id, ip, port and status of each available connection. We want the 127.0.0.1 - var connection = resultHosts.Result.FirstOrDefault(v => "127.0.0.1" == (v[1] as string)); + var connection = resultHosts.Result.FirstOrDefault(v => (v[1] as string) == "127.0.0.1"); if (connection != null) { @@ -337,7 +342,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge } } - throw new DownloadClientException("Failed to connect to Deluge daemon."); + throw new DownloadClientException("Failed to connect to Deluge daemon."); } private DelugeTorrent[] GetTorrents(DelugeUpdateUIResult result) diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs index bb8f06396..e9f5a6a70 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Download.Clients.Deluge { - class DelugeTorrentStatus + internal class DelugeTorrentStatus { public const string Paused = "Paused"; public const string Queued = "Queued"; diff --git a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs index 38c956479..6d27bb9bd 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs @@ -7,19 +7,16 @@ namespace NzbDrone.Core.Download.Clients public DownloadClientAuthenticationException(string message, params object[] args) : base(message, args) { - } public DownloadClientAuthenticationException(string message) : base(message) { - } public DownloadClientAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) { - } public DownloadClientAuthenticationException(string message, Exception innerException) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs index 67d150a9b..60f84c672 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs @@ -16,7 +16,10 @@ public string Path { - get { return _path; } + get + { + return _path; + } set { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs index 11ff9d7a7..e21d7a718 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs @@ -53,8 +53,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation public DownloadStationSettings() { - this.Host = "127.0.0.1"; - this.Port = 5000; + Host = "127.0.0.1"; + Port = 5000; } public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs index 5b4a61253..41faac633 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs @@ -29,13 +29,18 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation public override string ToString() { - return this.Title; + return Title; } } public enum DownloadStationTaskType { - BT, NZB, http, ftp, eMule, https + BT, + NZB, + http, + ftp, + eMule, + https } public enum DownloadStationTaskStatus diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs index 45c9fd137..81e55569e 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; namespace NzbDrone.Core.Download.Clients.DownloadStation { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs index 3aad129a7..322296c06 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs @@ -12,8 +12,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies public class DSMInfoProxy : DiskStationProxyBase, IDSMInfoProxy { - public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) + public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs index 2b2ea6ca7..d0f817df2 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs @@ -60,7 +60,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { return ProcessRequest(requestBuilder, operation, _apiType, settings); } @@ -68,7 +69,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies private DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, DiskStationApi api, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { var request = requestBuilder.Build(); HttpResponse response; diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs index 9b0cb00ed..1723fcc80 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs @@ -1,7 +1,7 @@ -using NLog; -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies { @@ -12,8 +12,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies public class DownloadStationInfoProxy : DiskStationProxyBase, IDownloadStationInfoProxy { - public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) + public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs index edb82465b..50758d3af 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs @@ -47,7 +47,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses FileStationMessages = new Dictionary { - { 160, "Permission denied. Give your user access to FileStation."}, + { 160, "Permission denied. Give your user access to FileStation." }, { 400, "Invalid parameter of file operation" }, { 401, "Unknown error of file operation" }, { 402, "System is too busy" }, @@ -100,7 +100,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses return CommonMessages[Code]; } - return $"{ Code } - Unknown error"; + return $"{Code} - Unknown error"; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs index 54ac7dc8b..6c40ae75c 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { public class DiskStationApiInfoResponse : Dictionary { - } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs index de7aadfc6..43c981669 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs @@ -1,6 +1,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { - public class DiskStationResponse where T:new() + public class DiskStationResponse + where T : new() { public bool Success { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs index 1d974b913..ebd79f3d7 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses public class DownloadStationTaskInfoResponse { public int Offset { get; set; } - public List Tasks {get;set;} + public List Tasks { get; set; } public int Total { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs index 2f689a48b..f31d51a68 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs @@ -7,6 +7,6 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses public bool IsDir { get; set; } public string Name { get; set; } public string Path { get; set; } - public Dictionary Additional { get; set; } + public Dictionary Additional { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs index ddf971384..88a419d22 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs @@ -15,8 +15,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation public class SerialNumberProvider : ISerialNumberProvider { private readonly IDSMInfoProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; public SerialNumberProvider(ICacheManager cacheManager, IDSMInfoProxy proxy, diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs index d1db18db0..25ff176f6 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs @@ -14,8 +14,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation public class SharedFolderResolver : ISharedFolderResolver { private readonly IFileStationProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; public SharedFolderResolver(ICacheManager cacheManager, IFileStationProxy proxy, diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs index a6e0d8e0c..3613fedf9 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs @@ -196,7 +196,11 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetTorrents()); } @@ -208,7 +212,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation protected bool IsCompleted(DownloadStationTask torrent) { - return torrent.Status == DownloadStationTaskStatus.Seeding || IsFinished(torrent) || (torrent.Status == DownloadStationTaskStatus.Waiting && torrent.Size != 0 && GetRemainingSize(torrent) <= 0); + return torrent.Status == DownloadStationTaskStatus.Seeding || IsFinished(torrent) || (torrent.Status == DownloadStationTaskStatus.Waiting && torrent.Size != 0 && GetRemainingSize(torrent) <= 0); } protected string GetMessage(DownloadStationTask torrent) @@ -339,7 +343,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); @@ -376,6 +380,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, $"Unknown exception: {ex.Message}"); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs index 892f407df..1ea58ba87 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs @@ -36,9 +36,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, IValidateNzbs nzbValidationService, - Logger logger - ) - : base(httpClient, configService, namingConfigService, diskProvider, remotePathMappingService, nzbValidationService, logger) + Logger logger) + : base(httpClient, configService, namingConfigService, diskProvider, remotePathMappingService, nzbValidationService, logger) { _dsInfoProxy = dsInfoProxy; _dsTaskProxy = dsTaskProxy; @@ -191,7 +190,11 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetNZB()); } @@ -238,7 +241,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); @@ -275,6 +278,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs index e64144654..1488c8988 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs @@ -76,7 +76,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken Title = torrent.Name, TotalSize = torrent.TotalSize, SeedRatio = torrent.DownloadedBytes <= 0 ? 0 : - (double) torrent.UploadedBytes / torrent.DownloadedBytes + (double)torrent.UploadedBytes / torrent.DownloadedBytes }; if (!string.IsNullOrEmpty(torrent.Error)) @@ -101,7 +101,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken item.Status = DownloadItemStatus.Downloading; } - item.CanMoveFiles = item.CanBeRemoved = (torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused); + item.CanMoveFiles = item.CanBeRemoved = torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused; items.Add(item); } @@ -142,7 +142,11 @@ namespace NzbDrone.Core.Download.Clients.Hadouken protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -189,7 +193,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken catch (Exception ex) { _logger.Error(ex, ex.Message); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs index 6083851d5..4ab8f67c1 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs @@ -145,7 +145,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken SavePath = Convert.ToString(item[26]) }; } - catch(Exception ex) + catch (Exception ex) { _logger.Error(ex, "Failed to map Hadouken torrent data."); } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs index 2b812a9f5..6841a460e 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs @@ -8,10 +8,10 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.NzbVortex { @@ -82,22 +82,25 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { queueItem.Status = DownloadItemStatus.Paused; } - else switch (vortexQueueItem.State) + else { - case NzbVortexStateType.Waiting: - queueItem.Status = DownloadItemStatus.Queued; - break; - case NzbVortexStateType.Done: - queueItem.Status = DownloadItemStatus.Completed; - break; - case NzbVortexStateType.UncompressFailed: - case NzbVortexStateType.CheckFailedDataCorrupt: - case NzbVortexStateType.BadlyEncoded: - queueItem.Status = DownloadItemStatus.Failed; - break; - default: - queueItem.Status = DownloadItemStatus.Downloading; - break; + switch (vortexQueueItem.State) + { + case NzbVortexStateType.Waiting: + queueItem.Status = DownloadItemStatus.Queued; + break; + case NzbVortexStateType.Done: + queueItem.Status = DownloadItemStatus.Completed; + break; + case NzbVortexStateType.UncompressFailed: + case NzbVortexStateType.CheckFailedDataCorrupt: + case NzbVortexStateType.BadlyEncoded: + queueItem.Status = DownloadItemStatus.Failed; + break; + default: + queueItem.Status = DownloadItemStatus.Downloading; + break; + } } queueItem.OutputPath = GetOutputPath(vortexQueueItem, queueItem); @@ -127,7 +130,6 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { _proxy.Remove(id, deleteData, Settings); } - else { var queue = _proxy.GetQueue(30, Settings); diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs index 10178b9ce..6c8d3e34b 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs @@ -2,21 +2,25 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { - class NzbVortexAuthenticationException : DownloadClientException + internal class NzbVortexAuthenticationException : DownloadClientException { - public NzbVortexAuthenticationException(string message, params object[] args) : base(message, args) + public NzbVortexAuthenticationException(string message, params object[] args) + : base(message, args) { } - public NzbVortexAuthenticationException(string message) : base(message) + public NzbVortexAuthenticationException(string message) + : base(message) { } - public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexAuthenticationException(string message, Exception innerException) : base(message, innerException) + public NzbVortexAuthenticationException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs index 61bbb27d6..8735cb383 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs @@ -2,25 +2,30 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { - class NzbVortexNotLoggedInException : DownloadClientException + internal class NzbVortexNotLoggedInException : DownloadClientException { - public NzbVortexNotLoggedInException() : this("Authentication is required") + public NzbVortexNotLoggedInException() + : this("Authentication is required") { } - public NzbVortexNotLoggedInException(string message, params object[] args) : base(message, args) + public NzbVortexNotLoggedInException(string message, params object[] args) + : base(message, args) { } - public NzbVortexNotLoggedInException(string message) : base(message) + public NzbVortexNotLoggedInException(string message) + : base(message) { } - public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexNotLoggedInException(string message, Exception innerException) : base(message, innerException) + public NzbVortexNotLoggedInException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs index 7c78559ef..4014e6334 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs @@ -92,7 +92,6 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { var requestBuilder = BuildRequest(settings).Resource("nzb"); - if (settings.TvCategory.IsNotNullOrWhiteSpace()) { requestBuilder.AddQueryParam("groupName", settings.TvCategory); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs index ad9a496aa..3c3a04734 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs @@ -10,10 +10,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Nzbget { @@ -21,7 +21,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { private readonly INzbgetProxy _proxy; private readonly string[] _successStatus = { "SUCCESS", "NONE" }; - private readonly string[] _deleteFailedStatus = { "HEALTH", "DUPE", "SCAN", "COPY" }; + private readonly string[] _deleteFailedStatus = { "HEALTH", "DUPE", "SCAN", "COPY" }; public Nzbget(INzbgetProxy proxy, IHttpClient httpClient, @@ -79,7 +79,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget queueItem.CanMoveFiles = true; queueItem.CanBeRemoved = true; - if (globalStatus.DownloadPaused || remainingSize == pausedSize && remainingSize != 0) + if (globalStatus.DownloadPaused || (remainingSize == pausedSize && remainingSize != 0)) { queueItem.Status = DownloadItemStatus.Paused; queueItem.RemainingSize = remainingSize; @@ -223,7 +223,10 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { var name = config.GetValueOrDefault("Category" + i + ".Name"); - if (name == null) yield break; + if (name == null) + { + yield break; + } var destDir = config.GetValueOrDefault("Category" + i + ".DestDir"); @@ -273,6 +276,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { return new ValidationFailure("Username", "Authentication failed"); } + _logger.Error(ex, "Unable to connect to NZBGet"); return new ValidationFailure("Host", "Unable to connect to NZBGet"); } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs index 7c1690dab..092325bc9 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using System.Net; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Download.Clients.Nzbget { @@ -102,6 +102,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget return droneId; } + private string DownloadNzbLegacy12(byte[] nzbData, string title, string category, int priority, NzbgetSettings settings) { var response = ProcessRequest(settings, "append", title, category, priority, false, nzbData); @@ -158,7 +159,6 @@ namespace NzbDrone.Core.Download.Clients.Nzbget return ProcessRequest>(settings, "config").ToDictionary(v => v.Name, v => v.Value); } - public void RemoveItem(string id, NzbgetSettings settings) { var queue = GetQueue(settings); @@ -187,7 +187,6 @@ namespace NzbDrone.Core.Download.Clients.Nzbget _logger.Warn("Failed to remove item from NZBGet, {0} [{1}]", queueItem.NzbName, queueItem.NzbId); } } - else if (historyItem != null) { if (!EditQueue("HistoryDelete", 0, "", historyItem.Id, settings)) @@ -195,7 +194,6 @@ namespace NzbDrone.Core.Download.Clients.Nzbget _logger.Warn("Failed to remove item from NZBGet history, {0} [{1}]", historyItem.Name, historyItem.Id); } } - else { _logger.Warn("Unable to remove item from NZBGet, Unknown ID: {0}", id); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs index a41667824..c6132fbae 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs @@ -5,6 +5,5 @@ namespace NzbDrone.Core.Download.Clients.Nzbget public string Version { get; set; } public T Result { get; set; } - } } diff --git a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs index 0911d74e4..c84a40b3d 100644 --- a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs +++ b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs @@ -8,9 +8,9 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; namespace NzbDrone.Core.Download.Clients.Pneumatic { @@ -43,7 +43,6 @@ namespace NzbDrone.Core.Download.Clients.Pneumatic //{ // throw new NotSupportedException("Full season releases are not supported with Pneumatic."); //} - title = FileNameBuilder.CleanFileName(title); //Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC) @@ -56,7 +55,6 @@ namespace NzbDrone.Core.Download.Clients.Pneumatic var strmFile = WriteStrmFile(title, nzbFile); - return GetDownloadClientId(strmFile); } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs index 3a6cd6a73..0d43b54fc 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; +using System.Net; +using FluentValidation.Results; +using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; -using System.Net; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.Organizer; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.QBittorrent { @@ -57,8 +57,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } catch (DownloadClientException) { - _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", Settings.MovieImportedCategory, downloadClientItem.Title); } } } @@ -74,8 +73,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -90,7 +89,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent return hash; } - protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string hash, string filename, Byte[] fileContent) + protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string hash, string filename, byte[] fileContent) { Proxy.AddTorrentFromFile(filename, fileContent, Settings); @@ -98,8 +97,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -145,7 +144,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent // Avoid removing torrents that haven't reached the global max ratio. // Removal also requires the torrent to be paused, in case a higher max ratio was set on the torrent itself (which is not exposed by the api). - item.CanMoveFiles = item.CanBeRemoved = (torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config)); + item.CanMoveFiles = item.CanBeRemoved = torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config); if (!item.OutputPath.IsEmpty && item.OutputPath.FileName != torrent.Name) { @@ -193,6 +192,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent item.Status = DownloadItemStatus.Warning; item.Message = "qBittorrent cannot resolve magnet link with DHT disabled"; } + break; case "forcedDL": //torrent is being downloaded, and was forced started @@ -235,7 +235,11 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestPrioritySupport()); failures.AddIfNotNull(TestGetTorrents()); @@ -279,7 +283,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent var config = Proxy.GetConfig(Settings); if ((config.MaxRatioEnabled || config.MaxSeedingTimeEnabled) && config.RemoveOnMaxRatio) { - return new NzbDroneValidationFailure(String.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") + return new NzbDroneValidationFailure(string.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") { DetailedDescription = "Radarr will be unable to perform Completed Download Handling as configured. You can fix this in qBittorrent ('Tools -> Options...' in the menu) by changing 'Options -> BitTorrent -> Share Ratio Limiting' from 'Remove them' to 'Pause them'." }; @@ -303,12 +307,13 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent DetailedDescription = "Please verify the hostname and port." }; } - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) { _logger.Error(ex, "Unable to test qBittorrent"); - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } return null; @@ -390,7 +395,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent catch (Exception ex) { _logger.Error(ex, "Failed to test qBittorrent"); - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } return null; @@ -405,7 +410,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent catch (Exception ex) { _logger.Error(ex, "Failed to get torrents"); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; @@ -454,15 +459,23 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { if (torrent.RatioLimit >= 0) { - if (torrent.Ratio >= torrent.RatioLimit) return true; + if (torrent.Ratio >= torrent.RatioLimit) + { + return true; + } } else if (torrent.RatioLimit == -2 && config.MaxRatioEnabled) { - if (torrent.Ratio >= config.MaxRatio) return true; + if (torrent.Ratio >= config.MaxRatio) + { + return true; + } } - if (HasReachedSeedingTimeLimit(torrent, config)) return true; - + if (HasReachedSeedingTimeLimit(torrent, config)) + { + return true; + } return false; } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs index 0f1777b88..bbd308eea 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.Cache; using NzbDrone.Common.Http; - namespace NzbDrone.Core.Download.Clients.QBittorrent { public interface IQBittorrentProxy @@ -19,9 +18,9 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent QBittorrentTorrentProperties GetTorrentProperties(string hash, QBittorrentSettings settings); void AddTorrentFromUrl(string torrentUrl, QBittorrentSettings settings); - void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings); + void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings); - void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings); + void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings); void SetTorrentLabel(string hash, string label, QBittorrentSettings settings); void AddLabel(string label, QBittorrentSettings settings); Dictionary GetLabels(QBittorrentSettings settings); @@ -46,7 +45,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent private readonly IQBittorrentProxy _proxyV1; private readonly IQBittorrentProxy _proxyV2; - public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, + public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, QBittorrentProxyV2 proxyV2, IHttpClient httpClient, ICacheManager cacheManager, diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs index b317ce675..a2d690503 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Serializer; namespace NzbDrone.Core.Download.Clients.QBittorrent { // API https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation - public class QBittorrentProxyV1 : IQBittorrentProxy { private readonly IHttpClient _httpClient; @@ -22,7 +21,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent _httpClient = httpClient; _logger = logger; _authCookieCache = cacheManager.GetCache>(GetType(), "authCookies"); - } public bool IsApiSupported(QBittorrentSettings settings) @@ -93,6 +91,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent request.AddQueryParam("label", settings.MovieCategory); request.AddQueryParam("category", settings.MovieCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -131,7 +130,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/command/upload") .Post() @@ -156,7 +155,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource(removeData ? "/command/deletePerm" : "/command/delete") .Post() @@ -227,7 +226,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -325,7 +323,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { _authCookieCache.Remove(authKey); - var authLoginRequest = BuildRequest(settings).Resource( "/login") + var authLoginRequest = BuildRequest(settings).Resource("/login") .Post() .AddFormParameter("username", settings.Username ?? string.Empty) .AddFormParameter("password", settings.Password ?? string.Empty) @@ -351,7 +349,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + // returns "Fails." on bad login + if (response.Content != "Ok.") { _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs index 7350d5f0c..2e26b1389 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Serializer; namespace NzbDrone.Core.Download.Clients.QBittorrent { // API https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation - public class QBittorrentProxyV2 : IQBittorrentProxy { private readonly IHttpClient _httpClient; @@ -91,6 +90,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { request.AddQueryParam("category", settings.MovieCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -129,7 +129,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/add") .Post() @@ -154,7 +154,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/delete") .Post() @@ -238,7 +238,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -329,6 +328,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } + return; } @@ -366,7 +366,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + // returns "Fails." on bad login + if (response.Content != "Ok.") { _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs index 17557abcc..246b5b558 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var priorityType = (SabnzbdPriority)value; - writer.WriteValue(priorityType.ToString()); + writer.WriteValue(priorityType.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs index c5274efb1..10efa12b2 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var ts = (TimeSpan)value; - writer.WriteValue(ts.ToString()); + writer.WriteValue(ts.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -19,7 +19,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters switch (split.Count()) { case 4: - return new TimeSpan(split[0] * 24 + split[1], split[2], split[3]); + return new TimeSpan((split[0] * 24) + split[1], split[2], split[3]); case 3: return new TimeSpan(split[0], split[1], split[2]); default: diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs index 3d0d7b6b5..9592b80af 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs @@ -9,10 +9,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -150,8 +150,9 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { historyItem.Status = DownloadItemStatus.Completed; } - else // Verifying/Moving etc + else { + // Verifying/Moving etc historyItem.Status = DownloadItemStatus.Downloading; } @@ -168,11 +169,11 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { historyItem.OutputPath = parent; } + parent = parent.Directory; } } - historyItems.Add(historyItem); } @@ -185,7 +186,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { foreach (var downloadClientItem in GetQueue().Concat(GetHistory())) { - if (downloadClientItem.Category == Settings.MovieCategory || downloadClientItem.Category == "*" && Settings.MovieCategory.IsNullOrWhiteSpace()) + if (downloadClientItem.Category == Settings.MovieCategory || (downloadClientItem.Category == "*" && Settings.MovieCategory.IsNullOrWhiteSpace())) { yield return downloadClientItem; } @@ -326,7 +327,6 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd minor = Convert.ToInt32(parsed.Groups["minor"].Value); patch = Convert.ToInt32(parsed.Groups["patch"].Value.Replace("x", "0")); } - else { if (!version.Equals("develop", StringComparison.InvariantCultureIgnoreCase)) @@ -394,10 +394,12 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { return new ValidationFailure("APIKey", "API Key Incorrect"); } + if (ex.Message.ContainsIgnoreCase("API Key Required")) { return new ValidationFailure("APIKey", "API Key Required"); } + throw; } @@ -446,6 +448,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd }; } } + if (config.Misc.enable_tv_sorting && ContainsCategory(config.Misc.tv_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable TV Sorting") @@ -454,6 +457,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd DetailedDescription = "You must disable SABnzbd TV Sorting for the category Radarr uses to prevent import issues. Go to SABnzbd to fix it." }; } + if (config.Misc.enable_movie_sorting && ContainsCategory(config.Misc.movie_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable Movie Sorting") @@ -462,6 +466,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd DetailedDescription = "You must disable SABnzbd Movie Sorting for the category Radarr uses to prevent import issues. Go to SABnzbd to fix it." }; } + if (config.Misc.enable_date_sorting && ContainsCategory(config.Misc.date_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable Date Sorting") diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs index 0f5234727..f725e303d 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs @@ -1,11 +1,11 @@ using System; +using System.Net; using Newtonsoft.Json.Linq; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Common.Http; -using System.Net; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { string GetBaseUrl(SabnzbdSettings settings, string relativePath = null); SabnzbdAddResponse DownloadNzb(byte[] nzbData, string filename, string category, int priority, SabnzbdSettings settings); - void RemoveFrom(string source, string id,bool deleteData, SabnzbdSettings settings); + void RemoveFrom(string source, string id, bool deleteData, SabnzbdSettings settings); string GetVersion(SabnzbdSettings settings); SabnzbdConfig GetConfig(SabnzbdSettings settings); SabnzbdFullStatus GetFullStatus(SabnzbdSettings settings); @@ -166,6 +166,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd requestBuilder.AddSuffixQueryParam("ma_username", settings.Username); requestBuilder.AddSuffixQueryParam("ma_password", settings.Password); } + requestBuilder.AddSuffixQueryParam("output", "json"); return requestBuilder; @@ -211,7 +212,6 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd result.Status = "false"; result.Error = response.Content.Replace("error: ", ""); } - else { result.Status = "true"; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs index 3c2e25e36..38909b8a4 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs @@ -1,13 +1,13 @@ using System; using System.Text.RegularExpressions; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NLog; -using FluentValidation.Results; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.RemotePathMappings; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs index 15d8df5dc..bd4e9aa98 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs @@ -42,18 +42,27 @@ namespace NzbDrone.Core.Download.Clients.Transmission foreach (var torrent in torrents) { // If totalsize == 0 the torrent is a magnet downloading metadata - if (torrent.TotalSize == 0) continue; + if (torrent.TotalSize == 0) + { + continue; + } var outputPath = new OsPath(torrent.DownloadDir); if (Settings.MovieDirectory.IsNotNullOrWhiteSpace()) { - if (!new OsPath(Settings.MovieDirectory).Contains(outputPath)) continue; + if (!new OsPath(Settings.MovieDirectory).Contains(outputPath)) + { + continue; + } } else if (Settings.MovieCategory.IsNotNullOrWhiteSpace()) { var directories = outputPath.FullPath.Split('\\', '/'); - if (!directories.Contains(Settings.MovieCategory)) continue; + if (!directories.Contains(Settings.MovieCategory)) + { + continue; + } } outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, outputPath); @@ -69,7 +78,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission item.TotalSize = torrent.TotalSize; item.RemainingSize = torrent.LeftUntilDone; item.SeedRatio = torrent.DownloadedEver <= 0 ? 0 : - (double) torrent.UploadedEver / torrent.DownloadedEver; + (double)torrent.UploadedEver / torrent.DownloadedEver; if (torrent.Eta >= 0) { @@ -179,8 +188,8 @@ namespace NzbDrone.Core.Download.Clients.Transmission var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -195,8 +204,8 @@ namespace NzbDrone.Core.Download.Clients.Transmission var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -207,7 +216,11 @@ namespace NzbDrone.Core.Download.Clients.Transmission protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -223,7 +236,10 @@ namespace NzbDrone.Core.Download.Clients.Transmission return Settings.MovieDirectory; } - if (!Settings.MovieCategory.IsNotNullOrWhiteSpace()) return null; + if (!Settings.MovieCategory.IsNotNullOrWhiteSpace()) + { + return null; + } var config = _proxy.GetConfig(Settings); var destDir = config.DownloadDir; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs index f89ee42da..3b91b4ce3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs @@ -5,7 +5,6 @@ public TransmissionException(string message) : base(message) { - } } } diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs index dd0b0a0cf..de5c1e4e3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs @@ -1,11 +1,11 @@ using System; -using System.Net; using System.Collections.Generic; -using NzbDrone.Common.Extensions; -using NLog; +using System.Net; using Newtonsoft.Json.Linq; -using NzbDrone.Common.Http; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; namespace NzbDrone.Core.Download.Clients.Transmission @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission void MoveTorrentToTopInQueue(string hashString, TransmissionSettings settings); } - public class TransmissionProxy: ITransmissionProxy + public class TransmissionProxy : ITransmissionProxy { private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -77,7 +77,10 @@ namespace NzbDrone.Core.Download.Clients.Transmission public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, TransmissionSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var arguments = new Dictionary(); arguments.Add("ids", new[] { hash }); @@ -139,7 +142,6 @@ namespace NzbDrone.Core.Download.Clients.Transmission private TransmissionResponse GetSessionVariables(TransmissionSettings settings) { // Retrieve transmission information such as the default download directory, bandwith throttling and seed ratio. - return ProcessRequest("session-get", null, settings); } @@ -155,7 +157,8 @@ namespace NzbDrone.Core.Download.Clients.Transmission private TransmissionResponse GetTorrentStatus(IEnumerable hashStrings, TransmissionSettings settings) { - var fields = new string[]{ + var fields = new string[] + { "id", "hashString", // Unique torrent ID. Use this instead of the client id? "name", diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs index b8ae790d4..9d9df1c0f 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs @@ -1,9 +1,9 @@ using System.Text.RegularExpressions; using FluentValidation; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs index 232b96b4f..f6c393e94 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs @@ -1,21 +1,21 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Threading; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; using NzbDrone.Core.Download.Clients.rTorrent; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Organizer; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -51,8 +51,10 @@ namespace NzbDrone.Core.Download.Clients.RTorrent } catch (Exception ex) { - _logger.Warn(ex, "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + _logger.Warn(ex, + "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", + Settings.MovieImportedCategory, + downloadClientItem.Title); } } } @@ -109,7 +111,10 @@ namespace NzbDrone.Core.Download.Clients.RTorrent foreach (RTorrentTorrent torrent in torrents) { // Don't concern ourselves with categories other than specified - if (Settings.MovieCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MovieCategory) continue; + if (Settings.MovieCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MovieCategory) + { + continue; + } if (torrent.Path.StartsWith(".")) { @@ -171,7 +176,6 @@ namespace NzbDrone.Core.Download.Clients.RTorrent public override DownloadClientInfo GetStatus() { // XXX: This function's correctness has not been considered - var status = new DownloadClientInfo { IsLocalhost = Settings.Host == "127.0.0.1" || Settings.Host == "localhost" @@ -183,7 +187,11 @@ namespace NzbDrone.Core.Download.Clients.RTorrent protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); failures.AddIfNotNull(TestDirectory()); } diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs index 044eaa9f7..39f4d2cc2 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Net; +using CookComputing.XmlRpc; using NLog; using NzbDrone.Common.Extensions; -using CookComputing.XmlRpc; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -73,7 +73,9 @@ namespace NzbDrone.Core.Download.Clients.RTorrent _logger.Debug("Executing remote method: d.multicall2"); var client = BuildClient(settings); - var ret = ExecuteRequest(() => client.TorrentMulticall("", "", + var ret = ExecuteRequest(() => client.TorrentMulticall( + "", + "", "d.name=", // string "d.hash=", // string "d.base_path=", // string @@ -84,8 +86,7 @@ namespace NzbDrone.Core.Download.Clients.RTorrent "d.ratio=", // long "d.is_open=", // long "d.is_active=", // long - "d.complete=") //long - ); + "d.complete=")); //long var items = new List(); diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs index a1140277f..e3ed91759 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs @@ -1,19 +1,19 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Net; +using FluentValidation.Results; +using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; -using System.Net; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Cache; -using NzbDrone.Core.Organizer; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.UTorrent { @@ -66,8 +66,8 @@ namespace NzbDrone.Core.Download.Clients.UTorrent var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)UTorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)UTorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)UTorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -89,8 +89,8 @@ namespace NzbDrone.Core.Download.Clients.UTorrent var isRecentEpisode = remoteMovie.Movie.IsRecentMovie; - if (isRecentEpisode && Settings.RecentMoviePriority == (int)UTorrentPriority.First || - !isRecentEpisode && Settings.OlderMoviePriority == (int)UTorrentPriority.First) + if ((isRecentEpisode && Settings.RecentMoviePriority == (int)UTorrentPriority.First) || + (!isRecentEpisode && Settings.OlderMoviePriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -250,7 +250,11 @@ namespace NzbDrone.Core.Download.Clients.UTorrent protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -283,6 +287,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs index f8a76892b..b95a2aeac 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs @@ -107,7 +107,10 @@ namespace NzbDrone.Core.Download.Clients.UTorrent public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, UTorrentSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var requestBuilder = BuildRequest(settings) .AddQueryParam("action", "setprops") diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs index 30f4c33a8..027b138e0 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent public object Unknown28 { get; set; } } - class UTorrentTorrentJsonConverter : JsonConverter + internal class UTorrentTorrentJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { @@ -78,7 +78,6 @@ namespace NzbDrone.Core.Download.Clients.UTorrent reader.Read(); // Builds before 25406 don't return the remaining items. - if (reader.TokenType != JsonToken.EndArray) { result.DownloadUrl = (string)reader.Value; @@ -101,8 +100,10 @@ namespace NzbDrone.Core.Download.Clients.UTorrent reader.Read(); result.Unknown28 = reader.Value; - while(reader.TokenType != JsonToken.EndArray) + while (reader.TokenType != JsonToken.EndArray) + { reader.Read(); + } } return result; diff --git a/src/NzbDrone.Core/Download/CompletedDownloadService.cs b/src/NzbDrone.Core/Download/CompletedDownloadService.cs index 1ffce2830..d23559703 100644 --- a/src/NzbDrone.Core/Download/CompletedDownloadService.cs +++ b/src/NzbDrone.Core/Download/CompletedDownloadService.cs @@ -9,8 +9,8 @@ using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Download { @@ -125,6 +125,7 @@ namespace NzbDrone.Core.Download { return new TrackedDownloadStatusMessage("", v.Errors); } + return new TrackedDownloadStatusMessage(Path.GetFileName(v.ImportDecision.LocalMovie.Path), v.Errors); }) .ToArray(); diff --git a/src/NzbDrone.Core/Download/DownloadClientBase.cs b/src/NzbDrone.Core/Download/DownloadClientBase.cs index 051a97b51..88c6c13ae 100644 --- a/src/NzbDrone.Core/Download/DownloadClientBase.cs +++ b/src/NzbDrone.Core/Download/DownloadClientBase.cs @@ -1,17 +1,17 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentValidation.Results; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Download { @@ -34,7 +34,10 @@ namespace NzbDrone.Core.Download public ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; @@ -154,7 +157,7 @@ namespace NzbDrone.Core.Download public virtual void MarkItemAsImported(DownloadClientItem downloadClientItem) { - throw new NotSupportedException(this.Name + " does not support marking items as imported"); + throw new NotSupportedException(Name + " does not support marking items as imported"); } } } diff --git a/src/NzbDrone.Core/Download/DownloadClientProvider.cs b/src/NzbDrone.Core/Download/DownloadClientProvider.cs index 978f9ea60..3ad8f6615 100644 --- a/src/NzbDrone.Core/Download/DownloadClientProvider.cs +++ b/src/NzbDrone.Core/Download/DownloadClientProvider.cs @@ -1,8 +1,8 @@ -using System.Linq; -using System.Collections.Generic; -using NzbDrone.Core.Indexers; -using NzbDrone.Common.Cache; +using System.Collections.Generic; +using System.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Download { @@ -32,7 +32,10 @@ namespace NzbDrone.Core.Download { var availableProviders = _downloadClientFactory.GetAvailableProviders().Where(v => v.Protocol == downloadProtocol).ToList(); - if (!availableProviders.Any()) return null; + if (!availableProviders.Any()) + { + return null; + } var blockedProviders = new HashSet(_downloadClientStatusService.GetBlockedProviders().Select(v => v.ProviderId)); diff --git a/src/NzbDrone.Core/Download/DownloadClientRepository.cs b/src/NzbDrone.Core/Download/DownloadClientRepository.cs index 1d04b56f3..704dababc 100644 --- a/src/NzbDrone.Core/Download/DownloadClientRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientRepository : IProviderRepository { - } public class DownloadClientRepository : ProviderRepository, IDownloadClientRepository diff --git a/src/NzbDrone.Core/Download/DownloadClientStatus.cs b/src/NzbDrone.Core/Download/DownloadClientStatus.cs index f4d819424..a6d388125 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatus.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatus.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download { public class DownloadClientStatus : ProviderStatusBase { - } } diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs index 4f6fd6dfa..f7c2b8f08 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusRepository : IProviderStatusRepository { - } public class DownloadClientStatusRepository : ProviderStatusRepository, IDownloadClientStatusRepository diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs index 11eecfe89..19f11d4b7 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusService : IProviderStatusServiceBase { - } public class DownloadClientStatusService : ProviderStatusServiceBase, IDownloadClientStatusService diff --git a/src/NzbDrone.Core/Download/DownloadEventHub.cs b/src/NzbDrone.Core/Download/DownloadEventHub.cs index 8b235c9b7..fa7b6aabf 100644 --- a/src/NzbDrone.Core/Download/DownloadEventHub.cs +++ b/src/NzbDrone.Core/Download/DownloadEventHub.cs @@ -60,7 +60,6 @@ namespace NzbDrone.Core.Download RemoveFromDownloadClient(trackedDownload); } - private void RemoveFromDownloadClient(TrackedDownload trackedDownload) { var downloadClient = _downloadClientProvider.Get(trackedDownload.DownloadClient); diff --git a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs index 6af3aed51..494d8eb56 100644 --- a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Common.Messaging; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Download/DownloadService.cs b/src/NzbDrone.Core/Download/DownloadService.cs index f0110ef6c..cdfc2bc2c 100644 --- a/src/NzbDrone.Core/Download/DownloadService.cs +++ b/src/NzbDrone.Core/Download/DownloadService.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Download void DownloadReport(RemoteMovie remoteMovie); } - public class DownloadService : IDownloadService { private readonly IProvideDownloadClient _downloadClientProvider; @@ -91,6 +90,7 @@ namespace NzbDrone.Core.Download { _indexerStatusService.RecordFailure(remoteMovie.Release.IndexerId); } + throw; } diff --git a/src/NzbDrone.Core/Download/InvalidNzbException.cs b/src/NzbDrone.Core/Download/InvalidNzbException.cs index 5607590d9..5fde39c54 100644 --- a/src/NzbDrone.Core/Download/InvalidNzbException.cs +++ b/src/NzbDrone.Core/Download/InvalidNzbException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Download { public class InvalidNzbException : NzbDroneException { - public InvalidNzbException(string message, params object[] args) : base(message, args) + public InvalidNzbException(string message, params object[] args) + : base(message, args) { } - public InvalidNzbException(string message) : base(message) + public InvalidNzbException(string message) + : base(message) { } - public InvalidNzbException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public InvalidNzbException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public InvalidNzbException(string message, Exception innerException) : base(message, innerException) + public InvalidNzbException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs index 7be49b99a..aecdbbba9 100644 --- a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs +++ b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs @@ -8,14 +8,14 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Indexers; using NzbDrone.Core.Jobs; +using NzbDrone.Core.Languages; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Download.Pending { @@ -195,9 +195,7 @@ namespace NzbDrone.Core.Download.Pending }; queued.Add(queue); - } - } //Return best quality release for each movie @@ -274,7 +272,10 @@ namespace NzbDrone.Core.Download.Pending var movie = movieMap.GetValueOrDefault(release.MovieId); // Just in case the series was removed, but wasn't cleaned up yet (housekeeper will clean it up) - if (movie == null) return null; + if (movie == null) + { + return null; + } release.RemoteMovie = new RemoteMovie { @@ -337,7 +338,6 @@ namespace NzbDrone.Core.Download.Pending { var pendingReleases = GetPendingReleases(remoteMovie.Movie.Id); - var existingReports = pendingReleases.Where(r => r.RemoteMovie.Movie.Id == remoteMovie.Movie.Id) .ToList(); diff --git a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs index fb6d7b8e0..78ef519e1 100644 --- a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs +++ b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs @@ -63,8 +63,8 @@ namespace NzbDrone.Core.Download continue; } - if (downloadProtocol == DownloadProtocol.Usenet && usenetFailed || - downloadProtocol == DownloadProtocol.Torrent && torrentFailed) + if ((downloadProtocol == DownloadProtocol.Usenet && usenetFailed) || + (downloadProtocol == DownloadProtocol.Torrent && torrentFailed)) { PreparePending(pendingAddQueue, grabbed, pending, report, PendingReleaseReason.DownloadClientUnavailable); continue; @@ -134,7 +134,6 @@ namespace NzbDrone.Core.Download // If a higher quality release failed to add to the download client, but a lower quality release // was sent to another client we still list it normally so it apparent that it'll grab next time. // Delayed is treated the same, but only the first is listed the subsequent items as stored as Fallback. - if (IsMovieProcessed(grabbed, report) || IsMovieProcessed(pending, report)) { diff --git a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs index 87c924d52..d73963114 100644 --- a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs +++ b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; -using System.Collections.Generic; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Download/TorrentClientBase.cs b/src/NzbDrone.Core/Download/TorrentClientBase.cs index b5397ca33..0b78aebfb 100644 --- a/src/NzbDrone.Core/Download/TorrentClientBase.cs +++ b/src/NzbDrone.Core/Download/TorrentClientBase.cs @@ -1,18 +1,18 @@ using System; using System.Net; using MonoTorrent; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { @@ -193,7 +193,8 @@ namespace NzbDrone.Core.Download { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Radarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteMovie.Release.DownloadUrl); + Definition.Implementation, + remoteMovie.Release.DownloadUrl); } return actualHash; @@ -224,7 +225,8 @@ namespace NzbDrone.Core.Download { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Radarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteMovie.Release.DownloadUrl); + Definition.Implementation, + remoteMovie.Release.DownloadUrl); } return actualHash; diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs index 4fe4f7998..7d4998dc3 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs @@ -103,7 +103,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads } return trackedDownloads; - } private void RemoveCompletedDownloads(List trackedDownloads) @@ -128,11 +127,9 @@ namespace NzbDrone.Core.Download.TrackedDownloads { _completedDownloadService.Process(trackedDownload); } - } trackedDownloads.AddIfNotNull(trackedDownload); - } catch (Exception e) { diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs index 6148b51a9..7b1a78aa8 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Download.TrackedDownloads public TrackedDownload() { - StatusMessages = new TrackedDownloadStatusMessage[] {}; + StatusMessages = new TrackedDownloadStatusMessage[] { }; } public void Warn(string message, params object[] args) diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs index 43bc66264..49d86fea4 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs @@ -97,12 +97,12 @@ namespace NzbDrone.Core.Download.TrackedDownloads try { - var historyItems = _historyService.FindByDownloadId(downloadItem.DownloadId); var grabbedHistoryItem = historyItems.OrderByDescending(h => h.Date).FirstOrDefault(h => h.EventType == HistoryEventType.Grabbed); var firstHistoryItem = historyItems.OrderByDescending(h => h.Date).FirstOrDefault(); + //TODO: Create release info from history and use that here, so we don't loose indexer flags! - var parsedMovieInfo = _parsingService.ParseMovieInfo(trackedDownload.DownloadItem.Title, new List{grabbedHistoryItem}); + var parsedMovieInfo = _parsingService.ParseMovieInfo(trackedDownload.DownloadItem.Title, new List { grabbedHistoryItem }); if (parsedMovieInfo != null) { @@ -120,7 +120,7 @@ namespace NzbDrone.Core.Download.TrackedDownloads trackedDownload.RemoteMovie == null || trackedDownload.RemoteMovie.Movie == null) { - parsedMovieInfo = _parsingService.ParseMovieInfo(firstHistoryItem.SourceTitle, new List{grabbedHistoryItem}); + parsedMovieInfo = _parsingService.ParseMovieInfo(firstHistoryItem.SourceTitle, new List { grabbedHistoryItem }); if (parsedMovieInfo != null) { @@ -170,9 +170,10 @@ namespace NzbDrone.Core.Download.TrackedDownloads existingItem.CanMoveFiles != downloadItem.CanMoveFiles) { _logger.Debug("Tracking '{0}:{1}': ClientState={2}{3} SonarrStage={4} Episode='{5}' OutputPath={6}.", - downloadItem.DownloadClient, downloadItem.Title, - downloadItem.Status, downloadItem.CanBeRemoved ? "" : - downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", + downloadItem.DownloadClient, + downloadItem.Title, + downloadItem.Status, + downloadItem.CanBeRemoved ? "" : downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", trackedDownload.State, trackedDownload.RemoteMovie?.ParsedMovieInfo, downloadItem.OutputPath); diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs index e0537b8c3..2d8a30cfe 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads public string Title { get; set; } public List Messages { get; set; } - public TrackedDownloadStatusMessage(string title, List messages) { Title = title; diff --git a/src/NzbDrone.Core/Download/UsenetClientBase.cs b/src/NzbDrone.Core/Download/UsenetClientBase.cs index 0a2a9541d..790985629 100644 --- a/src/NzbDrone.Core/Download/UsenetClientBase.cs +++ b/src/NzbDrone.Core/Download/UsenetClientBase.cs @@ -1,14 +1,14 @@ using System.Net; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Exceptions/BadRequestException.cs b/src/NzbDrone.Core/Exceptions/BadRequestException.cs index adf8bf57f..b74559d05 100644 --- a/src/NzbDrone.Core/Exceptions/BadRequestException.cs +++ b/src/NzbDrone.Core/Exceptions/BadRequestException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Exceptions { public class BadRequestException : DownstreamException { - public BadRequestException(string message) : base(HttpStatusCode.BadRequest, message) + public BadRequestException(string message) + : base(HttpStatusCode.BadRequest, message) { } - public BadRequestException(string message, params object[] args) : base(HttpStatusCode.BadRequest, message, args) + public BadRequestException(string message, params object[] args) + : base(HttpStatusCode.BadRequest, message, args) { } } diff --git a/src/NzbDrone.Core/Exceptions/DownstreamException.cs b/src/NzbDrone.Core/Exceptions/DownstreamException.cs index 0ce8f1a94..88bf850fa 100644 --- a/src/NzbDrone.Core/Exceptions/DownstreamException.cs +++ b/src/NzbDrone.Core/Exceptions/DownstreamException.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Core.Exceptions { public HttpStatusCode StatusCode { get; private set; } - public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) : base(message, args) + public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) + : base(message, args) { StatusCode = statusCode; } diff --git a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs index d9225eb2c..ed44e447c 100644 --- a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs +++ b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Core.Exceptions { public HttpStatusCode StatusCode { get; private set; } - public NzbDroneClientException(HttpStatusCode statusCode, string message, params object[] args) : base(message, args) + public NzbDroneClientException(HttpStatusCode statusCode, string message, params object[] args) + : base(message, args) { StatusCode = statusCode; } diff --git a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs index c9582ddde..b891b6d3b 100644 --- a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs +++ b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Exceptions { public ReleaseInfo Release { get; set; } - public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) : base(message, args) + public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) + : base(message, args) { Release = release; } diff --git a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs index e5f42595c..356a343df 100644 --- a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs +++ b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Exceptions { public class SearchFailedException : NzbDroneException { - public SearchFailedException(string message) : base(message) + public SearchFailedException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Extras/ExtraService.cs b/src/NzbDrone.Core/Extras/ExtraService.cs index 0aa901d5a..f87add16d 100644 --- a/src/NzbDrone.Core/Extras/ExtraService.cs +++ b/src/NzbDrone.Core/Extras/ExtraService.cs @@ -11,8 +11,8 @@ using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Extras { @@ -78,7 +78,6 @@ namespace NzbDrone.Core.Extras foreach (var matchingFilename in matchingFilenames) { // Filter out duplicate NFO files - if (matchingFilename.EndsWith(".nfo", StringComparison.InvariantCultureIgnoreCase)) { if (hasNfo) diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs index 24ee8e1df..882b0edb3 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs @@ -23,7 +23,6 @@ namespace NzbDrone.Core.Extras.Files public abstract class ExtraFileManager : IManageExtraFiles where TExtraFile : ExtraFile, new() - { private readonly IConfigService _configService; private readonly IDiskProvider _diskProvider; @@ -113,4 +112,3 @@ namespace NzbDrone.Core.Extras.Files } } } - diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs index c5d7cba47..716725b84 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs @@ -5,7 +5,8 @@ using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Extras.Files { - public interface IExtraFileRepository : IBasicRepository where TExtraFile : ExtraFile, new() + public interface IExtraFileRepository : IBasicRepository + where TExtraFile : ExtraFile, new() { void DeleteForMovie(int movieId); void DeleteForMovieFile(int movieFileId); diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs index 819de5b02..bf934a368 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs @@ -108,7 +108,6 @@ namespace NzbDrone.Core.Extras.Files { _logger.Debug("Removing movie file from DB as part of cleanup routine, not deleting extra files from disk."); } - else { var movie = _movieService.GetMovie(message.MovieFile.MovieId); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs index 210217dc0..89bb2b071 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs @@ -29,14 +29,17 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.MediaBrowser { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; if (filename.Equals("movie.xml", StringComparison.InvariantCultureIgnoreCase)) { diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs index 733253d9d..af8d9ef65 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs @@ -32,7 +32,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox //Re-enable when/if we store and use mpaa certification //private static List ValidCertification = new List { "G", "NC-17", "PG", "PG-13", "R", "UR", "UNRATED", "NR", "TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "TV-PG", "TV-14", "TV-MA" }; - public override string Name => "Roksbox"; public override string GetFilenameAfterMove(Movie movie, MovieFile movieFile, MetadataFile metadataFile) @@ -57,15 +56,19 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } + var parentdir = Directory.GetParent(path); var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; var parseResult = Parser.Parser.ParseMovieTitle(filename, false); @@ -103,29 +106,28 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox var xmlResult = string.Empty; - var sb = new StringBuilder(); - var xws = new XmlWriterSettings(); - xws.OmitXmlDeclaration = true; - xws.Indent = false; + var sb = new StringBuilder(); + var xws = new XmlWriterSettings(); + xws.OmitXmlDeclaration = true; + xws.Indent = false; - using (var xw = XmlWriter.Create(sb, xws)) - { - var doc = new XDocument(); + using (var xw = XmlWriter.Create(sb, xws)) + { + var doc = new XDocument(); - var details = new XElement("video"); - details.Add(new XElement("title", movie.Title)); + var details = new XElement("video"); + details.Add(new XElement("title", movie.Title)); - details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); - details.Add(new XElement("description", movie.Overview)); - details.Add(new XElement("length", movie.Runtime)); + details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); + details.Add(new XElement("description", movie.Overview)); + details.Add(new XElement("length", movie.Runtime)); - doc.Add(details); - doc.Save(xw); - - xmlResult += doc.ToString(); - xmlResult += Environment.NewLine; - } + doc.Add(details); + doc.Save(xw); + xmlResult += doc.ToString(); + xmlResult += Environment.NewLine; + } return new MetadataFileResult(GetMovieFileMetadataFilename(movieFile.RelativePath), xmlResult.Trim(Environment.NewLine.ToCharArray())); } diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs index ad67947b4..b1b2c5a42 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs @@ -48,21 +48,23 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv _logger.Debug("Unknown movie file metadata: {0}", metadataFile.RelativePath); return Path.Combine(movie.Path, metadataFile.RelativePath); - } public override MetadataFile FindMetadataFile(Movie movie, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; if (Path.GetFileName(filename).Equals("folder.jpg", StringComparison.InvariantCultureIgnoreCase)) { @@ -83,7 +85,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv metadata.Type = MetadataType.MovieImage; return metadata; } - } return null; @@ -100,28 +101,27 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv var xmlResult = string.Empty; - var sb = new StringBuilder(); - var xws = new XmlWriterSettings(); - xws.OmitXmlDeclaration = true; - xws.Indent = false; + var sb = new StringBuilder(); + var xws = new XmlWriterSettings(); + xws.OmitXmlDeclaration = true; + xws.Indent = false; - using (var xw = XmlWriter.Create(sb, xws)) - { - var doc = new XDocument(); + using (var xw = XmlWriter.Create(sb, xws)) + { + var doc = new XDocument(); - var details = new XElement("details"); - details.Add(new XElement("id", movie.Id)); - details.Add(new XElement("title", movie.Title)); - details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); - details.Add(new XElement("overview", movie.Overview)); + var details = new XElement("details"); + details.Add(new XElement("id", movie.Id)); + details.Add(new XElement("title", movie.Title)); + details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); + details.Add(new XElement("overview", movie.Overview)); - doc.Add(details); - doc.Save(xw); - - xmlResult += doc.ToString(); - xmlResult += Environment.NewLine; - } + doc.Add(details); + doc.Save(xw); + xmlResult += doc.ToString(); + xmlResult += Environment.NewLine; + } var filename = GetMovieFileMetadataFilename(movieFile.RelativePath); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs index b688332a6..ffc4e14aa 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs @@ -33,7 +33,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc _mediaCoverService = mediaCoverService; _diskProvider = diskProvider; _detectNfo = detectNfo; - } private static readonly Regex MovieImagesRegex = new Regex(@"^(?poster|banner|fanart|clearart|discart|landscape|logo|backdrop|clearlogo)\.(?:png|jpg)", RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -59,7 +58,10 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile { @@ -162,7 +164,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc { details.Add(new XElement("thumb")); } - else { details.Add(new XElement("thumb", thumbnail.Url)); @@ -186,6 +187,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc fanartElement.Add(new XElement("thumb", fanart.Url)); } } + details.Add(fanartElement); } @@ -240,6 +242,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc xmlResult += Environment.NewLine; } } + if (Settings.MovieMetadataURL) { xmlResult += "https://www.themoviedb.org/movie/" + movie.TmdbId; diff --git a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs index 850a83c5e..4c2662303 100644 --- a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs +++ b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs @@ -5,8 +5,8 @@ using NLog; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Subtitles; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Metadata { @@ -41,7 +41,6 @@ namespace NzbDrone.Core.Extras.Metadata foreach (var possibleMetadataFile in filterResult.FilesOnDisk) { // Don't process files that have known Subtitle file extensions (saves a bit of unecessary processing) - if (SubtitleFileExtensions.Extensions.Contains(Path.GetExtension(possibleMetadataFile))) { continue; @@ -81,7 +80,6 @@ namespace NzbDrone.Core.Extras.Metadata // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return metadataFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs index e3d0b0624..746d52c6f 100644 --- a/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Extras.Metadata { diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs index 7358d7f5a..ea4f4df65 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs @@ -4,12 +4,13 @@ using System.IO; using FluentValidation.Results; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Extras.Metadata { - public abstract class MetadataBase : IMetadata where TSettings : IProviderConfig, new() + public abstract class MetadataBase : IMetadata + where TSettings : IProviderConfig, new() { public abstract string Name { get; } @@ -40,7 +41,10 @@ namespace NzbDrone.Core.Extras.Metadata public abstract MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFile); public abstract List MovieImages(Movie movie); - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs index 5566a18c9..65972c007 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs @@ -133,7 +133,6 @@ namespace NzbDrone.Core.Extras.Metadata // TODO: Move EpisodeImage and EpisodeMetadata metadata files, instead of relying on consumers to do it // (Xbmc's EpisodeImage is more than just the extension) - foreach (var consumer in _metadataFactory.GetAvailableProviders()) { foreach (var movieFile in movieFiles) @@ -278,6 +277,7 @@ namespace NzbDrone.Core.Extras.Metadata { _diskProvider.CopyFile(image.Url, fullPath); } + _mediaFileAttributeService.SetFilePermissions(fullPath); } catch (WebException ex) @@ -316,7 +316,6 @@ namespace NzbDrone.Core.Extras.Metadata _metadataFileService.Delete(file.Id); } - return matchingMetadataFiles.First(); } } diff --git a/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs b/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs index eb6f6f95a..a30f9fa17 100644 --- a/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs +++ b/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs @@ -4,8 +4,8 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Others { @@ -68,7 +68,6 @@ namespace NzbDrone.Core.Extras.Others // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return extraFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs index a75dc54c5..8d1e23f3e 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs @@ -4,8 +4,8 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Subtitles { @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Extras.Subtitles public ExistingSubtitleImporter(IExtraFileService subtitleFileService, IParsingService parsingService, Logger logger) - : base (subtitleFileService) + : base(subtitleFileService) { _subtitleFileService = subtitleFileService; _parsingService = parsingService; @@ -49,13 +49,13 @@ namespace NzbDrone.Core.Extras.Subtitles } var subtitleFile = new SubtitleFile - { - MovieId = movie.Id, - MovieFileId = movie.MovieFileId, - RelativePath = movie.Path.GetRelativePath(possibleSubtitleFile), - Language = LanguageParser.ParseSubtitleLanguage(possibleSubtitleFile), - Extension = extension - }; + { + MovieId = movie.Id, + MovieFileId = movie.MovieFileId, + RelativePath = movie.Path.GetRelativePath(possibleSubtitleFile), + Language = LanguageParser.ParseSubtitleLanguage(possibleSubtitleFile), + Extension = extension + }; subtitleFiles.Add(subtitleFile); } @@ -66,7 +66,6 @@ namespace NzbDrone.Core.Extras.Subtitles // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return subtitleFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs index 41cfd7cf8..851b90727 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs @@ -7,10 +7,10 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Subtitles { diff --git a/src/NzbDrone.Core/Fluent.cs b/src/NzbDrone.Core/Fluent.cs index dd63c1de9..02f993f4e 100644 --- a/src/NzbDrone.Core/Fluent.cs +++ b/src/NzbDrone.Core/Fluent.cs @@ -43,7 +43,6 @@ namespace NzbDrone.Core return Convert.ToInt64(gigabytes * 1024L * 1024L * 1024L); } - public static long Round(this long number, long level) { return Convert.ToInt64(Math.Floor((decimal)number / level) * level); @@ -52,16 +51,24 @@ namespace NzbDrone.Core public static string ToBestDateString(this DateTime dateTime) { if (dateTime == DateTime.Today.AddDays(-1)) + { return "Yesterday"; + } if (dateTime == DateTime.Today) + { return "Today"; + } if (dateTime == DateTime.Today.AddDays(1)) + { return "Tomorrow"; + } if (dateTime > DateTime.Today.AddDays(1) && dateTime < DateTime.Today.AddDays(7)) + { return dateTime.DayOfWeek.ToString(); + } return dateTime.ToShortDateString(); } @@ -69,12 +76,16 @@ namespace NzbDrone.Core public static int MaxOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intList = ints.ToList(); if (!intList.Any()) + { return 0; + } return intList.Max(); } @@ -82,7 +93,10 @@ namespace NzbDrone.Core public static string Truncate(this string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) + { return s; + } + var cs = s.ToCharArray(); int length = 0; int i = 0; @@ -90,7 +104,10 @@ namespace NzbDrone.Core { int charSize = 1; if (i < (cs.Length - 1) && char.IsSurrogate(cs[i])) + { charSize = 2; + } + int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) <= maxLength) { @@ -98,20 +115,27 @@ namespace NzbDrone.Core length += byteSize; } else + { break; + } } + return s.Substring(0, i); } public static int MinOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intsList = ints.ToList(); if (!intsList.Any()) + { return 0; + } return intsList.Min(); } diff --git a/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs b/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs index 7e7b9d259..dd1dcb3be 100644 --- a/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs +++ b/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs @@ -3,7 +3,7 @@ using System; namespace NzbDrone.Core.HealthCheck { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public class CheckOnAttribute: Attribute + public class CheckOnAttribute : Attribute { public Type EventType { get; set; } public CheckOnCondition Condition { get; set; } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs index dce62085e..212af2317 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs @@ -37,12 +37,14 @@ namespace NzbDrone.Core.HealthCheck.Checks if (dotnetVersion >= stableVersion) { _logger.Debug("Dotnet version is {0} or better: {1}", stableVersion, dotnetVersion); - return new HealthCheck(GetType(), HealthCheckResult.Notice, + return new HealthCheck(GetType(), + HealthCheckResult.Notice, $"Currently installed .Net Framework {dotnetVersion} is supported but we recommend upgrading to at least {targetVersion}.", "#currently-installed-net-framework-is-supported-but-upgrading-is-recommended"); } - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed .Net Framework {dotnetVersion} is old and unsupported. Please upgrade the .Net Framework to at least {targetVersion}.", "#currently-installed-net-framework-is-old-and-unsupported"); } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs index a62f82c19..ebb0c2609 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.HealthCheck.Checks private readonly IConfigService _configService; private readonly IProvideDownloadClient _provideDownloadClient; - public ImportMechanismCheck(IConfigService configService, IProvideDownloadClient provideDownloadClient) { _configService = configService; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs index f15874770..03f60031b 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs @@ -30,7 +30,7 @@ namespace NzbDrone.Core.HealthCheck.Checks if (active.Empty()) { - return new HealthCheck(GetType(), HealthCheckResult.Warning, "All rss-capable indexers are temporarily unavailable due to recent indexer errors"); + return new HealthCheck(GetType(), HealthCheckResult.Warning, "All rss-capable indexers are temporarily unavailable due to recent indexer errors"); } return new HealthCheck(GetType()); diff --git a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs index 0bdc8466c..70d3dd68a 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs @@ -28,7 +28,8 @@ namespace NzbDrone.Core.HealthCheck.Checks if (monoVersion == new Version("4.4.0") || monoVersion == new Version("4.4.1")) { _logger.Debug("Mono version {0}", monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed Mono version {monoVersion} has a bug that causes issues connecting to indexers/download clients. You should upgrade to a higher version", "#currently-installed-mono-version-is-old-and-unsupported"); } @@ -47,7 +48,8 @@ namespace NzbDrone.Core.HealthCheck.Checks if (monoVersion >= stableVersion) { _logger.Debug("Mono version is {0} or better: {1}", stableVersion, monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Notice, + return new HealthCheck(GetType(), + HealthCheckResult.Notice, $"Currently installed Mono version {monoVersion} is supported but upgrading to {bestVersion} is recommended.", "#currently-installed-mono-version-is-supported-but-upgrading-is-recommended"); } @@ -57,12 +59,14 @@ namespace NzbDrone.Core.HealthCheck.Checks if (monoVersion >= supportedVersion) { _logger.Debug("Mono version is {0} or better: {1}", supportedVersion, monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Warning, + return new HealthCheck(GetType(), + HealthCheckResult.Warning, $"Currently installed Mono version {monoVersion} is supported but has some known issues. Please upgrade Mono to version {bestVersion}.", "#currently-installed-mono-version-is-supported-but-upgrading-is-recommended"); } - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed Mono version {monoVersion} is old and unsupported. Please upgrade Mono to version {bestVersion}.", "#currently-installed-mono-version-is-old-and-unsupported"); } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs index 029c2e6b8..e6b0b7576 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs @@ -1,10 +1,10 @@ -using NLog; -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; -using System; +using System; using System.Linq; using System.Net; +using NLog; using NzbDrone.Common.Cloud; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Configuration.Events; namespace NzbDrone.Core.HealthCheck.Checks diff --git a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs index 5b8c2f3a5..82b640a7a 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs @@ -38,21 +38,24 @@ namespace NzbDrone.Core.HealthCheck.Checks { if (OsInfo.IsOsx && startupFolder.GetAncestorFolders().Contains("AppTranslocation")) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is in an App Translocation folder.", startupFolder), "Cannot install update because startup folder is in an App Translocation folder."); } if (!_diskProvider.FolderWritable(startupFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is not writable by the user '{1}'.", startupFolder, Environment.UserName), "Cannot install update because startup folder is not writable by the user"); } if (!_diskProvider.FolderWritable(uiFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because UI folder '{0}' is not writable by the user '{1}'.", uiFolder, Environment.UserName), "Cannot install update because UI folder is not writable by the user"); } diff --git a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs index 643863c2b..761e9f7d0 100644 --- a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs +++ b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs @@ -73,7 +73,6 @@ namespace NzbDrone.Core.HealthCheck { _healthCheckResults.Remove(result.Source.Name); } - else { if (_healthCheckResults.Find(result.Source.Name) == null) @@ -145,9 +144,7 @@ namespace NzbDrone.Core.HealthCheck } } - // TODO: Add debounce - PerformHealthCheck(filteredChecks.ToArray()); } } diff --git a/src/NzbDrone.Core/History/History.cs b/src/NzbDrone.Core/History/History.cs index f022d65b4..fe58239c3 100644 --- a/src/NzbDrone.Core/History/History.cs +++ b/src/NzbDrone.Core/History/History.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -26,16 +26,17 @@ namespace NzbDrone.Core.History public List Languages { get; set; } public string DownloadId { get; set; } - } public enum HistoryEventType { Unknown = 0, Grabbed = 1, + // SeriesFolderImported = 2, // deprecated DownloadFolderImported = 3, DownloadFailed = 4, + // EpisodeFileDeleted = 5, // deprecated MovieFileDeleted = 6, MovieFolderImported = 7, // not used yet diff --git a/src/NzbDrone.Core/History/HistoryRepository.cs b/src/NzbDrone.Core/History/HistoryRepository.cs index dde58ccb9..7be0674da 100644 --- a/src/NzbDrone.Core/History/HistoryRepository.cs +++ b/src/NzbDrone.Core/History/HistoryRepository.cs @@ -4,8 +4,8 @@ using System.Linq; using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -23,7 +23,6 @@ namespace NzbDrone.Core.History public class HistoryRepository : BasicRepository, IHistoryRepository { - public HistoryRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -55,8 +54,8 @@ namespace NzbDrone.Core.History h.Quality == quality && (h.EventType == HistoryEventType.Grabbed || h.EventType == HistoryEventType.DownloadFailed || - h.EventType == HistoryEventType.DownloadFolderImported) - ).ToList(); + h.EventType == HistoryEventType.DownloadFolderImported)) + .ToList(); } public List GetByMovieId(int movieId, HistoryEventType? eventType) diff --git a/src/NzbDrone.Core/History/HistoryService.cs b/src/NzbDrone.Core/History/HistoryService.cs index f453efcd6..ba259ac46 100644 --- a/src/NzbDrone.Core/History/HistoryService.cs +++ b/src/NzbDrone.Core/History/HistoryService.cs @@ -9,10 +9,10 @@ using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies.Events; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies.Events; namespace NzbDrone.Core.History { @@ -249,21 +249,22 @@ namespace NzbDrone.Core.History //foreach (var matchingHistory in trackedDownload.EpisodeInfo.Episodes.Select(e => stillDownloading.Where(c => c.MovieId == e.Id).ToList())) //foreach (var matchingHistory in stillDownloading.Where(c => c.MovieId == e.Id).ToList()) //{ - if (stillDownloading.Count != 1) - { - return null; - } + if (stillDownloading.Count != 1) + { + return null; + } - var newDownloadId = stillDownloading.Single().DownloadId; + var newDownloadId = stillDownloading.Single().DownloadId; + + if (downloadId == null || downloadId == newDownloadId) + { + downloadId = newDownloadId; + } + else + { + return null; + } - if (downloadId == null || downloadId == newDownloadId) - { - downloadId = newDownloadId; - } - else - { - return null; - } //} } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs index e63fd2dfa..8546cd37c 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM NamingConfig WHERE ID NOT IN ( SELECT ID FROM NamingConfig diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs index 4dde12d14..4064d453e 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM Users WHERE ID NOT IN ( SELECT ID FROM Users @@ -24,4 +23,3 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers } } } - diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs index 51c3ba3f9..a7b36639e 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs @@ -22,11 +22,11 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers (p.Reason == PendingReleaseReason.DownloadClientUnavailable || p.Reason == PendingReleaseReason.Fallback)); -// mapper.AddParameter("twoWeeksAgo", $"{DateTime.UtcNow.AddDays(-14).ToString("s")}Z"); + // mapper.AddParameter("twoWeeksAgo", $"{DateTime.UtcNow.AddDays(-14).ToString("s")}Z"); -// mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases -// WHERE Added < @twoWeeksAgo -// AND (Reason = 'DownloadClientUnavailable' OR Reason = 'Fallback')"); + // mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases + // WHERE Added < @twoWeeksAgo + // AND (Reason = 'DownloadClientUnavailable' OR Reason = 'Fallback')"); } } } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs index 5a405de77..8ce13e95c 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles @@ -36,7 +35,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs index 6ef15ac2f..62e8de4c8 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM AlternativeTitles WHERE Id IN ( SELECT AlternativeTitles.Id FROM AlternativeTitles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs index 7816c5ab9..609236cb4 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM Blacklist WHERE Id IN ( SELECT Blacklist.Id FROM Blacklist diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs index d69112d97..a8d071365 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM History WHERE Id IN ( SELECT History.Id FROM History diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs index 60c956b99..6f6a61267 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM IndexerStatus WHERE Id IN ( SELECT IndexerStatus.Id FROM IndexerStatus diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs index 1c89b1c46..bf10b4fcf 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs @@ -22,7 +22,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT MetadataFiles.Id FROM MetadataFiles @@ -36,7 +35,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT MetadataFiles.Id FROM MetadataFiles @@ -51,7 +49,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs index bed514b93..71e9eded6 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases WHERE Id IN ( SELECT PendingReleases.Id FROM PendingReleases diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs index f8ead0292..4f473b158 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs @@ -19,8 +19,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { using (var mapper = _database.GetDataMapper()) { - - var usedTags = new[] {"Movies", "Notifications", "DelayProfiles", "Restrictions", "NetImport"} + var usedTags = new[] { "Movies", "Notifications", "DelayProfiles", "Restrictions", "NetImport" } .SelectMany(v => GetUsedTags(v, mapper)) .Distinct() .ToArray(); diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs index 0b9119425..1ba7f83d5 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs @@ -32,7 +32,10 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers public void Clean() { - if (!_configService.CleanupMetadataImages) return; + if (!_configService.CleanupMetadataImages) + { + return; + } var movies = _movieService.GetAllMovies(); @@ -59,7 +62,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers } } - _configService.CleanupMetadataImages = false; } @@ -75,7 +77,11 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers using (var imageStream = _diskProvider.OpenReadStream(path)) { - if (imageStream.Length < buffer.Length) return false; + if (imageStream.Length < buffer.Length) + { + return false; + } + imageStream.Read(buffer, 0, buffer.Length); } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs index 80bf5c8b9..55a4c6b3d 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs @@ -5,7 +5,8 @@ using NzbDrone.Core.ThingiProvider.Status; namespace NzbDrone.Core.Housekeeping.Housekeepers { - public abstract class FixFutureProviderStatusTimes where TModel : ProviderStatusBase, new() + public abstract class FixFutureProviderStatusTimes + where TModel : ProviderStatusBase, new() { private readonly IProviderStatusRepository _repo; diff --git a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs index eb8cedd9e..277065511 100644 --- a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs +++ b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using NLog; -using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.Housekeeping { @@ -30,7 +30,6 @@ namespace NzbDrone.Core.Housekeeping _logger.Debug("Starting {0}", housekeeper.GetType().Name); housekeeper.Clean(); _logger.Debug("Completed {0}", housekeeper.GetType().Name); - } catch (Exception ex) { diff --git a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs index e5590c63c..dca1d12c0 100644 --- a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs +++ b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs @@ -7,9 +7,8 @@ namespace NzbDrone.Core.Http.CloudFlare { public class CloudFlareHttpInterceptor : IHttpRequestInterceptor { - private readonly Logger _logger; - private const string _cloudFlareChallengeScript = "cdn-cgi/scripts/cf.challenge.js"; + private readonly Logger _logger; private static readonly Regex _cloudFlareRegex = new Regex(@"data-ray=""(?[\w-_]+)"".*?data-sitekey=""(?[\w-_]+)"".*?data-stoken=""(?[\w-_]+)""", RegexOptions.Compiled); public CloudFlareHttpInterceptor(Logger logger) diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs index b35f508a3..567dae930 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Core.IndexerSearch.Definitions { public class MovieSearchCriteria : SearchCriteriaBase { - public override string ToString() { return string.Format("[{0}]", Movie.Title); diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs index c5d3b482d..da55ef55f 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs @@ -23,7 +23,7 @@ namespace NzbDrone.Core.IndexerSearch.Definitions public static string GetQueryTitle(string title) { - Ensure.That(title,() => title).IsNotNullOrWhiteSpace(); + Ensure.That(title, () => title).IsNotNullOrWhiteSpace(); var cleanTitle = BeginningThe.Replace(title, string.Empty); diff --git a/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs index 09c4c8736..9e8459344 100644 --- a/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.IndexerSearch { diff --git a/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs b/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs index 608b03efc..9ae982aef 100644 --- a/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs @@ -1,14 +1,14 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Movies; -using NzbDrone.Core.Datastore; using NzbDrone.Core.Queue; -using NzbDrone.Core.DecisionEngine; namespace NzbDrone.Core.IndexerSearch { @@ -49,10 +49,10 @@ namespace NzbDrone.Core.IndexerSearch continue; } - var decisions = _nzbSearchService.MovieSearch(movieId, false, false);//_nzbSearchService.SeasonSearch(message.MovieId, season.SeasonNumber, false, message.Trigger == CommandTrigger.Manual); + var decisions = _nzbSearchService.MovieSearch(movieId, false, false); //_nzbSearchService.SeasonSearch(message.MovieId, season.SeasonNumber, false, message.Trigger == CommandTrigger.Manual); downloadedCount += _processDownloadDecisions.ProcessDecisions(decisions).Grabbed.Count; - } + _logger.ProgressInfo("Movie search completed. {0} reports downloaded.", downloadedCount); } @@ -73,7 +73,6 @@ namespace NzbDrone.Core.IndexerSearch var missing = movies.Where(e => !queue.Contains(e.Id)).ToList(); SearchForMissingMovies(missing, message.Trigger == CommandTrigger.Manual); - } public void Execute(CutoffUnmetMoviesSearchCommand message) @@ -94,7 +93,6 @@ namespace NzbDrone.Core.IndexerSearch var missing = movies.Where(e => !queue.Contains(e.Id)).ToList(); SearchForMissingMovies(missing, message.Trigger == CommandTrigger.Manual); - } private void SearchForMissingMovies(List movies, bool userInvokedSearch) @@ -112,7 +110,7 @@ namespace NzbDrone.Core.IndexerSearch } catch (Exception ex) { - var message = String.Format("Unable to search for missing movie {0}", movieId.Key); + var message = string.Format("Unable to search for missing movie {0}", movieId.Key); _logger.Error(ex, message); continue; } @@ -124,8 +122,5 @@ namespace NzbDrone.Core.IndexerSearch _logger.ProgressInfo("Completed missing search for {0} movies. {1} reports downloaded.", movies.Count, downloadedCount); } - - - } } diff --git a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs index c4c74d2d4..0d7219892 100644 --- a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs @@ -1,15 +1,15 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common.Instrumentation.Extensions; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using System.Linq; using NzbDrone.Common.TPL; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.IndexerSearch { @@ -51,14 +51,15 @@ namespace NzbDrone.Core.IndexerSearch return Dispatch(indexer => indexer.Fetch(searchSpec), searchSpec); } - private TSpec Get(Movie movie, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Movie movie, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec() { Movie = movie, UserInvokedSearch = userInvokedSearch, InteractiveSearch = interactiveSearch - }; + }; return spec; } diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs index afe7892a0..edfee09cc 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs @@ -15,7 +15,8 @@ namespace NzbDrone.Core.Indexers.AwesomeHD public AwesomeHD(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) - { } + { + } public override IIndexerRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs index a5dbe8d7c..8b4e2c68e 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs @@ -36,7 +36,6 @@ namespace NzbDrone.Core.Indexers.AwesomeHD { yield return new IndexerRequest($"{Settings.BaseUrl.Trim().TrimEnd('/')}/searchapi.php?action=latestmovies&passkey={Settings.Passkey.Trim()}", HttpAccept.Rss); } - } } } diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs index 9fa65a71d..44384dac5 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs @@ -1,12 +1,12 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Linq; using System.Net; +using System.Xml; +using System.Xml.Linq; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; -using System; -using System.Linq; -using System.Xml; -using System.Xml.Linq; namespace NzbDrone.Core.Indexers.AwesomeHD { @@ -125,7 +125,6 @@ namespace NzbDrone.Core.Indexers.AwesomeHD "An error occurred while processing feed, feed invalid"); } - return torrentInfos.OrderByDescending(o => ((dynamic)o).Seeders).ToArray(); } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs index 41d0d4d5e..eb4e26654 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class ApiKeyException : NzbDroneException { - public ApiKeyException(string message, params object[] args) : base(message, args) + public ApiKeyException(string message, params object[] args) + : base(message, args) { } - public ApiKeyException(string message) : base(message) + public ApiKeyException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs index 6fe085dd4..08e5d72f4 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class SizeParsingException : NzbDroneException { - public SizeParsingException(string message, params object[] args) : base(message, args) + public SizeParsingException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs index 48773d2c6..298d7f4fe 100644 --- a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs +++ b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NLog; -using NzbDrone.Core.Parser.Model; using NzbDrone.Common.TPL; -using System; +using NzbDrone.Core.Parser.Model; + namespace NzbDrone.Core.Indexers { public interface IFetchAndParseRss diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs index 5185433a5..c52a2f496 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs @@ -15,7 +15,8 @@ namespace NzbDrone.Core.Indexers.HDBits public HDBits(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) - { } + { + } public override IIndexerRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs index 0a163f4ce..a772e9f74 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs @@ -51,7 +51,7 @@ namespace NzbDrone.Core.Indexers.HDBits foreach (var result in queryResults) { var id = result.Id; - var internalRelease = (result.TypeOrigin == 1 ? true : false); + var internalRelease = result.TypeOrigin == 1 ? true : false; IndexerFlags flags = 0; @@ -104,7 +104,6 @@ namespace NzbDrone.Core.Indexers.HDBits .AddQueryParam("id", torrentId); return url.FullUri; - } } } diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs index 71ff7ade9..3dbe3e526 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs @@ -43,6 +43,7 @@ namespace NzbDrone.Core.Indexers.HDBits query.ImdbInfo.Id = imdbId; return true; } + return false; } diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs index be003121f..82cea616b 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Collections.Generic; namespace NzbDrone.Core.Indexers.HDBits { diff --git a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs index 71fc0b4c3..99aa31092 100644 --- a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs @@ -63,7 +63,6 @@ namespace NzbDrone.Core.Indexers var generator = GetRequestGenerator(); //A func ensures cookies are always updated to the latest. This way, the first page could update the cookies and then can be reused by the second page. - generator.GetCookies = () => { var cookies = _indexerStatusService.GetIndexerCookies(Definition.Id); @@ -86,7 +85,6 @@ namespace NzbDrone.Core.Indexers return requests; } - protected virtual IList FetchReleases(Func pageableRequestChainSelector, bool isRecent = false) { var releases = new List(); @@ -133,6 +131,7 @@ namespace NzbDrone.Core.Indexers fullyUpdated = true; break; } + var oldestReleaseDate = page.Select(v => v.PublishDate).Min(); if (oldestReleaseDate < lastReleaseInfo.PublishDate || page.Any(v => v.DownloadUrl == lastReleaseInfo.DownloadUrl)) { @@ -177,6 +176,7 @@ namespace NzbDrone.Core.Indexers var gapEnd = ordered.Last().PublishDate; _logger.Warn("Indexer {0} rss sync didn't cover the period between {1} and {2} UTC. Search may be required.", Definition.Name, gapStart, gapEnd); } + lastReleaseInfo = ordered.First(); _indexerStatusService.UpdateRssSyncStatus(Definition.Id, lastReleaseInfo); } @@ -215,6 +215,7 @@ namespace NzbDrone.Core.Indexers { _indexerStatusService.RecordFailure(Definition.Id, TimeSpan.FromHours(1)); } + _logger.Warn("API Request Limit reached for {0}", this); } catch (HttpException ex) @@ -285,7 +286,7 @@ namespace NzbDrone.Core.Indexers } catch (Exception ex) { - ex.WithData(response.HttpResponse, 128*1024); + ex.WithData(response.HttpResponse, 128 * 1024); _logger.Trace("Unexpected Response content ({0} bytes): {1}", response.HttpResponse.ResponseData.Length, response.HttpResponse.Content); throw; } @@ -385,5 +386,4 @@ namespace NzbDrone.Core.Indexers return null; } } - } diff --git a/src/NzbDrone.Core/Indexers/IIndexerSettings.cs b/src/NzbDrone.Core/Indexers/IIndexerSettings.cs index ab76c2ffd..1bc607561 100644 --- a/src/NzbDrone.Core/Indexers/IIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/IIndexerSettings.cs @@ -6,6 +6,7 @@ namespace NzbDrone.Core.Indexers public interface IIndexerSettings : IProviderConfig { string BaseUrl { get; set; } + // TODO: Need to Create UI field for this and turn functionality back on per indexer. IEnumerable MultiLanguages { get; set; } } diff --git a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs index 633f27bd0..6b74949ba 100644 --- a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs +++ b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs @@ -1,7 +1,7 @@ +using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NLog; namespace NzbDrone.Core.Indexers.IPTorrents { @@ -16,7 +16,6 @@ namespace NzbDrone.Core.Indexers.IPTorrents public IPTorrents(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/IndexerBase.cs b/src/NzbDrone.Core/Indexers/IndexerBase.cs index ed258365f..265a1b144 100644 --- a/src/NzbDrone.Core/Indexers/IndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/IndexerBase.cs @@ -58,7 +58,10 @@ namespace NzbDrone.Core.Indexers public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs index 427617b61..1671ff1c1 100644 --- a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs +++ b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs @@ -27,7 +27,10 @@ namespace NzbDrone.Core.Indexers public void Add(IEnumerable request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new IndexerPageableRequest(request)); } @@ -40,7 +43,10 @@ namespace NzbDrone.Core.Indexers public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List()); } diff --git a/src/NzbDrone.Core/Indexers/IndexerRepository.cs b/src/NzbDrone.Core/Indexers/IndexerRepository.cs index 50d07d66d..c4858f415 100644 --- a/src/NzbDrone.Core/Indexers/IndexerRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Indexers { public interface IIndexerRepository : IProviderRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatus.cs b/src/NzbDrone.Core/Indexers/IndexerStatus.cs index a556036cb..ea277e6da 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatus.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatus.cs @@ -11,6 +11,5 @@ namespace NzbDrone.Core.Indexers public IDictionary Cookies { get; set; } public DateTime? CookiesExpirationDate { get; set; } - } } diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs index 78d2cc41c..5df1f1523 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Indexers { public interface IIndexerStatusRepository : IProviderStatusRepository { - } public class IndexerStatusRepository : ProviderStatusRepository, IIndexerStatusRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs index 847b30caa..9254a5b3e 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs @@ -23,7 +23,6 @@ namespace NzbDrone.Core.Indexers public IndexerStatusService(IIndexerStatusRepository providerStatusRepository, IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, Logger logger) : base(providerStatusRepository, eventAggregator, runtimeInfo, logger) { - } public ReleaseInfo GetLastRssSyncReleaseInfo(int indexerId) @@ -41,8 +40,6 @@ namespace NzbDrone.Core.Indexers return GetProviderStatus(indexerId).CookiesExpirationDate ?? DateTime.Now + TimeSpan.FromDays(12); } - - public void UpdateRssSyncStatus(int indexerId, ReleaseInfo releaseInfo) { lock (_syncRoot) diff --git a/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs b/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs index 2d06d7098..a566cf1ac 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs @@ -53,7 +53,6 @@ namespace NzbDrone.Core.Indexers.Newznab yield return GetDefinition("PFmonkey", GetSettings("https://www.pfmonkey.com")); yield return GetDefinition("SimplyNZBs", GetSettings("https://simplynzbs.com")); yield return GetDefinition("Usenet Crawler", GetSettings("https://www.usenet-crawler.com")); - } } @@ -66,17 +65,17 @@ namespace NzbDrone.Core.Indexers.Newznab private IndexerDefinition GetDefinition(string name, NewznabSettings settings) { return new IndexerDefinition - { - EnableRss = false, - EnableAutomaticSearch = false, - EnableInteractiveSearch = false, - Name = name, - Implementation = GetType().Name, - Settings = settings, - Protocol = DownloadProtocol.Usenet, - SupportsRss = SupportsRss, - SupportsSearch = SupportsSearch - }; + { + EnableRss = false, + EnableAutomaticSearch = false, + EnableInteractiveSearch = false, + Name = name, + Implementation = GetType().Name, + Settings = settings, + Protocol = DownloadProtocol.Usenet, + SupportsRss = SupportsRss, + SupportsSearch = SupportsSearch + }; } private NewznabSettings GetSettings(string url, string apiPath = null, int[] categories = null) @@ -99,7 +98,11 @@ namespace NzbDrone.Core.Indexers.Newznab protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } @@ -110,7 +113,9 @@ namespace NzbDrone.Core.Indexers.Newznab foreach (var category in categories) { if (category.Subcategories != null) + { l.AddRange(CategoryIds(category.Subcategories)); + } } return l; @@ -128,7 +133,9 @@ namespace NzbDrone.Core.Indexers.Newznab { _logger.Warn($"{Definition.Name} does not support the following categories: {string.Join(", ", notSupported)}. You should probably remove them."); if (notSupported.Count() == Settings.Categories.Count()) + { return new ValidationFailure(string.Empty, $"This indexer does not support any of the selected categories! (You may need to turn on advanced settings to see them)"); + } } if (capabilities.SupportedSearchParameters != null && capabilities.SupportedSearchParameters.Contains("q")) diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs index f8b713637..e1a27cefe 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs @@ -128,6 +128,7 @@ namespace NzbDrone.Core.Indexers.Newznab capabilities.SupportedTvSearchParameters = xmlTvSearch.Attribute("supportedParams").Value.Split(','); capabilities.SupportsAggregateIdSearch = true; } + var xmlMovieSearch = xmlSearching.Element("movie-search"); if (xmlMovieSearch == null || xmlMovieSearch.Attribute("available").Value != "yes") { @@ -160,7 +161,6 @@ namespace NzbDrone.Core.Indexers.Newznab Id = int.Parse(xmlSubcat.Attribute("id").Value), Name = xmlSubcat.Attribute("name").Value, Description = xmlSubcat.Attribute("description") != null ? xmlSubcat.Attribute("description").Value : string.Empty - }); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs index 255b30cea..4161dbb82 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs @@ -65,12 +65,12 @@ namespace NzbDrone.Core.Indexers.Newznab var altTitles = searchCriteria.Movie.AlternativeTitles.Take(5).Select(t => t.Title).ToList(); altTitles.Add(searchCriteria.Movie.Title); - var realMaxPages = (int)MaxPages / (altTitles.Count()); + var realMaxPages = (int)MaxPages / altTitles.Count(); //pageableRequests.Add(GetPagedRequests(MaxPages - (altTitles.Count() * realMaxPages), Settings.Categories, "search", $"&q={searchTitle}%20{searchCriteria.Movie.Year}")); //Also use alt titles for searching. - foreach (String altTitle in altTitles) + foreach (string altTitle in altTitles) { var searchAltTitle = System.Web.HttpUtility.UrlPathEncode(Parser.Parser.ReplaceGermanUmlauts(Parser.Parser.NormalizeTitle(altTitle))); var queryString = $"&q={searchAltTitle}"; @@ -78,6 +78,7 @@ namespace NzbDrone.Core.Indexers.Newznab { queryString += $"%20{searchCriteria.Movie.Year}"; } + pageableRequests.Add(GetPagedRequests(realMaxPages, Settings.Categories, "search", queryString)); } } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs index a301c658d..3921615aa 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs @@ -27,7 +27,10 @@ namespace NzbDrone.Core.Indexers.Newznab var xdoc = LoadXmlDocument(indexerResponse); var error = xdoc.Descendants("error").FirstOrDefault(); - if (error == null) return true; + if (error == null) + { + return true; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; @@ -74,7 +77,6 @@ namespace NzbDrone.Core.Indexers.Newznab releaseInfo = base.ProcessItem(item, releaseInfo); releaseInfo.ImdbId = GetImdbId(item); - //// This shouldn't be needed with changes to the DownloadDecisionMaker //var imdbMovieTitle = GetImdbTitle(item); //var imdbYear = GetImdbYear(item); @@ -90,7 +92,6 @@ namespace NzbDrone.Core.Indexers.Newznab // releaseInfo.Title = Regex.Replace(releaseInfo.Title, imdbMovieTitle, imdbMovieTitle + "." + imdbYear, RegexOptions.IgnoreCase); // } //} - return releaseInfo; } @@ -162,9 +163,7 @@ namespace NzbDrone.Core.Indexers.Newznab { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase( Parser.Parser.ReplaceGermanUmlauts( - Parser.Parser.NormalizeTitle(imdbTitle).Replace(" ", ".") - ) - ); + Parser.Parser.NormalizeTitle(imdbTitle).Replace(" ", "."))); } return string.Empty; diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs index 8b747203b..820c00c2a 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs @@ -84,17 +84,22 @@ namespace NzbDrone.Core.Indexers.Newznab [FieldDefinition(5, Label = "Additional Parameters", HelpText = "Additional Newznab parameters", Advanced = true)] public string AdditionalParameters { get; set; } - [FieldDefinition(6, Label = "Remove year from search string", - HelpText = "Should Radarr remove the year after the title when searching this indexer?", Advanced = true, Type = FieldType.Checkbox)] + [FieldDefinition(6, + Label = "Remove year from search string", + HelpText = "Should Radarr remove the year after the title when searching this indexer?", + Advanced = true, + Type = FieldType.Checkbox)] public bool RemoveYear { get; set; } - [FieldDefinition(7, Label = "Search by Title", + [FieldDefinition(7, + Label = "Search by Title", HelpText = "By default, Radarr will try to search by IMDB ID if your indexer supports that. However, some indexers are not very good at tagging their releases correctly, so you can force Radarr to search that indexer by title instead.", - Advanced = true, Type = FieldType.Checkbox)] + Advanced = true, + Type = FieldType.Checkbox)] public bool SearchByTitle { get; set; } + // Field 8 is used by TorznabSettings MinimumSeeders // If you need to add another field here, update TorznabSettings as well and this comment - public virtual NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs index 748a33ef6..d2d63cbf0 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Indexers.Nyaa public Nyaa(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs index 8a650f7e6..c1eae6680 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using System.Text.RegularExpressions; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.Indexers.Nyaa { diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs index d957b5cbd..e4f1bb56b 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs @@ -14,7 +14,6 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs public Omgwtfnzbs(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs index a2cb63bd0..b3c345beb 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs @@ -19,9 +19,15 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs var xdoc = LoadXmlDocument(indexerResponse); var notice = xdoc.Descendants("notice").FirstOrDefault(); - if (notice == null) return true; + if (notice == null) + { + return true; + } - if (!notice.Value.ContainsIgnoreCase("api")) return true; + if (!notice.Value.ContainsIgnoreCase("api")) + { + return true; + } throw new ApiKeyException(notice.Value); } @@ -29,8 +35,9 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs protected override string GetInfoUrl(XElement item) { //Todo: Me thinks I need to parse details to get this... - var match = Regex.Match(item.Description(), @"(?:\View NZB\:\<\/b\>\s\.+?)(?:\"")", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + var match = Regex.Match(item.Description(), + @"(?:\View NZB\:\<\/b\>\s\.+?)(?:\"")", + RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success) { diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs index 2d393e72d..786747f63 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs @@ -14,8 +14,12 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn public override bool SupportsSearch => true; public override int PageSize => 50; - public PassThePopcorn(IHttpClient httpClient, ICacheManager cacheManager, IIndexerStatusService indexerStatusService, - IConfigService configService, IParsingService parsingService, Logger logger) + public PassThePopcorn(IHttpClient httpClient, + ICacheManager cacheManager, + IIndexerStatusService indexerStatusService, + IConfigService configService, + IParsingService parsingService, + Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs index 3c1be48c9..4ff21e026 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs @@ -61,7 +61,5 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn public string Result { get; set; } public string Popcron { get; set; } public string AntiCsrfToken { get; set; } - } - } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs index 9caec8fed..d675d8fd3 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs @@ -2,11 +2,11 @@ using System; using System.Collections.Generic; using System.Net; using Newtonsoft.Json; +using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; -using NLog; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Indexers.PassThePopcorn { @@ -33,6 +33,7 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn CookiesUpdater(null, null); throw new IndexerException(indexerResponse, "We are being redirected to the PTP login page. Most likely your session expired or was killed. Try testing the indexer in the settings."); } + throw new IndexerException(indexerResponse, $"Unexpected response status {indexerResponse.HttpResponse.StatusCode} code from API request"); } @@ -43,6 +44,7 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn CookiesUpdater(null, null); throw new IndexerException(indexerResponse, "We are currently on the login page. Most likely your session expired or was killed. Try testing the indexer in the settings."); } + // Remove cookie cache throw new IndexerException(indexerResponse, $"Unexpected response header {indexerResponse.HttpResponse.Headers.ContentType} from API request, expected {HttpAccept.Json.Value}"); } @@ -55,7 +57,6 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn return torrentInfos; } - foreach (var result in jsonResponse.Movies) { foreach (var torrent in result.Torrents) @@ -66,12 +67,12 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn if (torrent.GoldenPopcorn) { - flags |= IndexerFlags.PTP_Golden;//title = $"{title} 🍿"; + flags |= IndexerFlags.PTP_Golden; //title = $"{title} 🍿"; } if (torrent.Checked) { - flags |= IndexerFlags.PTP_Approved;//title = $"{title} ✔"; + flags |= IndexerFlags.PTP_Approved; //title = $"{title} ✔"; } if (torrent.FreeleechType == "Freeleech") @@ -100,7 +101,7 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn Golden = torrent.GoldenPopcorn, Scene = torrent.Scene, Approved = torrent.Checked, - ImdbId = (result.ImdbId.IsNotNullOrWhiteSpace() ? int.Parse(result.ImdbId) : 0), + ImdbId = result.ImdbId.IsNotNullOrWhiteSpace() ? int.Parse(result.ImdbId) : 0, IndexerFlags = flags }); } @@ -116,13 +117,11 @@ namespace NzbDrone.Core.Indexers.PassThePopcorn "}. Please immediately report this info on https://github.com/Radarr/Radarr/issues/1584."); throw; } - - } } + return torrentInfos; - } public Action, DateTime?> CookiesUpdater { get; set; } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs index 8a19112c1..d0e91f161 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs @@ -1,15 +1,14 @@ using System; using System.Collections.Generic; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; +using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.Indexers.PassThePopcorn { public class PassThePopcornRequestGenerator : IIndexerRequestGenerator { - public PassThePopcornSettings Settings { get; set; } public IDictionary Cookies { get; set; } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs index 44f50adf8..89b82e080 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs @@ -23,6 +23,7 @@ namespace NzbDrone.Core.Indexers.Rarbg { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -53,7 +54,7 @@ namespace NzbDrone.Core.Indexers.Rarbg torrentInfo.Title = torrent.title; torrentInfo.Size = torrent.size; torrentInfo.DownloadUrl = torrent.download; - torrentInfo.InfoUrl = torrent.info_page + "&app_id=Radarr"; ; + torrentInfo.InfoUrl = torrent.info_page + "&app_id=Radarr"; torrentInfo.PublishDate = torrent.pubdate.ToUniversalTime(); torrentInfo.Seeders = torrent.seeders; torrentInfo.Peers = torrent.leechers + torrent.seeders; @@ -92,6 +93,5 @@ namespace NzbDrone.Core.Indexers.Rarbg return string.Format("rarbg-{0}", torrent.download); } } - } } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs index 0314a2115..1881e0479 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using NzbDrone.Common.EnvironmentInfo; using System.Linq; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.IndexerSearch.Definitions; @@ -96,7 +96,6 @@ namespace NzbDrone.Core.Indexers.Rarbg requestBuilder.AddQueryParam("search_string", $"{searchCriteria.Movie.Title} {searchCriteria.Movie.Year}"); } - if (!Settings.RankedOnly) { requestBuilder.AddQueryParam("ranked", "0"); diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs index 44aa87599..b4d84ff81 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs @@ -27,7 +27,8 @@ namespace NzbDrone.Core.Indexers.Rarbg public string GetToken(RarbgSettings settings) { - return _tokenCache.Get(settings.BaseUrl, () => + return _tokenCache.Get(settings.BaseUrl, + () => { var requestBuilder = new HttpRequestBuilder(settings.BaseUrl.Trim('/')) .WithRateLimit(3.0) @@ -43,7 +44,8 @@ namespace NzbDrone.Core.Indexers.Rarbg var response = _httpClient.Get(requestBuilder.Build()); return response.Resource["token"].ToString(); - }, TimeSpan.FromMinutes(14.0)); + }, + TimeSpan.FromMinutes(14.0)); } } } diff --git a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs index 87788e366..7897af38f 100644 --- a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs @@ -14,7 +14,6 @@ namespace NzbDrone.Core.Indexers _baseUrl = baseUrl; } - public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/RssParser.cs b/src/NzbDrone.Core/Indexers/RssParser.cs index d92e249b3..8ae83a624 100644 --- a/src/NzbDrone.Core/Indexers/RssParser.cs +++ b/src/NzbDrone.Core/Indexers/RssParser.cs @@ -232,6 +232,7 @@ namespace NzbDrone.Core.Indexers { return GetEnclosureLength(item); } + if (ParseSizeInDescription && item.Element("description") != null) { return ParseSize(item.Element("description").Value, true); @@ -260,11 +261,11 @@ namespace NzbDrone.Core.Indexers try { return new RssEnclosure - { - Url = v.Attribute("url").Value, - Type = v.Attribute("type").Value, - Length = (long)v.Attribute("length") - }; + { + Url = v.Attribute("url").Value, + Type = v.Attribute("type").Value, + Length = (long)v.Attribute("length") + }; } catch (Exception e) { @@ -394,6 +395,7 @@ namespace NzbDrone.Core.Indexers return (long)value; } } + return 0; } diff --git a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs index aad80d1ce..47b9cca67 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Indexers { public class RssSyncCommand : Command { - public override bool SendUpdatesToClient => true; } } diff --git a/src/NzbDrone.Core/Indexers/RssSyncService.cs b/src/NzbDrone.Core/Indexers/RssSyncService.cs index 27c0256e4..8f4a07a04 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncService.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncService.cs @@ -39,7 +39,6 @@ namespace NzbDrone.Core.Indexers _logger = logger; } - private ProcessedDecisions Sync() { _logger.ProgressInfo("Starting RSS Sync"); diff --git a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs index 284a99b54..e61116feb 100644 --- a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs +++ b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs @@ -21,8 +21,15 @@ namespace NzbDrone.Core.Indexers public TorrentSeedConfiguration GetSeedConfiguration(RemoteMovie remoteMovie) { - if (remoteMovie.Release.DownloadProtocol != DownloadProtocol.Torrent) return null; - if (remoteMovie.Release.IndexerId == 0) return null; + if (remoteMovie.Release.DownloadProtocol != DownloadProtocol.Torrent) + { + return null; + } + + if (remoteMovie.Release.IndexerId == 0) + { + return null; + } try { diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs index fb3f9b4e0..a1aebdb26 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Core.Indexers.TorrentPotato public TorrentPotato(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } private IndexerDefinition GetDefinition(string name, TorrentPotatoSettings settings) @@ -44,7 +43,5 @@ namespace NzbDrone.Core.Indexers.TorrentPotato { return new TorrentPotatoParser(); } - - } } diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs index 14aeb132c..847a965d3 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs @@ -23,6 +23,7 @@ namespace NzbDrone.Core.Indexers.TorrentPotato { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -34,7 +35,7 @@ namespace NzbDrone.Core.Indexers.TorrentPotato torrentInfo.Guid = GetGuid(torrent); torrentInfo.Title = torrent.release_name; - torrentInfo.Size = (long)torrent.size*1000*1000; + torrentInfo.Size = (long)torrent.size * 1000 * 1000; torrentInfo.DownloadUrl = torrent.download_url; torrentInfo.InfoUrl = torrent.details_url; torrentInfo.PublishDate = torrent.publish_date.ToUniversalTime(); @@ -63,6 +64,5 @@ namespace NzbDrone.Core.Indexers.TorrentPotato return string.Format("potato-{0}", torrent.download_url); } } - } } diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs index d404516b6..1879a8933 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs @@ -8,12 +8,10 @@ namespace NzbDrone.Core.Indexers.TorrentPotato { public class TorrentPotatoRequestGenerator : IIndexerRequestGenerator { - public TorrentPotatoSettings Settings { get; set; } public TorrentPotatoRequestGenerator() { - } public virtual IndexerPageableRequestChain GetRecentRequests() diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs index b9d6dc527..ca89524eb 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs @@ -2,7 +2,6 @@ using System; namespace NzbDrone.Core.Indexers.TorrentPotato { - public class TorrentPotatoResponse { public Result[] results { get; set; } @@ -22,5 +21,4 @@ namespace NzbDrone.Core.Indexers.TorrentPotato public int seeders { get; set; } public DateTime publish_date { get; set; } } - } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs index 4c1dc64f0..5103d5c6d 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public class TorrentRssIndexerSettings : ITorrentIndexerSettings { - private static readonly TorrentRssIndexerSettingsValidator validator = new TorrentRssIndexerSettingsValidator(); + private static readonly TorrentRssIndexerSettingsValidator Validator = new TorrentRssIndexerSettingsValidator(); public TorrentRssIndexerSettings() { @@ -34,7 +34,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss [FieldDefinition(1, Label = "Cookie", HelpText = "If you site requires a login cookie to access the rss, you'll have to retrieve it via a browser.")] public string Cookie { get; set; } - [FieldDefinition(2, Type = FieldType.Checkbox, Label = "Allow Zero Size", HelpText="Enabling this will allow you to use feeds that don't specify release size, but be careful, size related checks will not be performed.")] + [FieldDefinition(2, Type = FieldType.Checkbox, Label = "Allow Zero Size", HelpText = "Enabling this will allow you to use feeds that don't specify release size, but be careful, size related checks will not be performed.")] public bool AllowZeroSize { get; set; } // [FieldDefinition(3, Type = FieldType.Tag, SelectOptions = typeof(Language), Label = "Multi Languages", HelpText = "What languages are normally in a multi release on this indexer?", Advanced = true)] @@ -51,7 +51,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public NzbDroneValidationResult Validate() { - return new NzbDroneValidationResult(validator.Validate(this)); + return new NzbDroneValidationResult(Validator.Validate(this)); } } } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs index 6c85e4758..35d2fd5f6 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.IO; +using System.Linq; using System.Xml; using System.Xml.Linq; using NLog; @@ -18,12 +18,12 @@ namespace NzbDrone.Core.Indexers.TorrentRss public class TorrentRssSettingsDetector : ITorrentRssSettingsDetector { + private const long ValidSizeThreshold = 2 * 1024 * 1024; + protected readonly Logger _logger; private readonly IHttpClient _httpClient; - private const long ValidSizeThreshold = 2 * 1024 * 1024; - public TorrentRssSettingsDetector(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; @@ -174,6 +174,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss { _logger.Debug("Feed {0} contains very small releases.", response.Request.Url); } + _logger.Trace("Feed has valid size in description."); return settings; } @@ -235,7 +236,6 @@ namespace NzbDrone.Core.Indexers.TorrentRss { var releases = parser.ParseResponse(response).Cast().ToArray(); return releases; - } catch (Exception ex) { @@ -270,7 +270,6 @@ namespace NzbDrone.Core.Indexers.TorrentRss if (distinct.Length != total.Length) { - throw new UnsupportedFeedException("Feed contains releases with same guid, rejecting malformed rss feed."); } } diff --git a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs index 0f1f01a21..a5d33c85b 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs @@ -54,17 +54,17 @@ namespace NzbDrone.Core.Indexers.Torznab private IndexerDefinition GetDefinition(string name, TorznabSettings settings) { return new IndexerDefinition - { - EnableRss = false, - EnableAutomaticSearch = false, - EnableInteractiveSearch = false, - Name = name, - Implementation = GetType().Name, - Settings = settings, - Protocol = DownloadProtocol.Usenet, - SupportsRss = SupportsRss, - SupportsSearch = SupportsSearch - }; + { + EnableRss = false, + EnableAutomaticSearch = false, + EnableInteractiveSearch = false, + Name = name, + Implementation = GetType().Name, + Settings = settings, + Protocol = DownloadProtocol.Usenet, + SupportsRss = SupportsRss, + SupportsSearch = SupportsSearch + }; } private TorznabSettings GetSettings(string url, string apiPath = null, int[] categories = null) @@ -87,7 +87,11 @@ namespace NzbDrone.Core.Indexers.Torznab protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } @@ -98,7 +102,9 @@ namespace NzbDrone.Core.Indexers.Torznab foreach (var category in categories) { if (category.Subcategories != null) + { l.AddRange(CategoryIds(category.Subcategories)); + } } return l; @@ -116,7 +122,9 @@ namespace NzbDrone.Core.Indexers.Torznab { _logger.Warn($"{Definition.Name} does not support the following categories: {string.Join(", ", notSupported)}. You should probably remove them."); if (notSupported.Count() == Settings.Categories.Count()) + { return new ValidationFailure(string.Empty, $"This indexer does not support any of the selected categories! (You may need to turn on advanced settings to see them)"); + } } if (capabilities.SupportedSearchParameters != null && capabilities.SupportedSearchParameters.Contains("q")) diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs index 258a12492..4c8836a88 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Torznab { public class TorznabException : NzbDroneException { - public TorznabException(string message, params object[] args) : base(message, args) + public TorznabException(string message, params object[] args) + : base(message, args) { } - public TorznabException(string message) : base(message) + public TorznabException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs index 0d9fd16b7..7ea6839d7 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs @@ -22,12 +22,18 @@ namespace NzbDrone.Core.Indexers.Torznab var xdoc = LoadXmlDocument(indexerResponse); var error = xdoc.Descendants("error").FirstOrDefault(); - if (error == null) return true; + if (error == null) + { + return true; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; - if (code >= 100 && code <= 199) throw new ApiKeyException("Invalid API key"); + if (code >= 100 && code <= 199) + { + throw new ApiKeyException("Invalid API key"); + } if (!indexerResponse.Request.Url.FullUri.Contains("apikey=") && errorMessage == "Missing parameter") { @@ -58,7 +64,6 @@ namespace NzbDrone.Core.Indexers.Torznab return torrentInfo; } - protected override bool PostProcess(IndexerResponse indexerResponse, List items, List releases) { var enclosureTypes = items.SelectMany(GetEnclosures).Select(v => v.Type).Distinct().ToArray(); @@ -122,7 +127,7 @@ namespace NzbDrone.Core.Indexers.Torznab protected virtual string GetImdbId(XElement item) { var imdbIdString = TryGetTorznabAttribute(item, "imdbid"); - return (!imdbIdString.IsNullOrWhiteSpace() ? imdbIdString.Substring(2) : null); + return !imdbIdString.IsNullOrWhiteSpace() ? imdbIdString.Substring(2) : null; } protected override string GetInfoHash(XElement item) diff --git a/src/NzbDrone.Core/Indexers/XElementExtensions.cs b/src/NzbDrone.Core/Indexers/XElementExtensions.cs index ef2b8b064..1c4ca6634 100644 --- a/src/NzbDrone.Core/Indexers/XElementExtensions.cs +++ b/src/NzbDrone.Core/Indexers/XElementExtensions.cs @@ -25,10 +25,7 @@ namespace NzbDrone.Core.Indexers { var res = new XElement( root.Name.LocalName, - root.HasElements ? - root.Elements().Select(StripNameSpace) : - (object)root.Value - ); + root.HasElements ? root.Elements().Select(StripNameSpace) : (object)root.Value); res.ReplaceAttributes( root.Attributes().Where(attr => (!attr.IsNamespaceDeclaration))); @@ -46,6 +43,7 @@ namespace NzbDrone.Core.Indexers dateString = RemoveTimeZoneRegex.Replace(dateString, ""); result = DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); } + return result.ToUniversalTime(); } catch (FormatException e) @@ -109,7 +107,6 @@ namespace NzbDrone.Core.Indexers { return (T)Convert.ChangeType(element.Value, typeof(T)); } - catch (InvalidCastException) { return defaultValue; diff --git a/src/NzbDrone.Core/Indexers/XmlCleaner.cs b/src/NzbDrone.Core/Indexers/XmlCleaner.cs index f40d2e2af..9d1f95654 100644 --- a/src/NzbDrone.Core/Indexers/XmlCleaner.cs +++ b/src/NzbDrone.Core/Indexers/XmlCleaner.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Indexers { public static class XmlCleaner { - private static readonly Regex ReplaceEntitiesRegex = new Regex("&[a-z]+;", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ReplaceUnicodeRegex = new Regex(@"[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]", RegexOptions.Compiled | RegexOptions.IgnoreCase); diff --git a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs index e95095f17..f761f3f7c 100644 --- a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs +++ b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs @@ -1,8 +1,8 @@ using System.Data; using System.Data.SQLite; +using NLog; using NLog.Common; using NLog.Config; -using NLog; using NLog.Targets; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore; @@ -13,11 +13,11 @@ namespace NzbDrone.Core.Instrumentation { public class DatabaseTarget : TargetWithLayout, IHandle { - private readonly IConnectionStringFactory _connectionStringFactory; - - const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + + private const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + "VALUES(@Message,@Time,@Logger,@Exception,@ExceptionType,@Level)"; + private readonly IConnectionStringFactory _connectionStringFactory; + public DatabaseTarget(IConnectionStringFactory connectionStringFactory) { _connectionStringFactory = connectionStringFactory; @@ -101,7 +101,6 @@ namespace NzbDrone.Core.Instrumentation sqlCommand.ExecuteNonQuery(); } } - } catch (SQLiteException ex) { diff --git a/src/NzbDrone.Core/Instrumentation/Log.cs b/src/NzbDrone.Core/Instrumentation/Log.cs index acd421596..91e4710b0 100644 --- a/src/NzbDrone.Core/Instrumentation/Log.cs +++ b/src/NzbDrone.Core/Instrumentation/Log.cs @@ -1,12 +1,10 @@ using System; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.Instrumentation { public class Log : ModelBase { - public string Message { get; set; } public DateTime Time { get; set; } diff --git a/src/NzbDrone.Core/Instrumentation/LogRepository.cs b/src/NzbDrone.Core/Instrumentation/LogRepository.cs index 0400e3b25..69bcbe474 100644 --- a/src/NzbDrone.Core/Instrumentation/LogRepository.cs +++ b/src/NzbDrone.Core/Instrumentation/LogRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Instrumentation { public interface ILogRepository : IBasicRepository diff --git a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs index 27a7a9143..a0c0adead 100644 --- a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs +++ b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs @@ -26,11 +26,17 @@ namespace NzbDrone.Core.Instrumentation LogLevel minimumConsoleLogLevel; if (_configFileProvider.ConsoleLogLevel.IsNotNullOrWhiteSpace()) + { minimumConsoleLogLevel = LogLevel.FromString(_configFileProvider.ConsoleLogLevel); + } else if (minimumLogLevel > LogLevel.Info) + { minimumConsoleLogLevel = minimumLogLevel; + } else + { minimumConsoleLogLevel = LogLevel.Info; + } var rules = LogManager.Configuration.LoggingRules; @@ -64,7 +70,6 @@ namespace NzbDrone.Core.Instrumentation { rule.DisableLoggingForLevel(logLevel); } - else { rule.EnableLoggingForLevel(logLevel); @@ -77,7 +82,7 @@ namespace NzbDrone.Core.Instrumentation var sentryTarget = LogManager.Configuration.AllTargets.OfType().FirstOrDefault(); if (sentryTarget != null) { - sentryTarget.SentryEnabled = RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled || RuntimeInfo.IsDevelopment; + sentryTarget.SentryEnabled = (RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled) || RuntimeInfo.IsDevelopment; sentryTarget.FilterEvents = _configFileProvider.FilterSentryEvents; } } diff --git a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs index 994aedc50..d64178f81 100644 --- a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs +++ b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs @@ -13,7 +13,6 @@ namespace NzbDrone.Core.Instrumentation public SlowRunningAsyncTargetWrapper(Target wrappedTarget) : base(wrappedTarget) { - } protected override void StopLazyWriterThread() @@ -37,7 +36,6 @@ namespace NzbDrone.Core.Instrumentation protected override void StartLazyWriterTimer() { // Is executed when the background task has finished processing the queue. (also executed by base.InitializeTarget once) - if (Interlocked.Decrement(ref _state) == 1) { // There might be more work. Restart timer. base.StartLazyWriterTimer(); diff --git a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs index 90a3e6ecf..4b46b2efc 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs @@ -3,7 +3,6 @@ using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Jobs { public interface IScheduledTaskRepository : IBasicRepository @@ -14,7 +13,6 @@ namespace NzbDrone.Core.Jobs public class ScheduledTaskRepository : BasicRepository, IScheduledTaskRepository { - public ScheduledTaskRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -28,11 +26,11 @@ namespace NzbDrone.Core.Jobs public void SetLastExecutionTime(int id, DateTime executionTime, DateTime startTime) { var task = new ScheduledTask - { - Id = id, - LastExecution = executionTime, - LastStartTime = startTime - }; + { + Id = id, + LastExecution = executionTime, + LastStartTime = startTime + }; SetFields(task, scheduledTask => scheduledTask.LastExecution, scheduledTask => scheduledTask.LastStartTime); } diff --git a/src/NzbDrone.Core/Jobs/Scheduler.cs b/src/NzbDrone.Core/Jobs/Scheduler.cs index 80ddae00d..dffe4dba7 100644 --- a/src/NzbDrone.Core/Jobs/Scheduler.cs +++ b/src/NzbDrone.Core/Jobs/Scheduler.cs @@ -2,11 +2,11 @@ using System.Threading; using System.Threading.Tasks; using NLog; +using NzbDrone.Common.TPL; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using Timer = System.Timers.Timer; -using NzbDrone.Common.TPL; namespace NzbDrone.Core.Jobs { @@ -42,7 +42,6 @@ namespace NzbDrone.Core.Jobs _commandQueueManager.Push(task.TypeName, task.LastExecution, task.LastStartTime, CommandPriority.Low, CommandTrigger.Scheduled); } } - finally { if (!_cancellationTokenSource.IsCancellationRequested) diff --git a/src/NzbDrone.Core/Jobs/TaskManager.cs b/src/NzbDrone.Core/Jobs/TaskManager.cs index e1981f4de..35b5b6d7d 100644 --- a/src/NzbDrone.Core/Jobs/TaskManager.cs +++ b/src/NzbDrone.Core/Jobs/TaskManager.cs @@ -13,10 +13,10 @@ using NzbDrone.Core.Lifecycle; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.NetImport; -using NzbDrone.Core.Movies.Commands; -using NzbDrone.Core.Update.Commands; using NzbDrone.Core.MetadataSource.PreDB; +using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.NetImport; +using NzbDrone.Core.Update.Commands; namespace NzbDrone.Core.Jobs { @@ -71,14 +71,15 @@ namespace NzbDrone.Core.Jobs var defaultTasks = new[] { - new ScheduledTask{ Interval = 1*60, TypeName = typeof(PreDBSyncCommand).FullName}, - new ScheduledTask{ Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName}, - new ScheduledTask{ Interval = updateInterval, TypeName = typeof(ApplicationUpdateCommand).FullName}, - // new ScheduledTask{ Interval = 3*60, TypeName = typeof(UpdateSceneMappingCommand).FullName}, - new ScheduledTask{ Interval = 6*60, TypeName = typeof(CheckHealthCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(RefreshMovieCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(HousekeepingCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(CleanUpRecycleBinCommand).FullName}, + new ScheduledTask { Interval = 1 * 60, TypeName = typeof(PreDBSyncCommand).FullName }, + new ScheduledTask { Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName }, + new ScheduledTask { Interval = updateInterval, TypeName = typeof(ApplicationUpdateCommand).FullName }, + + // new ScheduledTask { Interval = 3 * 60, TypeName = typeof(UpdateSceneMappingCommand).FullName }, + new ScheduledTask { Interval = 6 * 60, TypeName = typeof(CheckHealthCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(RefreshMovieCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(HousekeepingCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(CleanUpRecycleBinCommand).FullName }, new ScheduledTask { diff --git a/src/NzbDrone.Core/Languages/Language.cs b/src/NzbDrone.Core/Languages/Language.cs index 681935a68..149073337 100644 --- a/src/NzbDrone.Core/Languages/Language.cs +++ b/src/NzbDrone.Core/Languages/Language.cs @@ -32,15 +32,30 @@ namespace NzbDrone.Core.Languages public bool Equals(Language other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Language); } @@ -55,34 +70,33 @@ namespace NzbDrone.Core.Languages return !Equals(left, right); } - public static Language Unknown { get { return new Language(0, "Unknown"); } } - public static Language English { get { return new Language(1, "English"); } } - public static Language French { get { return new Language(2, "French"); } } - public static Language Spanish { get { return new Language(3, "Spanish"); } } - public static Language German { get { return new Language(4, "German"); } } - public static Language Italian { get { return new Language(5, "Italian"); } } - public static Language Danish { get { return new Language(6, "Danish"); } } - public static Language Dutch { get { return new Language(7, "Dutch"); } } - public static Language Japanese { get { return new Language(8, "Japanese"); } } - public static Language Icelandic { get { return new Language(9, "Icelandic"); } } - public static Language Chinese { get { return new Language(10, "Chinese"); } } - public static Language Russian { get { return new Language(11, "Russian"); } } - public static Language Polish { get { return new Language(12, "Polish"); } } - public static Language Vietnamese { get { return new Language(13, "Vietnamese"); } } - public static Language Swedish { get { return new Language(14, "Swedish"); } } - public static Language Norwegian { get { return new Language(15, "Norwegian"); } } - public static Language Finnish { get { return new Language(16, "Finnish"); } } - public static Language Turkish { get { return new Language(17, "Turkish"); } } - public static Language Portuguese { get { return new Language(18, "Portuguese"); } } - public static Language Flemish { get { return new Language(19, "Flemish"); } } - public static Language Greek { get { return new Language(20, "Greek"); } } - public static Language Korean { get { return new Language(21, "Korean"); } } - public static Language Hungarian { get { return new Language(22, "Hungarian"); } } - public static Language Hebrew { get { return new Language(23, "Hebrew"); } } - public static Language Lithuanian { get { return new Language(24, "Lithuanian"); } } - public static Language Czech { get { return new Language(25, "Czech"); } } - public static Language Any { get { return new Language(-1, "Any"); } } - + public static Language Unknown => new Language(0, "Unknown"); + public static Language English => new Language(1, "English"); + public static Language French => new Language(2, "French"); + public static Language Spanish => new Language(3, "Spanish"); + public static Language German => new Language(4, "German"); + public static Language Italian => new Language(5, "Italian"); + public static Language Danish => new Language(6, "Danish"); + public static Language Dutch => new Language(7, "Dutch"); + public static Language Japanese => new Language(8, "Japanese"); + public static Language Icelandic => new Language(9, "Icelandic"); + public static Language Chinese => new Language(10, "Chinese"); + public static Language Russian => new Language(11, "Russian"); + public static Language Polish => new Language(12, "Polish"); + public static Language Vietnamese => new Language(13, "Vietnamese"); + public static Language Swedish => new Language(14, "Swedish"); + public static Language Norwegian => new Language(15, "Norwegian"); + public static Language Finnish => new Language(16, "Finnish"); + public static Language Turkish => new Language(17, "Turkish"); + public static Language Portuguese => new Language(18, "Portuguese"); + public static Language Flemish => new Language(19, "Flemish"); + public static Language Greek => new Language(20, "Greek"); + public static Language Korean => new Language(21, "Korean"); + public static Language Hungarian => new Language(22, "Hungarian"); + public static Language Hebrew => new Language(23, "Hebrew"); + public static Language Lithuanian => new Language(24, "Lithuanian"); + public static Language Czech => new Language(25, "Czech"); + public static Language Any => new Language(-1, "Any"); public static List All { @@ -123,7 +137,10 @@ namespace NzbDrone.Core.Languages public static Language FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } Language language = All.FirstOrDefault(v => v.Id == id); diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs index e3b460fb8..8e0d45e15 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Lifecycle { public class ApplicationStartedEvent : IEvent { - } } diff --git a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs index e4d727b0d..9ed36a42e 100644 --- a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs +++ b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.Lifecycle private readonly IServiceProvider _serviceProvider; private readonly Logger _logger; - public LifecycleService(IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, IServiceProvider serviceProvider, diff --git a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs index a8493a178..d6c303d88 100644 --- a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs +++ b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs @@ -1,6 +1,6 @@ -using NzbDrone.Common.Disk; +using NLog; +using NzbDrone.Common.Disk; using NzbDrone.Common.Http; -using NLog; namespace NzbDrone.Core.MediaCover { diff --git a/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs b/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs index 2dac41668..fa3d6cc8a 100644 --- a/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs +++ b/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.MediaCover public EnsureMediaCoversCommand() { - } public EnsureMediaCoversCommand(int movieId) diff --git a/src/NzbDrone.Core/MediaCover/ImageResizer.cs b/src/NzbDrone.Core/MediaCover/ImageResizer.cs index 3e8d36bce..2bb46f33f 100644 --- a/src/NzbDrone.Core/MediaCover/ImageResizer.cs +++ b/src/NzbDrone.Core/MediaCover/ImageResizer.cs @@ -41,7 +41,10 @@ namespace NzbDrone.Core.MediaCover public void Resize(string source, string destination, int height) { - if (!_enabled) return; + if (!_enabled) + { + return; + } try { @@ -57,6 +60,7 @@ namespace NzbDrone.Core.MediaCover { _diskProvider.DeleteFile(destination); } + throw; } } diff --git a/src/NzbDrone.Core/MediaCover/MediaCover.cs b/src/NzbDrone.Core/MediaCover/MediaCover.cs index 22b143b36..459fa6373 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCover.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCover.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; namespace NzbDrone.Core.MediaCover { - public enum MediaCoverTypes { Unknown = 0, diff --git a/src/NzbDrone.Core/MediaCover/MediaCoverService.cs b/src/NzbDrone.Core/MediaCover/MediaCoverService.cs index 9a33141b6..b3e215696 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCoverService.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCoverService.cs @@ -24,6 +24,7 @@ namespace NzbDrone.Core.MediaCover public class MediaCoverService : IHandleAsync, + //IHandleAsync, IHandleAsync, IExecute, @@ -45,7 +46,6 @@ namespace NzbDrone.Core.MediaCover // So limit the number of concurrent resizing tasks private static SemaphoreSlim _semaphore = new SemaphoreSlim((int)Math.Ceiling(Environment.ProcessorCount / 2.0)); - public MediaCoverService(IImageResizer resizer, IHttpClient httpClient, IDiskProvider diskProvider, @@ -224,6 +224,7 @@ namespace NzbDrone.Core.MediaCover //EnsureCovers(message.Movie); _logger.Info("Testing: {0}, {1}", _commandQueue, message.Movie.Id); _commandQueue.Push(new EnsureMediaCoversCommand(message.Movie.Id)); + //_eventAggregator.PublishEvent(new MediaCoversUpdatedEvent(message.Movie)); } diff --git a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs index cef92d62b..ca1f3a49f 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.MediaFiles.Commands { diff --git a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs index 1a1584403..b4a5403c3 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.MediaFiles.Commands { @@ -11,7 +11,7 @@ namespace NzbDrone.Core.MediaFiles.Commands public RenameMovieFolderCommand(List ids) { - MovieIds = ids; + MovieIds = ids; } } } diff --git a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs index 2bf772c47..c3f336043 100644 --- a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs +++ b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs @@ -10,8 +10,8 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; @@ -190,10 +190,8 @@ namespace NzbDrone.Core.MediaFiles var permissions = _configService.FolderChmod; _diskProvider.SetPermissions(path, permissions, _configService.ChownUser, _configService.ChownGroup); } - catch (Exception ex) { - _logger.Warn(ex, "Unable to apply permissions to: " + path); _logger.Debug(ex, ex.Message); } @@ -221,7 +219,6 @@ namespace NzbDrone.Core.MediaFiles var movie = _movieService.GetMovie(message.MovieId.Value); Scan(movie); } - else { var allMovies = _movieService.GetAllMovies(); diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs index 277f69954..6d3bc1989 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; @@ -6,9 +9,6 @@ using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Commands; -using System; -using System.Collections.Generic; -using System.Linq; namespace NzbDrone.Core.MediaFiles { diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs index 7ae4e0284..dcd44ca5b 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs @@ -7,11 +7,11 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; using NzbDrone.Core.Download; using NzbDrone.Core.History; +using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles @@ -172,7 +172,7 @@ namespace NzbDrone.Core.MediaFiles var cleanedUpName = GetCleanedUpFolderName(directoryInfo.Name); var historyItems = _historyService.FindByDownloadId(downloadClientItem?.DownloadId ?? ""); var firstHistoryItem = historyItems?.OrderByDescending(h => h.Date).FirstOrDefault(); - var folderInfo = _parsingService.ParseMovieInfo(cleanedUpName, new List{firstHistoryItem}); + var folderInfo = _parsingService.ParseMovieInfo(cleanedUpName, new List { firstHistoryItem }); if (folderInfo != null) { diff --git a/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs index d5d98b24b..d8ec20ddd 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using NzbDrone.Common.Messaging; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Download; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs index 3e0839cb4..bf60d9be6 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs @@ -52,7 +52,6 @@ namespace NzbDrone.Core.MediaFiles } } } - else { SetMonoPermissions(path, _configService.FileChmod); @@ -87,10 +86,8 @@ namespace NzbDrone.Core.MediaFiles { _diskProvider.SetPermissions(path, permissions, _configService.ChownUser, _configService.ChownGroup); } - catch (Exception ex) { - _logger.Warn(ex, "Unable to apply permissions to: " + path); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs index b85ffaf1b..e63ed0709 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Qualities; - namespace NzbDrone.Core.MediaFiles { public static class MediaFileExtensions @@ -63,12 +62,12 @@ namespace NzbDrone.Core.MediaFiles //HD { ".mkv", Quality.WEBDL720p }, - { ".mk3d", Quality.WEBDL720p}, + { ".mk3d", Quality.WEBDL720p }, { ".ts", Quality.SDTV }, { ".wtv", Quality.SDTV }, //Bluray - { ".m2ts", Quality.Bluray720p} + { ".m2ts", Quality.Bluray720p } }; } @@ -83,6 +82,5 @@ namespace NzbDrone.Core.MediaFiles return Quality.Unknown; } - } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs index 6ef40f409..4864a9ad3 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.MediaFiles { public interface IMediaFileRepository : IBasicRepository @@ -11,7 +10,6 @@ namespace NzbDrone.Core.MediaFiles List GetFilesWithoutMediaInfo(); } - public class MediaFileRepository : BasicRepository, IMediaFileRepository { public MediaFileRepository(IMainDatabase database, IEventAggregator eventAggregator) diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs index 75a6c6d59..0b7f51faf 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs @@ -2,11 +2,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; using NLog; +using NzbDrone.Common; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Common; namespace NzbDrone.Core.MediaFiles { @@ -30,7 +30,8 @@ namespace NzbDrone.Core.MediaFiles private readonly Logger _logger; public MediaFileService(IMediaFileRepository mediaFileRepository, - IEventAggregator eventAggregator, Logger logger) + IEventAggregator eventAggregator, + Logger logger) { _mediaFileRepository = mediaFileRepository; _eventAggregator = eventAggregator; @@ -45,6 +46,7 @@ namespace NzbDrone.Core.MediaFiles { _logger.Error("Movie is null for the file {0}. Please run the houskeeping command to ensure movies and files are linked correctly."); } + //_movieService.SetFileId(addedFile.Movie.Value, addedFile); //Should not be necessary, but sometimes below fails? _eventAggregator.PublishEvent(new MovieFileAddedEvent(addedFile)); @@ -85,7 +87,10 @@ namespace NzbDrone.Core.MediaFiles { var movieFiles = GetFilesByMovie(movie.Id).Select(f => Path.Combine(movie.Path, f.RelativePath)).ToList(); - if (!movieFiles.Any()) return files; + if (!movieFiles.Any()) + { + return files; + } return files.Except(movieFiles, PathEqualityComparer.Instance).ToList(); } @@ -102,10 +107,8 @@ namespace NzbDrone.Core.MediaFiles public void HandleAsync(MovieDeletedEvent message) { - var files = GetFilesByMovie(message.Movie.Id); _mediaFileRepository.DeleteMany(files); - } } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs index 817cbaec7..97cdf650d 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.MediaFiles var filesOnDiskKeys = new HashSet(filesOnDisk, PathEqualityComparer.Instance); - foreach(var movieFile in movieFiles) + foreach (var movieFile in movieFiles) { var movieFilePath = Path.Combine(movie.Path, movieFile.RelativePath); @@ -55,7 +55,6 @@ namespace NzbDrone.Core.MediaFiles // continue; //} } - catch (Exception ex) { var errorMessage = string.Format("Unable to cleanup MovieFile in DB: {0}", movieFile.Id); diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs index 9167a27ed..5fd835753 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs @@ -12,6 +12,9 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { public static class MediaInfoFormatter { + private const string ValidHdrColourPrimaries = "BT.2020"; + private static readonly string[] ValidHdrTransferFunctions = { "PQ", "HLG" }; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(MediaInfoFormatter)); public static decimal FormatAudioChannels(MediaInfoModel mediaInfo) @@ -42,7 +45,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo var audioCodecID = mediaInfo.AudioCodecID ?? string.Empty; var audioProfile = mediaInfo.AudioProfile ?? string.Empty; var audioCodecLibrary = mediaInfo.AudioCodecLibrary ?? string.Empty; - var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (audioFormat.Empty()) { @@ -82,6 +85,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { return "DTS-X"; } + return "DTS-HD MA"; } @@ -457,10 +461,12 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo if (audioChannelPositions.Contains("/")) { - return Regex.Replace(audioChannelPositions, @"^\d+\sobjects", "", + return Regex.Replace(audioChannelPositions, + @"^\d+\sobjects", + "", RegexOptions.Compiled | RegexOptions.IgnoreCase) .Replace("Object Based / ", "") - .Split(new string[] {" / "}, StringSplitOptions.RemoveEmptyEntries) + .Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault() ?.Split('/') .Sum(s => decimal.Parse(s, CultureInfo.InvariantCulture)); @@ -527,9 +533,6 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo return tokens.Last(); } - private static readonly string[] ValidHdrTransferFunctions = {"PQ", "HLG"}; - private const string ValidHdrColourPrimaries = "BT.2020"; - public static string FormatVideoDynamicRange(MediaInfoModel mediaInfo) { // assume SDR by default diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs index 17474c89b..0f25334b8 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs @@ -55,8 +55,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo FileOption_NoRecursive = 0x01, FileOption_CloseAll = 0x02, FileOption_Max = 0x04 - }; - + } public class MediaInfo : IDisposable { @@ -87,6 +86,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { MediaInfo_Delete(_handle); } + GC.SuppressFinalize(this); } @@ -132,7 +132,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo return; } - throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ") ); + throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ")); } } @@ -233,7 +233,8 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo seekStart = seekPos; MediaInfo_Open_Buffer_Init(_handle, stream.Length, seekPos); } - } while (bufferRead > 0); + } + while (bufferRead > 0); MediaInfo_Open_Buffer_Finalize(_handle); @@ -337,7 +338,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo [DllImport("mediainfo")] private static extern IntPtr MediaInfo_State_Get(IntPtr handle); [DllImport("mediainfo")] - private static extern IntPtr MediaInfo_Count_Get(IntPtr handle, IntPtr StreamKind, IntPtr streamNumber); + private static extern IntPtr MediaInfo_Count_Get(IntPtr handle, IntPtr streamKind, IntPtr streamNumber); [DllImport("mediainfo")] private static extern IntPtr MediaInfoA_New(); @@ -364,6 +365,6 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo [DllImport("mediainfo")] private static extern IntPtr MediaInfoA_State_Get(IntPtr handle); [DllImport("mediainfo")] - private static extern IntPtr MediaInfoA_Count_Get(IntPtr handle, IntPtr StreamKind, IntPtr streamNumber); + private static extern IntPtr MediaInfoA_Count_Get(IntPtr handle, IntPtr streamKind, IntPtr streamNumber); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs index 9923671ef..1d028e54a 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs @@ -6,6 +6,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo public class MediaInfoModel : IEmbeddedDocument { public string ContainerFormat { get; set; } + // Deprecated according to MediaInfo public string VideoCodec { get; set; } public string VideoFormat { get; set; } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs index 13c6d7afe..50036e259 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs @@ -1,11 +1,11 @@ using System.IO; +using System.Linq; using NLog; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; -using System.Linq; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MediaFiles.MediaInfo { diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs index 9841d65ce..422c4bc1e 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo _logger = logger; } - public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) @@ -37,7 +36,6 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo MediaInfo mediaInfo = null; // TODO: Cache media info by path, mtime and length so we don't need to read files multiple times - try { mediaInfo = new MediaInfo(); @@ -105,6 +103,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate_Nominal"), out videoBitRate); } + decimal.TryParse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate"), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out videoFrameRate); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitDepth"), out videoBitDepth); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "MultiView_Count"), out videoMultiViewCount); @@ -119,7 +118,6 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo int.TryParse(aBitRate, out audioBitRate); int.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); - string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)").Split(new string[] { " /" }, StringSplitOptions.None)[0].Trim(); var audioChannelPositions = mediaInfo.Get(StreamKind.Audio, 0, "ChannelPositions/String2"); diff --git a/src/NzbDrone.Core/MediaFiles/MovieFile.cs b/src/NzbDrone.Core/MediaFiles/MovieFile.cs index 6e74a16e3..24efa96db 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieFile.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieFile.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using Marr.Data; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles { @@ -43,6 +43,6 @@ namespace NzbDrone.Core.MediaFiles } return string.Empty; -} + } } } diff --git a/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs b/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs index 2751e02e7..48c1ac056 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs @@ -8,9 +8,9 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.MediaFiles { @@ -101,7 +101,7 @@ namespace NzbDrone.Core.MediaFiles private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinationFilePath, TransferMode mode) { Ensure.That(movieFile, () => movieFile).IsNotNull(); - Ensure.That(movie,() => movie).IsNotNull(); + Ensure.That(movie, () => movie).IsNotNull(); Ensure.That(destinationFilePath, () => destinationFilePath).IsValidPath(); var movieFilePath = movieFile.Path ?? Path.Combine(movie.Path, movieFile.RelativePath); @@ -132,7 +132,6 @@ namespace NzbDrone.Core.MediaFiles { _mediaFileAttributeService.SetFolderLastWriteTime(movie.Path, movieFile.DateAdded); } - catch (Exception ex) { _logger.Warn(ex, "Unable to set last write time"); @@ -140,7 +139,7 @@ namespace NzbDrone.Core.MediaFiles _mediaFileAttributeService.SetFilePermissions(destinationFilePath); - if(oldMoviePath != newMoviePath && _diskProvider.FolderExists(oldMoviePath)) + if (oldMoviePath != newMoviePath && _diskProvider.FolderExists(oldMoviePath)) { //Let's move the old files before deleting the old folder. We could just do move folder, but the main file (movie file) is already moved, so eh. var files = _diskProvider.GetFiles(oldMoviePath, SearchOption.AllDirectories); @@ -182,7 +181,8 @@ namespace NzbDrone.Core.MediaFiles private void EnsureMovieFolder(MovieFile movieFile, Movie movie, string filePath) { var movieFolder = Path.GetDirectoryName(filePath); - //movie.Path = movieFolder; + + //movie.Path = movieFolder; var rootFolder = new OsPath(movieFolder).Directory.FullPath; var fileName = Path.GetFileName(filePath); diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs index 8269cf9e2..6bf59aefd 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation { public class AugmentingFailedException : NzbDroneException { - public AugmentingFailedException(string message, params object[] args) : base(message, args) + public AugmentingFailedException(string message, params object[] args) + : base(message, args) { } - public AugmentingFailedException(string message) : base(message) + public AugmentingFailedException(string message) + : base(message) { } - public AugmentingFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public AugmentingFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public AugmentingFailedException(string message, Exception innerException) : base(message, innerException) + public AugmentingFailedException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs index 715f522bc..6c0ba1114 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs @@ -4,8 +4,8 @@ using System.IO; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs index 48601cb1c..cdac2a0df 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators // Get languages in preferred order, download client item, folder and finally file. // Non-English languages will be preferred later, in the event there is a conflict // between parsed languages the more preferred item will be used. - var languages = new List(); languages.AddRange(GetLanguage(localMovie.DownloadClientMovieInfo)); @@ -41,7 +40,6 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators if (parsedMovieInfo == null) { // English is the default language when otherwise unknown - return new List { Language.English }; } diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs index 1d939fa6d..3962c579c 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs @@ -38,21 +38,21 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators foreach (var augmentedQuality in augmentedQualities) { if (augmentedQuality.Source > source || - augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != Source.UNKNOWN) + (augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != Source.UNKNOWN)) { source = augmentedQuality.Source; sourceConfidence = augmentedQuality.SourceConfidence; } if (augmentedQuality.Resolution > resolution || - augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0) + (augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0)) { resolution = augmentedQuality.Resolution; resolutionConfidence = augmentedQuality.ResolutionConfidence; } if (augmentedQuality.Modifier > modifier || - augmentedQuality.ModifierConfidence > modifierConfidence && augmentedQuality.Modifier != Modifier.NONE) + (augmentedQuality.ModifierConfidence > modifierConfidence && augmentedQuality.Modifier != Modifier.NONE)) { modifier = augmentedQuality.Modifier; modifierConfidence = augmentedQuality.ModifierConfidence; diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs index d7876c33f..b1ed51ab8 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs @@ -1,6 +1,6 @@ +using System.Collections.Generic; using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Qualities; -using System.Collections.Generic; namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs index d5d839fd9..2618e69c1 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs @@ -5,14 +5,13 @@ using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; +using NzbDrone.Core.Extras; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Download; -using NzbDrone.Core.Extras; - namespace NzbDrone.Core.MediaFiles.MovieImport { @@ -52,13 +51,11 @@ namespace NzbDrone.Core.MediaFiles.MovieImport //I added a null op for the rare case that the quality is null. TODO: find out why that would even happen in the first place. var qualifiedImports = decisions.Where(c => c.Approved) .GroupBy(c => c.LocalMovie.Movie.Id, (i, s) => s - .OrderByDescending(c => c.LocalMovie.Quality ?? new QualityModel{Quality = Quality.Unknown}, new QualityModelComparer(s.First().LocalMovie.Movie.Profile)) + .OrderByDescending(c => c.LocalMovie.Quality ?? new QualityModel { Quality = Quality.Unknown }, new QualityModelComparer(s.First().LocalMovie.Movie.Profile)) .ThenByDescending(c => c.LocalMovie.Size)) .SelectMany(c => c) .ToList(); - - var importResults = new List(); foreach (var importDecision in qualifiedImports.OrderByDescending(e => e.LocalMovie.Size)) diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs index 618294b78..5b648c0c3 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs @@ -17,6 +17,7 @@ namespace NzbDrone.Core.MediaFiles.MovieImport { LocalMovie = localMovie; Rejections = rejections.ToList(); + //LocalMovie = new LocalMovie //{ // Quality = localMovie.Quality, diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs index 87bea36f9..b3606293a 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs @@ -6,11 +6,10 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; - namespace NzbDrone.Core.MediaFiles.MovieImport { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs index 51cf8a13d..613cc6ca7 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles.MovieImport.Manual { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs index 889ba18fc..c4763fe0a 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs @@ -11,12 +11,12 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; namespace NzbDrone.Core.MediaFiles.MovieImport.Manual { @@ -183,7 +183,7 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Manual return MapItem(new ImportDecision(localMovie, new Rejection("Unknown Movie")), rootFolder, downloadId, null); } - var importDecisions = _importDecisionMaker.GetImportDecisions(new List {file}, movie, downloadClientItem, null, SceneSource(movie, baseFolder)); + var importDecisions = _importDecisionMaker.GetImportDecisions(new List { file }, movie, downloadClientItem, null, SceneSource(movie, baseFolder)); if (importDecisions.Any()) { @@ -274,7 +274,6 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Manual localMovie.Quality = file.Quality; //TODO: Cleanup non-tracked downloads - var importDecision = new ImportDecision(localMovie); if (trackedDownload == null) @@ -288,10 +287,10 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Manual imported.Add(importResult); importedTrackedDownload.Add(new ManuallyImportedFile - { - TrackedDownload = trackedDownload, - ImportResult = importResult - }); + { + TrackedDownload = trackedDownload, + ImportResult = importResult + }); } } @@ -311,7 +310,8 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Manual } } - if (groupedTrackedDownload.Select(c => c.ImportResult).Count(c => c.Result == ImportResultType.Imported) >= Math.Max(1, 1)) //TODO: trackedDownload.RemoteMovie.Movie.Count is always 1? + //TODO: trackedDownload.RemoteMovie.Movie.Count is always 1? + if (groupedTrackedDownload.Select(c => c.ImportResult).Count(c => c.Result == ImportResultType.Imported) >= Math.Max(1, 1)) { trackedDownload.State = TrackedDownloadStage.Imported; _eventAggregator.PublishEvent(new DownloadCompletedEvent(trackedDownload)); diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs index 9fc4b3aea..af0eb0ec7 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Specifications private readonly IConfigService _configService; private readonly Logger _logger; - public FreeSpaceSpecification(IDiskProvider diskProvider, IConfigService configService, Logger logger) + public FreeSpaceSpecification(IDiskProvider diskProvider, IConfigService configService, Logger logger) { _diskProvider = diskProvider; _configService = configService; diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs index c4ec2c200..ca88939b3 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs @@ -16,7 +16,8 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Specifications private readonly IHistoryService _historyService; private readonly IParsingService _parsingService; - public GrabbedReleaseQualitySpecification(Logger logger, IHistoryService historyService, + public GrabbedReleaseQualitySpecification(Logger logger, + IHistoryService historyService, IParsingService parsingService) { _logger = logger; diff --git a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs index 9484765b8..7dd2ac926 100644 --- a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs +++ b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs @@ -27,7 +27,6 @@ namespace NzbDrone.Core.MediaFiles private readonly IConfigService _configService; private readonly Logger _logger; - public RecycleBinProvider(IDiskTransferService diskTransferService, IDiskProvider diskProvider, IConfigService configService, @@ -50,7 +49,6 @@ namespace NzbDrone.Core.MediaFiles _diskProvider.DeleteFolder(path, true); _logger.Debug("Folder has been permanently deleted: {0}", path); } - else { var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name); @@ -86,7 +84,6 @@ namespace NzbDrone.Core.MediaFiles _diskProvider.DeleteFile(path); _logger.Debug("File has been permanently deleted: {0}", path); } - else { var fileInfo = new FileInfo(path); diff --git a/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs b/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs index d36b48f7d..ed398f23f 100644 --- a/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs @@ -1,26 +1,26 @@ using System; using System.Collections.Generic; using System.Data.SQLite; -using System.Linq; using System.IO; +using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Movies; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MediaFiles.Commands; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; namespace NzbDrone.Core.MediaFiles { public interface IRenameMovieFileService { List GetRenamePreviews(int movieId); - void RenameMoviePath(Movie movie, bool shouldRenameFiles); + void RenameMoviePath(Movie movie, bool shouldRenameFiles); } public class RenameMovieFileService : IRenameMovieFileService, @@ -65,32 +65,30 @@ namespace NzbDrone.Core.MediaFiles var file = _mediaFileService.GetFilesByMovie(movieId); return GetPreviews(movie, file).OrderByDescending(m => m.MovieId).ToList(); //TODO: Would really like to not have these be lists - } private IEnumerable GetPreviews(Movie movie, List files) { - foreach(var file in files) + foreach (var file in files) { var movieFilePath = Path.Combine(movie.Path, file.RelativePath); var newName = _filenameBuilder.BuildFileName(movie, file); var newPath = _filenameBuilder.BuildFilePath(movie, newName, Path.GetExtension(movieFilePath)); - if(!movieFilePath.PathEquals(newPath, StringComparison.Ordinal)) + if (!movieFilePath.PathEquals(newPath, StringComparison.Ordinal)) { yield return new RenameMovieFilePreview { MovieId = movie.Id, MovieFileId = file.Id, ExistingPath = movieFilePath, + //NewPath = movie.Path.GetRelativePath(newPath) NewPath = newPath }; } - } - } private void RenameFiles(List movieFiles, Movie movie, string oldMoviePath = null) @@ -119,7 +117,6 @@ namespace NzbDrone.Core.MediaFiles _logger.Debug("Renamed movie file: {0}", movieFile); _eventAggregator.PublishEvent(new MovieFileRenamedEvent(movie, movieFile, oldMovieFilePath)); - } catch (SameFilenameException ex) { @@ -142,14 +139,13 @@ namespace NzbDrone.Core.MediaFiles var newFolder = _filenameBuilder.BuildMoviePath(movie); if (newFolder != movie.Path && movie.PathState == MoviePathState.Dynamic) { - if (!_configService.AutoRenameFolders) { _logger.Info("{0}'s movie should be {1} according to your naming config.", movie, newFolder); return; } - _logger.Info("{0}'s movie folder changed to: {1}", movie, newFolder); + _logger.Info("{0}'s movie folder changed to: {1}", movie, newFolder); var oldFolder = movie.Path; movie.Path = newFolder; @@ -162,15 +158,12 @@ namespace NzbDrone.Core.MediaFiles // RenameFiles(movieFiles, movie, oldFolder); // _logger.ProgressInfo("All movie files renamed for {0}", movie.Title); // } - _movieService.UpdateMovie(movie); if (_diskProvider.GetFiles(oldFolder, SearchOption.AllDirectories).Count() == 0) { _recycleBinProvider.DeleteFolder(oldFolder); } - - } if (movie.PathState == MoviePathState.StaticOnce) @@ -195,34 +188,33 @@ namespace NzbDrone.Core.MediaFiles _logger.Debug("Renaming movie files for selected movie"); var moviesToRename = _movieService.GetMovies(message.MovieIds); - foreach(var movie in moviesToRename) + foreach (var movie in moviesToRename) { var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); _logger.ProgressInfo("Renaming movie files for {0}", movie.Title); RenameFiles(movieFiles, movie); _logger.ProgressInfo("All movie files renamed for {0}", movie.Title); } - } - public void Execute(RenameMovieFolderCommand message) - { - try + public void Execute(RenameMovieFolderCommand message) { - _logger.Debug("Renaming movie folder for selected movie if necessary"); - var moviesToRename = _movieService.GetMovies(message.MovieIds); - foreach(var movie in moviesToRename) + try { - var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); - //_logger.ProgressInfo("Renaming movie folder for {0}", movie.Title); - RenameMoviePath(movie); + _logger.Debug("Renaming movie folder for selected movie if necessary"); + var moviesToRename = _movieService.GetMovies(message.MovieIds); + foreach (var movie in moviesToRename) + { + var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); + + //_logger.ProgressInfo("Renaming movie folder for {0}", movie.Title); + RenameMoviePath(movie); + } + } + catch (SQLiteException ex) + { + _logger.Warn(ex, "wtf: {0}, {1}", ex.ResultCode, ex.Data); } } - catch (SQLiteException ex) - { - _logger.Warn(ex, "wtf: {0}, {1}", ex.ResultCode, ex.Data); - } - - } } } diff --git a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs index c2a8cbd1f..d191bf55d 100644 --- a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs +++ b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs @@ -6,7 +6,8 @@ namespace NzbDrone.Core.MediaFiles { public string Filename { get; set; } - public SameFilenameException(string message, string filename) : base(message) + public SameFilenameException(string message, string filename) + : base(message) { Filename = filename; } diff --git a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs index 996b4211a..a3bb71acc 100644 --- a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.MediaFiles.TorrentInfo string GetHashFromTorrentFile(byte[] fileContents); } - public class TorrentFileInfoReader: ITorrentFileInfoReader + public class TorrentFileInfoReader : ITorrentFileInfoReader { public string GetHashFromTorrentFile(byte[] fileContents) { diff --git a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs index 93da29f05..11078be8b 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.MediaFiles { public interface IUpdateMovieFileQualityService { - } public class UpdateMovieFileQualityService : IUpdateMovieFileQualityService, IExecute @@ -57,7 +56,7 @@ namespace NzbDrone.Core.MediaFiles var sizeMovie = new LocalMovie(); sizeMovie.Size = movieFile.Size; - var helpers = new List{sizeMovie}; + var helpers = new List { sizeMovie }; if (movieFile.MediaInfo != null) { @@ -96,7 +95,6 @@ namespace NzbDrone.Core.MediaFiles count++; } - } } } diff --git a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs index 13ae56519..d2fecfc14 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs @@ -90,7 +90,6 @@ namespace NzbDrone.Core.MediaFiles return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); @@ -130,7 +129,6 @@ namespace NzbDrone.Core.MediaFiles { _logger.ProgressDebug("Changed file date for {0} files of {1} in {2}", updated.Count, movieFiles.Count, message.Movie.Title); } - else { _logger.ProgressDebug("No file dates changed for {0}", message.Movie.Title); @@ -155,14 +153,12 @@ namespace NzbDrone.Core.MediaFiles return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); } } } - else { _logger.Debug("Could not create valid date to change file [{0}]", filePath); @@ -184,7 +180,6 @@ namespace NzbDrone.Core.MediaFiles return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); diff --git a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs index 1ffbcb9f9..883bee45f 100644 --- a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Core.MediaFiles private readonly IRecycleBinProvider _recycleBinProvider; private readonly IMediaFileService _mediaFileService; private readonly IMoveMovieFiles _movieFileMover; - private readonly IRenameMovieFileService _movieFileRenamer; + private readonly IRenameMovieFileService _movieFileRenamer; private readonly IDiskProvider _diskProvider; private readonly Logger _logger; @@ -55,9 +55,9 @@ namespace NzbDrone.Core.MediaFiles _mediaFileService.Delete(existingFile, DeleteMediaFileReason.Upgrade); } - //Temporary for correctly getting path - localMovie.Movie.MovieFileId = 1; - localMovie.Movie.MovieFile = movieFile; + //Temporary for correctly getting path + localMovie.Movie.MovieFileId = 1; + localMovie.Movie.MovieFile = movieFile; if (copyOnly) { @@ -71,8 +71,7 @@ namespace NzbDrone.Core.MediaFiles localMovie.Movie.MovieFileId = existingFile?.Id ?? 0; localMovie.Movie.MovieFile = existingFile; - //_movieFileRenamer.RenameMoviePath(localMovie.Movie, false); - + //_movieFileRenamer.RenameMoviePath(localMovie.Movie, false); return moveFileResult; } } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs index 65f21b935..ea24a29df 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs @@ -10,12 +10,14 @@ namespace NzbDrone.Core.Messaging.Commands private CommandEqualityComparer() { - } public bool Equals(Command x, Command y) { - if(x.GetType() != y.GetType()) return false; + if (x.GetType() != y.GetType()) + { + return false; + } var xProperties = x.GetType().GetProperties(); var yProperties = y.GetType().GetProperties(); @@ -27,7 +29,7 @@ namespace NzbDrone.Core.Messaging.Commands continue; } - if (xProperty.DeclaringType == typeof (Command)) + if (xProperty.DeclaringType == typeof(Command)) { continue; } @@ -60,7 +62,6 @@ namespace NzbDrone.Core.Messaging.Commands return false; } } - else if (!xValue.Equals(yValue)) { return false; diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs index b507229b4..f430aa4df 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs @@ -11,15 +11,16 @@ namespace NzbDrone.Core.Messaging.Commands public class CommandExecutor : IHandle, IHandle { + private const int THREAD_UPPER_BOUND = 10; + private const int THREAD_LOWER_BOUND = 2; + private const int THREAD_LIMIT = 2; + private readonly Logger _logger; private readonly IServiceFactory _serviceFactory; private readonly IManageCommandQueue _commandQueueManager; private readonly IEventAggregator _eventAggregator; private static CancellationTokenSource _cancellationTokenSource; - private const int THREAD_UPPER_BOUND = 10; - private const int THREAD_LOWER_BOUND = 2; - private const int THREAD_LIMIT = 2; public CommandExecutor(IServiceFactory serviceFactory, IManageCommandQueue commandQueueManager, @@ -40,7 +41,7 @@ namespace NzbDrone.Core.Messaging.Commands { try { - ExecuteCommand((dynamic) command.Body, command); + ExecuteCommand((dynamic)command.Body, command); } catch (Exception ex) { @@ -63,7 +64,8 @@ namespace NzbDrone.Core.Messaging.Commands } } - private void ExecuteCommand(TCommand command, CommandModel commandModel) where TCommand : Command + private void ExecuteCommand(TCommand command, CommandModel commandModel) + where TCommand : Command { var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType()); var handler = (IExecute)_serviceFactory.Build(handlerContract); @@ -125,7 +127,10 @@ namespace NzbDrone.Core.Messaging.Commands var envLimit = Environment.GetEnvironmentVariable("THREAD_LIMIT") ?? $"{THREAD_LIMIT}"; int threadLimit = THREAD_LIMIT; - if (int.TryParse(envLimit, out int parsedLimit)) threadLimit = parsedLimit; + if (int.TryParse(envLimit, out int parsedLimit)) + { + threadLimit = parsedLimit; + } threadLimit = Math.Max(THREAD_LOWER_BOUND, threadLimit); threadLimit = Math.Min(THREAD_UPPER_BOUND, threadLimit); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs index 3dcbf60cc..cfb41883f 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Messaging.Commands { public class CommandFailedException : NzbDroneException { - public CommandFailedException(string message, params object[] args) : base(message, args) + public CommandFailedException(string message, params object[] args) + : base(message, args) { } - public CommandFailedException(string message) : base(message) + public CommandFailedException(string message) + : base(message) { } - public CommandFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CommandFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CommandFailedException(string message, Exception innerException) : base(message, innerException) + public CommandFailedException(string message, Exception innerException) + : base(message, innerException) { } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs index 656037138..503dadadf 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs @@ -8,6 +8,5 @@ namespace NzbDrone.Core.Messaging.Commands : base("Couldn't find command " + contract) { } - } } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs index 0aef57ac6..d8489785d 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs @@ -70,6 +70,7 @@ namespace NzbDrone.Core.Messaging.Commands } } } + public bool RemoveIfQueued(int id) { var rval = false; @@ -137,27 +138,32 @@ namespace NzbDrone.Core.Messaging.Commands return c.Status == CommandStatus.Queued && !c.Body.RequiresDiskAccess; } + return c.Status == CommandStatus.Queued; }) .OrderByDescending(c => c.Priority) .ThenBy(c => c.QueuedAt) .FirstOrDefault(); + // Nothing queued that meets the requirements if (localItem == null) { rval = false; } + // If any executing command is exclusive don't want return another command until it completes. else if (startedCommands.Any(c => c.Body.IsExclusive)) { rval = false; } + // If the next command to execute is exclusive wait for executing commands to complete. // This will prevent other tasks from starting so the exclusive task executes in the order it should. else if (localItem.Body.IsExclusive && startedCommands.Any()) { rval = false; } + // A command ready to execute else { diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs index 6095d3b4e..e8fc4cf58 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs @@ -1,22 +1,24 @@ -using NLog; -using NzbDrone.Common; -using NzbDrone.Common.EnsureThat; -using NzbDrone.Common.Serializer; -using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Messaging.Events; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; +using NLog; +using NzbDrone.Common; +using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Messaging.Commands { public interface IManageCommandQueue { - List PushMany(List commands) where TCommand : Command; - CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command; + List PushMany(List commands) + where TCommand : Command; + CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command; CommandModel Push(string commandName, DateTime? lastExecutionTime, DateTime? lastStartTime, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified); IEnumerable Queue(CancellationToken cancellationToken); List All(); @@ -50,7 +52,8 @@ namespace NzbDrone.Core.Messaging.Commands _commandQueue = new CommandQueue(); } - public List PushMany(List commands) where TCommand : Command + public List PushMany(List commands) + where TCommand : Command { _logger.Trace("Publishing {0} commands", commands.Count); @@ -89,7 +92,8 @@ namespace NzbDrone.Core.Messaging.Commands return commandModels; } - public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command + public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command { Ensure.That(command, () => command).IsNotNull(); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs b/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs index 173d6c6eb..7c6460cbc 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs @@ -39,9 +39,8 @@ namespace NzbDrone.Core.Messaging.Commands { using (var mapper = _database.GetDataMapper()) { - - mapper.Parameters.Add(new SQLiteParameter("@orphaned", (int) CommandStatus.Orphaned)); - mapper.Parameters.Add(new SQLiteParameter("@started", (int) CommandStatus.Started)); + mapper.Parameters.Add(new SQLiteParameter("@orphaned", (int)CommandStatus.Orphaned)); + mapper.Parameters.Add(new SQLiteParameter("@started", (int)CommandStatus.Started)); mapper.Parameters.Add(new SQLiteParameter("@ended", DateTime.UtcNow)); mapper.ExecuteNonQuery(@"UPDATE Commands diff --git a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs index fa93c8344..63bcc02d6 100644 --- a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs @@ -1,6 +1,7 @@ namespace NzbDrone.Core.Messaging.Commands { - public interface IExecute : IProcessMessage where TCommand : Command + public interface IExecute : IProcessMessage + where TCommand : Command { void Execute(TCommand message); } diff --git a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs index 4f49324a9..f660cd790 100644 --- a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs @@ -17,7 +17,8 @@ namespace NzbDrone.Core.Messaging.Events private readonly TaskFactory _taskFactory; private readonly Dictionary _eventSubscribers; - private class EventSubscribers where TEvent : class, IEvent + private class EventSubscribers + where TEvent : class, IEvent { private IServiceFactory _serviceFactory; @@ -49,7 +50,8 @@ namespace NzbDrone.Core.Messaging.Events _eventSubscribers = new Dictionary(); } - public void PublishEvent(TEvent @event) where TEvent : class, IEvent + public void PublishEvent(TEvent @event) + where TEvent : class, IEvent { Ensure.That(@event, () => @event).IsNotNull(); @@ -137,21 +139,22 @@ namespace NzbDrone.Core.Messaging.Events return string.Format("{0}<{1}>", eventType.Name.Remove(eventType.Name.IndexOf('`')), eventType.GetGenericArguments()[0].Name); } - internal static int GetEventHandleOrder(IHandle eventHandler) where TEvent : class, IEvent + internal static int GetEventHandleOrder(IHandle eventHandler) + where TEvent : class, IEvent { // TODO: Convert "Handle" to nameof(eventHandler.Handle) after .net 4.5 - var method = eventHandler.GetType().GetMethod("Handle", new Type[] {typeof(TEvent)}); + var method = eventHandler.GetType().GetMethod("Handle", new Type[] { typeof(TEvent) }); if (method == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } var attribute = method.GetCustomAttributes(typeof(EventHandleOrderAttribute), true).FirstOrDefault() as EventHandleOrderAttribute; if (attribute == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } return (int)attribute.EventHandleOrder; diff --git a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs index 7a83cbbf7..924cac454 100644 --- a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs @@ -4,6 +4,7 @@ namespace NzbDrone.Core.Messaging.Events { public interface IEventAggregator { - void PublishEvent(TEvent @event) where TEvent : class, IEvent; + void PublishEvent(TEvent @event) + where TEvent : class, IEvent; } } diff --git a/src/NzbDrone.Core/Messaging/Events/IHandle.cs b/src/NzbDrone.Core/Messaging/Events/IHandle.cs index dc389a18f..17c232e62 100644 --- a/src/NzbDrone.Core/Messaging/Events/IHandle.cs +++ b/src/NzbDrone.Core/Messaging/Events/IHandle.cs @@ -2,12 +2,14 @@ using NzbDrone.Common.Messaging; namespace NzbDrone.Core.Messaging.Events { - public interface IHandle : IProcessMessage where TEvent : IEvent + public interface IHandle : IProcessMessage + where TEvent : IEvent { void Handle(TEvent message); } - public interface IHandleAsync : IProcessMessageAsync where TEvent : IEvent + public interface IHandleAsync : IProcessMessageAsync + where TEvent : IEvent { void HandleAsync(TEvent message); } diff --git a/src/NzbDrone.Core/Messaging/IProcessMessage.cs b/src/NzbDrone.Core/Messaging/IProcessMessage.cs index 4a4b3d80c..f0463ce2e 100644 --- a/src/NzbDrone.Core/Messaging/IProcessMessage.cs +++ b/src/NzbDrone.Core/Messaging/IProcessMessage.cs @@ -1,10 +1,18 @@ namespace NzbDrone.Core.Messaging { - public interface IProcessMessage { } + public interface IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessage { } + public interface IProcessMessageAsync : IProcessMessage + { + } - public interface IProcessMessage : IProcessMessage { } + public interface IProcessMessage : IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessageAsync { } + public interface IProcessMessageAsync : IProcessMessageAsync + { + } } diff --git a/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs b/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs index ad12c0c8c..c86d2f55a 100644 --- a/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs +++ b/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; -using NzbDrone.Core.Profiles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.MetadataSource { public interface IProvideMovieInfo { - Movie GetMovieInfo(string ImdbId); - Movie GetMovieInfo(int TmdbId, Profile profile, bool hasPreDBEntry); + Movie GetMovieInfo(string imdbId); + Movie GetMovieInfo(int tmdbId, Profile profile, bool hasPreDBEntry); HashSet GetChangedMovies(DateTime startTime); } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs index eda48e628..3a6d6593a 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs @@ -1,9 +1,8 @@ namespace NzbDrone.Core.MetadataSource.PreDB { - class PreDBResult + internal class PreDBResult { public string Title { get; set; } public string Link { get; set; } - } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs index 9ffe1e4ee..8ec39ba4a 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using NLog; +using NzbDrone.Common.Http; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Indexers; -using NzbDrone.Common.Http; using NzbDrone.Core.Movies; -using System; using NzbDrone.Core.Parser; -using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.MetadataSource.PreDB { @@ -131,9 +131,6 @@ namespace NzbDrone.Core.MetadataSource.PreDB return matches; } - - - private List Sync() { _logger.ProgressInfo("Starting PreDB Sync"); @@ -168,33 +165,33 @@ namespace NzbDrone.Core.MetadataSource.PreDB public bool HasReleases(Movie movie) { - try - { - var results = GetResults("movies", movie.Title); - - foreach (PreDBResult result in results) + try { - var parsed = Parser.Parser.ParseMovieTitle(result.Title, true); - if (parsed == null) - { - parsed = new Parser.Model.ParsedMovieInfo { MovieTitle = result.Title, Year = 0 }; - } - var match = _parsingService.Map(parsed, "", new MovieSearchCriteria { Movie = movie }); + var results = GetResults("movies", movie.Title); - if (match != null && match.RemoteMovie.Movie != null && match.RemoteMovie.Movie.Id == movie.Id) + foreach (PreDBResult result in results) { - return true; + var parsed = Parser.Parser.ParseMovieTitle(result.Title, true); + if (parsed == null) + { + parsed = new Parser.Model.ParsedMovieInfo { MovieTitle = result.Title, Year = 0 }; + } + + var match = _parsingService.Map(parsed, "", new MovieSearchCriteria { Movie = movie }); + + if (match != null && match.RemoteMovie.Movie != null && match.RemoteMovie.Movie.Id == movie.Id) + { + return true; + } } + + return false; + } + catch (Exception ex) + { + _logger.Warn(ex, "Error while looking on predb.me."); + return false; } - - return false; - } - catch (Exception ex) - { - _logger.Warn(ex, "Error while looking on predb.me."); - return false; - } - } } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs index fffb532fc..89438e819 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.MetadataSource.PreDB { public class PreDBSyncCommand : Command { - public override bool SendUpdatesToClient => true; } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs index c1d4b9d1b..5311b2170 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Messaging; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Messaging; using NzbDrone.Core.Movies; namespace NzbDrone.Core.MetadataSource.PreDB diff --git a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs index e4f95e6d2..a0860d1a4 100644 --- a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs +++ b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs @@ -1,9 +1,9 @@ -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; using System; -using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; +using Newtonsoft.Json; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MetadataSource.SkyHook.Resource; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser; @@ -14,9 +14,9 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI { IHttpRequestBuilderFactory RadarrAPI { get; } List DiscoverMovies(string action, Func enhanceRequest); - List AlternativeTitlesForMovie(int TmdbId); + List AlternativeTitlesForMovie(int tmdbId); Tuple, AlternativeYear> AlternativeTitlesAndYearForMovie(int tmdbId); - AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int TmdbId); + AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int tmdbId); AlternativeYear AddNewAlternativeYear(int year, int tmdbId); string APIURL { get; } } @@ -40,7 +40,7 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI APIURL = "https://api.radarr.video/v2"; } - RadarrAPI = new HttpRequestBuilder(APIURL+"/{route}/{action}") + RadarrAPI = new HttpRequestBuilder(APIURL + "/{route}/{action}") .CreateFactory(); } @@ -82,7 +82,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI //No error! } - if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new HttpException(request, response); @@ -91,7 +90,7 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI return JsonConvert.DeserializeObject(response.Content); } - public List DiscoverMovies(string action, Func enhanceRequest = null ) + public List DiscoverMovies(string action, Func enhanceRequest = null) { var request = RadarrAPI.Create().SetSegment("route", "discovery").SetSegment("action", action).Build(); @@ -103,10 +102,9 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI return Execute>(request); } - - public List AlternativeTitlesForMovie(int TmdbId) + public List AlternativeTitlesForMovie(int tmdbId) { - var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "find").AddQueryParam("tmdbid", TmdbId).Build(); + var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "find").AddQueryParam("tmdbid", tmdbId).Build(); var mappings = Execute(request); @@ -149,10 +147,10 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI return new Tuple, AlternativeYear>(titles, newYear); } - public AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int TmdbId) + public AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int tmdbId) { var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "add") - .AddQueryParam("tmdbid", TmdbId).AddQueryParam("type", "title") + .AddQueryParam("tmdbid", tmdbId).AddQueryParam("type", "title") .AddQueryParam("language", IsoLanguages.Get(title.Language).TwoLetterCode) .AddQueryParam("aka_title", title.Title).Build(); diff --git a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs index f948ff489..5c14c86ba 100644 --- a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs +++ b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs @@ -29,7 +29,8 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI { public RadarrError APIErrors; - public RadarrAPIException(RadarrError apiError) : base(HumanReadable(apiError)) + public RadarrAPIException(RadarrError apiError) + : base(HumanReadable(apiError)) { APIErrors = apiError; } @@ -41,13 +42,12 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI { return $"{error.Title} ({error.Status}, RayId: {error.RayId}), Details: {error.Detail}"; })); - return $"Error while calling api: {firstError.Title}\nFull error(s): {details}"; + return $"Error while calling api: {firstError.Title}\nFull error(s): {details}"; } } public class TitleInfo { - [JsonProperty("id")] public int Id { get; set; } @@ -60,7 +60,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class YearInfo { - [JsonProperty("id")] public int Id { get; set; } @@ -70,7 +69,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class Title { - [JsonProperty("id")] public int Id { get; set; } @@ -98,7 +96,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class Year { - [JsonProperty("id")] public int Id { get; set; } @@ -126,7 +123,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class Mappings { - [JsonProperty("titles")] public IList Titles { get; set; } @@ -136,7 +132,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class Mapping { - [JsonProperty("id")] public int Id { get; set; } @@ -152,7 +147,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class AddTitleMapping { - [JsonProperty("tmdbid")] public string Tmdbid { get; set; } @@ -180,7 +174,6 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI public class AddYearMapping { - [JsonProperty("tmdbid")] public string Tmdbid { get; set; } @@ -205,5 +198,4 @@ namespace NzbDrone.Core.MetadataSource.RadarrAPI [JsonProperty("locked")] public bool Locked { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs b/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs index 16a1a6bc7..50bd18bbd 100644 --- a/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs +++ b/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs @@ -39,23 +39,38 @@ namespace NzbDrone.Core.MetadataSource // Prefer exact matches result = Compare(x, y, s => CleanPunctuation(s.Title).Equals(CleanPunctuation(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Remove Articles (a/an/the) result = Compare(x, y, s => CleanArticles(s.Title).Equals(CleanArticles(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Prefer close matches result = Compare(x, y, s => CleanPunctuation(s.Title).LevenshteinDistance(CleanPunctuation(SearchQuery)) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare clean matches by year "Battlestar Galactica 1978" result = CompareWithYear(x, y, s => CleanTitle(s.Title).LevenshteinDistance(_searchQueryWithoutYear) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare prefix matches by year "(CSI: ..." result = CompareWithYear(x, y, s => s.Title.ToLowerInvariant().StartsWith(_searchQueryWithoutYear + ":")); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } return Compare(x, y, s => SearchQuery.LevenshteinDistanceClean(s.Title) - GetYearFactor(s)); } @@ -79,7 +94,10 @@ namespace NzbDrone.Core.MetadataSource if (_year.HasValue) { var result = Compare(x, y, s => s.Year == _year.Value); - if (result != 0) return result; + if (result != 0) + { + return result; + } } return Compare(x, y, s => s.Year); @@ -117,7 +135,7 @@ namespace NzbDrone.Core.MetadataSource var offset = Math.Abs(movie.Year - _year.Value); if (offset <= 1) { - return 20 - 10 * offset; + return 20 - (10 * offset); } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs index 07c5ce01d..f04bc38e1 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs @@ -1,6 +1,5 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { - public class ConfigResource { public Images images { get; set; } @@ -17,5 +16,4 @@ public string[] profile_sizes { get; set; } public string[] still_sizes { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs index 5319bb202..2ede0ad86 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs @@ -1,19 +1,19 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { public class ImdbResource - { - public int v { get; set; } - public string q { get; set; } - public MovieResource[] d { get; set; } - } + { + public int v { get; set; } + public string q { get; set; } + public MovieResource[] d { get; set; } + } - public class MovieResource - { - public string l { get; set; } - public string id { get; set; } - public string s { get; set; } - public int y { get; set; } - public string q { get; set; } - public object[] i { get; set; } - } + public class MovieResource + { + public string l { get; set; } + public string id { get; set; } + public string s { get; set; } + public int y { get; set; } + public string q { get; set; } + public object[] i { get; set; } + } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs index cad37f8e2..6c4c3c476 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs @@ -2,11 +2,11 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { - public class FindRoot { public MovieResult[] movie_results { get; set; } } + public class MovieSearchRoot { public int page { get; set; } @@ -37,7 +37,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public string physical_release_note { get; set; } } - public class MovieResourceRoot { public bool adult { get; set; } @@ -173,5 +172,4 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public string name { get; set; } public string original_name { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs index a9591fd6b..aabfe757f 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { public class SkyHookException : NzbDroneClientException { - public SkyHookException(string message) : base(HttpStatusCode.ServiceUnavailable, message) + public SkyHookException(string message) + : base(HttpStatusCode.ServiceUnavailable, message) { } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs index e471eaa6a..6dc182a92 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs @@ -1,24 +1,24 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Net; +using System.Threading; using NLog; using NzbDrone.Common.Cloud; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.MediaCover; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; -using NzbDrone.Core.MetadataSource.PreDB; -using NzbDrone.Core.Movies; -using System.Threading; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.MediaCover; +using NzbDrone.Core.MetadataSource.PreDB; using NzbDrone.Core.MetadataSource.RadarrAPI; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; -using System.Globalization; +using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.MetadataSource.SkyHook { @@ -35,8 +35,15 @@ namespace NzbDrone.Core.MetadataSource.SkyHook private readonly IAlternativeTitleService _altTitleService; private readonly IRadarrAPIClient _radarrAPI; - public SkyHookProxy(IHttpClient httpClient, IRadarrCloudRequestBuilder requestBuilder, ITmdbConfigService configService, IMovieService movieService, - IPreDBService predbService, IImportExclusionsService exclusionService, IAlternativeTitleService altTitleService, IRadarrAPIClient radarrAPI, Logger logger) + public SkyHookProxy(IHttpClient httpClient, + IRadarrCloudRequestBuilder requestBuilder, + ITmdbConfigService configService, + IMovieService movieService, + IPreDBService predbService, + IImportExclusionsService exclusionService, + IAlternativeTitleService altTitleService, + IRadarrAPIClient radarrAPI, + Logger logger) { _httpClient = httpClient; _movieBuilder = requestBuilder.TMDB; @@ -50,7 +57,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook _logger = logger; } - public HashSet<int> GetChangedMovies (DateTime startTime) + public HashSet<int> GetChangedMovies(DateTime startTime) { var startDate = startTime.ToString("o"); @@ -69,16 +76,17 @@ namespace NzbDrone.Core.MetadataSource.SkyHook return new HashSet<int>(response.Resource.results.Select(c => c.id)); } - public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry = false) + public Movie GetMovieInfo(int tmdbId, Profile profile = null, bool hasPreDBEntry = false) { var langCode = profile != null ? IsoLanguages.Get(profile.Language)?.TwoLetterCode ?? "en" : "en"; var request = _movieBuilder.Create() .SetSegment("route", "movie") - .SetSegment("id", TmdbId.ToString()) + .SetSegment("id", tmdbId.ToString()) .SetSegment("secondaryRoute", "") .AddQueryParam("append_to_response", "alternative_titles,release_dates,videos") .AddQueryParam("language", langCode.ToUpper()) + // .AddQueryParam("country", "US") .Build(); @@ -91,6 +99,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { throw new MovieNotFoundException("Movie not found."); } + if (response.StatusCode != HttpStatusCode.OK) { throw new HttpException(request, response); @@ -104,7 +113,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook // The dude abides, so should us, Lets be nice to TMDb // var allowed = int.Parse(response.Headers.GetValues("X-RateLimit-Limit").First()); // get allowed // var reset = long.Parse(response.Headers.GetValues("X-RateLimit-Reset").First()); // get time when it resets - if (response.Headers.ContainsKey("X-RateLimit-Remaining")) { var remaining = int.Parse(response.Headers.GetValues("X-RateLimit-Remaining").First()); @@ -120,7 +128,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { if (resource.status_code == 34) { - _logger.Warn("Movie with TmdbId {0} could not be found. This is probably the case when the movie was deleted from TMDB.", TmdbId); + _logger.Warn("Movie with TmdbId {0} could not be found. This is probably the case when the movie was deleted from TMDB.", tmdbId); return null; } @@ -136,7 +144,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook var iso = IsoLanguages.Find(resource.original_language); if (iso != null) { - altTitles.Add(new AlternativeTitle(resource.original_title, SourceType.TMDB, TmdbId, iso.Language)); + altTitles.Add(new AlternativeTitle(resource.original_title, SourceType.TMDB, tmdbId, iso.Language)); } } @@ -144,15 +152,15 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { if (alternativeTitle.iso_3166_1.ToLower() == langCode) { - altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, TmdbId, IsoLanguages.Find(alternativeTitle.iso_3166_1.ToLower())?.Language ?? Language.English)); + altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, tmdbId, IsoLanguages.Find(alternativeTitle.iso_3166_1.ToLower())?.Language ?? Language.English)); } else if (alternativeTitle.iso_3166_1.ToLower() == "us") { - altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, TmdbId, Language.English)); + altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, tmdbId, Language.English)); } } - movie.TmdbId = TmdbId; + movie.TmdbId = tmdbId; movie.ImdbId = resource.imdb_id; movie.Title = resource.title; movie.TitleSlug = Parser.Parser.ToUrlSlug(resource.title); @@ -174,12 +182,13 @@ namespace NzbDrone.Core.MetadataSource.SkyHook lowestYear.Add(DateTime.Parse(releaseDate.release_date).Year); } } + movie.Year = lowestYear.Min(); } movie.TitleSlug += "-" + movie.TmdbId.ToString(); - movie.Images.Add(_configService.GetCoverForURL(resource.poster_path, MediaCoverTypes.Poster));//TODO: Update to load image specs from tmdb page! + movie.Images.Add(_configService.GetCoverForURL(resource.poster_path, MediaCoverTypes.Poster)); //TODO: Update to load image specs from tmdb page! movie.Images.Add(_configService.GetCoverForURL(resource.backdrop_path, MediaCoverTypes.Fanart)); movie.Runtime = resource.runtime; @@ -187,10 +196,9 @@ namespace NzbDrone.Core.MetadataSource.SkyHook //{ // movie.AlternativeTitles.Add(title.title); //} - - foreach(ReleaseDates releaseDates in resource.release_dates.results) + foreach (ReleaseDates releaseDates in resource.release_dates.results) { - foreach(ReleaseDate releaseDate in releaseDates.release_dates) + foreach (ReleaseDate releaseDate in releaseDates.release_dates) { if (releaseDate.type == 5 || releaseDate.type == 4) { @@ -215,32 +223,43 @@ namespace NzbDrone.Core.MetadataSource.SkyHook movie.Ratings.Votes = resource.vote_count; movie.Ratings.Value = (decimal)resource.vote_average; - foreach(Genre genre in resource.genres) + foreach (Genre genre in resource.genres) { movie.Genres.Add(genre.name); } var now = DateTime.Now; + //handle the case when we have both theatrical and physical release dates if (movie.InCinemas.HasValue && movie.PhysicalRelease.HasValue) { if (now < movie.InCinemas) + { movie.Status = MovieStatusType.Announced; + } else if (now >= movie.InCinemas) + { movie.Status = MovieStatusType.InCinemas; + } + if (now >= movie.PhysicalRelease) + { movie.Status = MovieStatusType.Released; + } } + //handle the case when we have theatrical release dates but we dont know the physical release date else if (movie.InCinemas.HasValue && (now >= movie.InCinemas)) { movie.Status = MovieStatusType.InCinemas; } + //handle the case where we only have a physical release date else if (movie.PhysicalRelease.HasValue && (now >= movie.PhysicalRelease)) { movie.Status = MovieStatusType.Released; } + //otherwise the title has only been announced else { @@ -248,7 +267,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook } //since TMDB lacks alot of information lets assume that stuff is released if its been in cinemas for longer than 3 months. - if (!movie.PhysicalRelease.HasValue && (movie.Status == MovieStatusType.InCinemas) && (((DateTime.Now).Subtract(movie.InCinemas.Value)).TotalSeconds > 60*60*24*30*3)) + if (!movie.PhysicalRelease.HasValue && (movie.Status == MovieStatusType.InCinemas) && (DateTime.Now.Subtract(movie.InCinemas.Value).TotalSeconds > 60 * 60 * 24 * 30 * 3)) { movie.Status = MovieStatusType.Released; } @@ -303,8 +322,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook .Build(); request.AllowAutoRedirect = true; - // request.SuppressHttpError = true; + // request.SuppressHttpError = true; var response = _httpClient.Get<FindRoot>(request); if (response.HasHttpError) @@ -376,13 +395,15 @@ namespace NzbDrone.Core.MetadataSource.SkyHook private string StripTrailingTheFromTitle(string title) { - if(title.EndsWith(",the")) + if (title.EndsWith(",the")) { title = title.Substring(0, title.Length - 4); - } else if(title.EndsWith(", the")) + } + else if (title.EndsWith(", the")) { title = title.Substring(0, title.Length - 5); } + return title; } @@ -417,7 +438,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { return new List<Movie>(); } - } } @@ -450,7 +470,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook int tmdbid = -1; - if (slug.IsNullOrWhiteSpace() || slug.Any(char.IsWhiteSpace) || !(int.TryParse(slug, out tmdbid))) + if (slug.IsNullOrWhiteSpace() || slug.Any(char.IsWhiteSpace) || !int.TryParse(slug, out tmdbid)) { return new List<Movie>(); } @@ -530,29 +550,38 @@ namespace NzbDrone.Core.MetadataSource.SkyHook _logger.Debug("Not a valid date time."); } - - var now = DateTime.Now; + //handle the case when we have both theatrical and physical release dates if (imdbMovie.InCinemas.HasValue && imdbMovie.PhysicalRelease.HasValue) { if (now < imdbMovie.InCinemas) + { imdbMovie.Status = MovieStatusType.Announced; + } else if (now >= imdbMovie.InCinemas) + { imdbMovie.Status = MovieStatusType.InCinemas; + } + if (now >= imdbMovie.PhysicalRelease) + { imdbMovie.Status = MovieStatusType.Released; + } } + //handle the case when we have theatrical release dates but we dont know the physical release date else if (imdbMovie.InCinemas.HasValue && (now >= imdbMovie.InCinemas)) { imdbMovie.Status = MovieStatusType.InCinemas; } + //handle the case where we only have a physical release date else if (imdbMovie.PhysicalRelease.HasValue && (now >= imdbMovie.PhysicalRelease)) { imdbMovie.Status = MovieStatusType.Released; } + //otherwise the title has only been announced else { @@ -560,7 +589,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook } //since TMDB lacks alot of information lets assume that stuff is released if its been in cinemas for longer than 3 months. - if (!imdbMovie.PhysicalRelease.HasValue && (imdbMovie.Status == MovieStatusType.InCinemas) && (((DateTime.Now).Subtract(imdbMovie.InCinemas.Value)).TotalSeconds > 60 * 60 * 24 * 30 * 3)) + if (!imdbMovie.PhysicalRelease.HasValue && (imdbMovie.Status == MovieStatusType.InCinemas) && (DateTime.Now.Subtract(imdbMovie.InCinemas.Value).TotalSeconds > 60 * 60 * 24 * 30 * 3)) { imdbMovie.Status = MovieStatusType.Released; } @@ -569,7 +598,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook imdbMovie.Images = new List<MediaCover.MediaCover>(); imdbMovie.Overview = result.overview; - imdbMovie.Ratings = new Ratings { Value = (decimal)result.vote_average, Votes = result.vote_count}; + imdbMovie.Ratings = new Ratings { Value = (decimal)result.vote_average, Votes = result.vote_count }; try { @@ -587,7 +616,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { imdbMovie.YouTubeTrailerId = result.trailer_key; } - } return imdbMovie; @@ -661,7 +689,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { try { - Movie newMovie = movie; + Movie newMovie = movie; if (movie.TmdbId > 0) { newMovie = GetMovieInfo(movie.TmdbId); @@ -677,6 +705,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { yearStr = $" {movie.Year}"; } + newMovie = SearchForNewMovie(movie.Title + yearStr).FirstOrDefault(); } @@ -699,7 +728,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook catch (Exception ex) { _logger.Warn(ex, "Couldn't map movie {0} to a movie on The Movie DB. It will not be added :(", movie.Title); - return null; + return null; } } } diff --git a/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs b/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs index be72c81fd..4cead20ed 100644 --- a/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs +++ b/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs @@ -1,8 +1,8 @@ using System.Linq; -using NzbDrone.Core.MediaCover; using NzbDrone.Common.Cache; -using NzbDrone.Common.Http; using NzbDrone.Common.Cloud; +using NzbDrone.Common.Http; +using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource.SkyHook.Resource; namespace NzbDrone.Core.MetadataSource @@ -12,7 +12,7 @@ namespace NzbDrone.Core.MetadataSource MediaCover.MediaCover GetCoverForURL(string url, MediaCover.MediaCoverTypes type); } - class TmdbConfigService : ITmdbConfigService + internal class TmdbConfigService : ITmdbConfigService { private readonly ICached<ConfigResource> _configurationCache; private readonly IHttpClient _httpClient; diff --git a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs index 6930bddf7..07c7db292 100644 --- a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs +++ b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs @@ -1,7 +1,7 @@ using Marr.Data; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Movies.AlternativeTitles { @@ -19,7 +19,6 @@ namespace NzbDrone.Core.Movies.AlternativeTitles public AlternativeTitle() { - } public AlternativeTitle(string title, SourceType sourceType = SourceType.TMDB, int sourceId = 0, Language language = null) @@ -51,7 +50,7 @@ namespace NzbDrone.Core.Movies.AlternativeTitles return false; } - return item.CleanTitle == this.CleanTitle; + return item.CleanTitle == CleanTitle; } public override int GetHashCode() @@ -59,7 +58,7 @@ namespace NzbDrone.Core.Movies.AlternativeTitles return CleanTitle.GetHashCode(); } - public override String ToString() + public override string ToString() { return Title; } diff --git a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs index 1b4fc197f..8df5706d8 100644 --- a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs +++ b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs @@ -1,9 +1,9 @@ -using NLog; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Messaging.Events; using System.Collections.Generic; using System.Linq; +using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.Events; namespace NzbDrone.Core.Movies.AlternativeTitles @@ -25,7 +25,6 @@ namespace NzbDrone.Core.Movies.AlternativeTitles private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - public AlternativeTitleService(IAlternativeTitleRepository titleRepo, IEventAggregator eventAggregator, IConfigService configService, @@ -73,10 +72,13 @@ namespace NzbDrone.Core.Movies.AlternativeTitles public List<AlternativeTitle> UpdateTitles(List<AlternativeTitle> titles, Movie movie) { int movieId = movie.Id; + // First update the movie ids so we can correlate them later. titles.ForEach(t => t.MovieId = movieId); + // Then make sure none of them are the same as the main title. titles = titles.Where(t => t.CleanTitle != movie.CleanTitle).ToList(); + // Then make sure they are all distinct titles titles = titles.DistinctBy(t => t.CleanTitle).ToList(); @@ -98,7 +100,6 @@ namespace NzbDrone.Core.Movies.AlternativeTitles { var title = GetAllTitlesForMovie(message.Movie.Id); _titleRepo.DeleteMany(title); - } } } diff --git a/src/NzbDrone.Core/Movies/Movie.cs b/src/NzbDrone.Core/Movies/Movie.cs index 2ecf68b7d..60eecceb1 100644 --- a/src/NzbDrone.Core/Movies/Movie.cs +++ b/src/NzbDrone.Core/Movies/Movie.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using Marr.Data; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Profiles; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Movies.AlternativeTitles; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.Movies { @@ -19,6 +19,7 @@ namespace NzbDrone.Core.Movies Tags = new HashSet<int>(); AlternativeTitles = new List<AlternativeTitle>(); } + public int TmdbId { get; set; } public string ImdbId { get; set; } public string Title { get; set; } @@ -45,18 +46,19 @@ namespace NzbDrone.Core.Movies public DateTime Added { get; set; } public DateTime? InCinemas { get; set; } public DateTime? PhysicalRelease { get; set; } - public String PhysicalReleaseNote { get; set; } + public string PhysicalReleaseNote { get; set; } public LazyLoaded<Profile> Profile { get; set; } public HashSet<int> Tags { get; set; } public AddMovieOptions AddOptions { get; set; } public MovieFile MovieFile { get; set; } public bool HasPreDBEntry { get; set; } public int MovieFileId { get; set; } + //Get Loaded via a Join Query public List<AlternativeTitle> AlternativeTitles { get; set; } public int? SecondaryYear { get; set; } public int SecondaryYearSourceId { get; set; } - public string YouTubeTrailerId{ get; set; } + public string YouTubeTrailerId { get; set; } public string Studio { get; set; } public bool IsRecentMovie @@ -85,6 +87,7 @@ namespace NzbDrone.Core.Movies { return ""; } + //Well what about Path = Null? //return new DirectoryInfo(Path).Name; return Path; @@ -96,24 +99,29 @@ namespace NzbDrone.Core.Movies //return (Status >= MinimumAvailability || (MinimumAvailability == MovieStatusType.PreDB && Status >= MovieStatusType.Released)); //This more complex sequence handles the delay - DateTime MinimumAvailabilityDate; + DateTime minimumAvailabilityDate; switch (MinimumAvailability) { case MovieStatusType.TBA: case MovieStatusType.Announced: - MinimumAvailabilityDate = DateTime.MinValue; + minimumAvailabilityDate = DateTime.MinValue; break; case MovieStatusType.InCinemas: if (InCinemas.HasValue) - MinimumAvailabilityDate = InCinemas.Value; + { + minimumAvailabilityDate = InCinemas.Value; + } else - MinimumAvailabilityDate = DateTime.MaxValue; + { + minimumAvailabilityDate = DateTime.MaxValue; + } + break; case MovieStatusType.Released: case MovieStatusType.PreDB: default: - MinimumAvailabilityDate = PhysicalRelease.HasValue ? PhysicalRelease.Value : (InCinemas.HasValue ? InCinemas.Value.AddDays(90) : DateTime.MaxValue); + minimumAvailabilityDate = PhysicalRelease.HasValue ? PhysicalRelease.Value : (InCinemas.HasValue ? InCinemas.Value.AddDays(90) : DateTime.MaxValue); break; } @@ -122,13 +130,12 @@ namespace NzbDrone.Core.Movies return true; } - if (MinimumAvailabilityDate == DateTime.MinValue || MinimumAvailabilityDate == DateTime.MaxValue) + if (minimumAvailabilityDate == DateTime.MinValue || minimumAvailabilityDate == DateTime.MaxValue) { - return DateTime.Now >= MinimumAvailabilityDate; + return DateTime.Now >= minimumAvailabilityDate; } - - return DateTime.Now >= MinimumAvailabilityDate.AddDays((double)delay); + return DateTime.Now >= minimumAvailabilityDate.AddDays((double)delay); } public DateTime PhysicalReleaseDate() diff --git a/src/NzbDrone.Core/Movies/MovieRepository.cs b/src/NzbDrone.Core/Movies/MovieRepository.cs index 619d42b19..b76bca489 100644 --- a/src/NzbDrone.Core/Movies/MovieRepository.cs +++ b/src/NzbDrone.Core/Movies/MovieRepository.cs @@ -1,11 +1,11 @@ using System; -using System.Linq; using System.Collections.Generic; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Datastore.Extensions; +using System.Linq; using Marr.Data.QGen; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser.RomanNumerals; using NzbDrone.Core.Qualities; @@ -78,16 +78,16 @@ namespace NzbDrone.Core.Movies public List<Movie> MoviesBetweenDates(DateTime start, DateTime end, bool includeUnmonitored) { - var query = Query.Where(m => - (m.InCinemas >= start && m.InCinemas <= end) || - (m.PhysicalRelease >= start && m.PhysicalRelease <= end)); + var query = Query.Where(m => + (m.InCinemas >= start && m.InCinemas <= end) || + (m.PhysicalRelease >= start && m.PhysicalRelease <= end)); - if (!includeUnmonitored) - { - query.AndWhere(e => e.Monitored == true); - } + if (!includeUnmonitored) + { + query.AndWhere(e => e.Monitored == true); + } - return query.ToList(); + return query.ToList(); } public List<Movie> MoviesWithFiles(int movieId) @@ -216,9 +216,12 @@ namespace NzbDrone.Core.Movies protected override QueryBuilder<TActual> AddJoinQueries<TActual>(QueryBuilder<TActual> baseQuery) { baseQuery = base.AddJoinQueries(baseQuery); - baseQuery = baseQuery.Join<Movie, AlternativeTitle>(JoinType.Left, m => m.AlternativeTitles, + baseQuery = baseQuery.Join<Movie, AlternativeTitle>(JoinType.Left, + m => m.AlternativeTitles, (m, t) => m.Id == t.MovieId); - baseQuery = baseQuery.Join<Movie, MovieFile>(JoinType.Left, m => m.MovieFile, (m, f) => m.Id == f.MovieId); + baseQuery = baseQuery.Join<Movie, MovieFile>(JoinType.Left, + m => m.MovieFile, + (m, f) => m.Id == f.MovieId); return baseQuery; } diff --git a/src/NzbDrone.Core/Movies/MovieScannedHandler.cs b/src/NzbDrone.Core/Movies/MovieScannedHandler.cs index 643268170..8e16efd31 100644 --- a/src/NzbDrone.Core/Movies/MovieScannedHandler.cs +++ b/src/NzbDrone.Core/Movies/MovieScannedHandler.cs @@ -1,22 +1,21 @@ -using NLog; +using System.Collections.Generic; +using NLog; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using System.Collections.Generic; namespace NzbDrone.Core.Movies { public class MovieScannedHandler : IHandle<MovieScannedEvent>, IHandle<MovieScanSkippedEvent> { - private readonly IMovieService _movieService; private readonly IManageCommandQueue _commandQueueManager; private readonly Logger _logger; - public MovieScannedHandler( IMovieService movieService, + public MovieScannedHandler(IMovieService movieService, IManageCommandQueue commandQueueManager, Logger logger) { @@ -34,8 +33,8 @@ namespace NzbDrone.Core.Movies } _logger.Info("[{0}] was recently added, performing post-add actions", movie.Title); - //_episodeMonitoredService.SetEpisodeMonitoredStatus(movie, movie.AddOptions); + //_episodeMonitoredService.SetEpisodeMonitoredStatus(movie, movie.AddOptions); if (movie.AddOptions.SearchForMovie) { _commandQueueManager.Push(new MoviesSearchCommand { MovieIds = new List<int> { movie.Id } }); diff --git a/src/NzbDrone.Core/Movies/MovieService.cs b/src/NzbDrone.Core/Movies/MovieService.cs index 16b17bdb0..4488f39ff 100644 --- a/src/NzbDrone.Core/Movies/MovieService.cs +++ b/src/NzbDrone.Core/Movies/MovieService.cs @@ -5,15 +5,15 @@ using System.Linq; using NLog; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Parser; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Datastore; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.Events; using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Movies { @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Movies bool MoviePathExists(string folder); void RemoveAddOptions(Movie movie); List<Movie> MoviesWithFiles(int movieId); - System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string FilterKey, string FilterValue, string filterType = null); + System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string filterKey, string filterValue, string filterType = null); } public class MovieService : IMovieService, IHandle<MovieFileAddedEvent>, @@ -73,24 +73,23 @@ namespace NzbDrone.Core.Movies _logger = logger; } - - public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string FilterKey, string FilterValue, string FilterType = null) + public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string filterKey, string filterValue, string filterType = null) { //if (FilterKey == "all" && FilterValue == "all") //{ // return v => v.Monitored == true || v.Monitored == false; //} - if (FilterKey == "monitored" && FilterValue == "false") + if (filterKey == "monitored" && filterValue == "false") { return v => v.Monitored == false; } - else if (FilterKey == "monitored" && FilterValue == "true") + else if (filterKey == "monitored" && filterValue == "true") { return v => v.Monitored == true; } - else if (FilterKey == "status") + else if (filterKey == "status") { - switch (FilterValue) + switch (filterValue) { case "released": return v => v.Status == MovieStatusType.Released; @@ -103,31 +102,32 @@ namespace NzbDrone.Core.Movies ((v.MinimumAvailability == MovieStatusType.Released && v.Status >= MovieStatusType.Released) || (v.MinimumAvailability == MovieStatusType.InCinemas && v.Status >= MovieStatusType.InCinemas) || (v.MinimumAvailability == MovieStatusType.Announced && v.Status >= MovieStatusType.Announced) || - (v.MinimumAvailability == MovieStatusType.PreDB && v.Status >= MovieStatusType.Released || v.HasPreDBEntry == true)); + ((v.MinimumAvailability == MovieStatusType.PreDB && v.Status >= MovieStatusType.Released) || v.HasPreDBEntry == true)); } } - else if (FilterKey == "downloaded") + else if (filterKey == "downloaded") { return v => v.MovieFileId == 0; } - else if (FilterKey == "title") + else if (filterKey == "title") { - if (FilterValue == string.Empty || FilterValue == null) + if (filterValue == string.Empty || filterValue == null) { return v => true; } else { - if (FilterType == "contains") + if (filterType == "contains") { - return v => v.CleanTitle.Contains(FilterValue); + return v => v.CleanTitle.Contains(filterValue); } else { - return v => v.CleanTitle == FilterValue; + return v => v.CleanTitle == filterValue; } } } + return v => true; } @@ -155,6 +155,7 @@ namespace NzbDrone.Core.Movies { defaultState = MoviePathState.Dynamic; } + if (string.IsNullOrWhiteSpace(newMovie.Path)) { var folderName = _fileNameBuilder.GetMovieFolder(newMovie); @@ -184,11 +185,12 @@ namespace NzbDrone.Core.Movies newMovies.ForEach(m => { - MoviePathState defaultState = MoviePathState.Static; + MoviePathState defaultState = MoviePathState.Static; if (!_configService.PathsDefaultStatic) { defaultState = MoviePathState.Dynamic; } + if (string.IsNullOrWhiteSpace(m.Path)) { var folderName = _fileNameBuilder.GetMovieFolder(m); @@ -246,6 +248,7 @@ namespace NzbDrone.Core.Movies // no movie matched return list; } + // build ordered list of movie by position in the search string var query = list.Select(movie => new @@ -254,7 +257,7 @@ namespace NzbDrone.Core.Movies length = movie.CleanTitle.Length, movie = movie }) - .Where(s => (s.position>=0)) + .Where(s => (s.position >= 0)) .ToList() .OrderBy(s => s.position) .ThenByDescending(s => s.length) @@ -267,6 +270,7 @@ namespace NzbDrone.Core.Movies public Movie FindByTitleInexact(string title) { var query = FindByTitleInexactAll(title); + // get the leftmost movie that is the longest // movie are usually the first thing in release title, so we select the leftmost and longest match var match = query.First(); @@ -276,6 +280,7 @@ namespace NzbDrone.Core.Movies { _logger.Debug("Multiple movie match candidate: {0} cleantitle: {1}", entry.Title, entry.CleanTitle); } + return match; } @@ -299,8 +304,9 @@ namespace NzbDrone.Core.Movies var movie = _movieRepository.Get(movieId); if (addExclusion) { - _exclusionService.AddExclusion(new ImportExclusion {TmdbId = movie.TmdbId, MovieTitle = movie.Title, MovieYear = movie.Year } ); + _exclusionService.AddExclusion(new ImportExclusion { TmdbId = movie.TmdbId, MovieTitle = movie.Title, MovieYear = movie.Year }); } + _movieRepository.Delete(movieId); _eventAggregator.PublishEvent(new MovieDeletedEvent(movie, deleteFiles)); _logger.Info("Deleted movie {}", movie); @@ -339,7 +345,6 @@ namespace NzbDrone.Core.Movies s.Path = Path.Combine(s.RootFolderPath, folderName); _logger.Trace("Changing path for {0} to {1}", s.Title, s.Path); } - else { _logger.Trace("Not changing path for: {0}", s.Title); @@ -367,6 +372,7 @@ namespace NzbDrone.Core.Movies var movie = message.MovieFile.Movie.Value; movie.MovieFileId = message.MovieFile.Id; _movieRepository.Update(movie); + //_movieRepository.SetFileId(message.MovieFile.Id, message.MovieFile.Movie.Value.Id); _logger.Info("Linking [{0}] > [{1}]", message.MovieFile.RelativePath, message.MovieFile.Movie.Value); } @@ -379,7 +385,6 @@ namespace NzbDrone.Core.Movies public void Handle(MovieFileDeletedEvent message) { - var movie = _movieRepository.GetMoviesByFileId(message.MovieFile.Id).First(); movie.MovieFileId = 0; _logger.Debug("Detaching movie {0} from file.", movie.Id); diff --git a/src/NzbDrone.Core/Movies/MovieStatusType.cs b/src/NzbDrone.Core/Movies/MovieStatusType.cs index f45ecb5f0..2e856e0b5 100644 --- a/src/NzbDrone.Core/Movies/MovieStatusType.cs +++ b/src/NzbDrone.Core/Movies/MovieStatusType.cs @@ -6,6 +6,6 @@ Announced = 1, //Movie is announced but Cinema date is in the future or unknown InCinemas = 2, //Been in Cinemas for less than 3 months (since TMDB lacks complete information) Released = 3, //Physical or Web Release or been in cinemas for > 3 months (since TMDB lacks complete information) - PreDB = 4 //this is only used for MinimumAvailability. Movie items should never be in this state. + PreDB = 4 //this is only used for MinimumAvailability. Movie items should never be in this state. } } diff --git a/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs b/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs index c5ca9edaf..7b4302708 100644 --- a/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs +++ b/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs @@ -4,7 +4,7 @@ namespace NzbDrone.Core.Movies { public static class MovieTitleNormalizer { - private readonly static Dictionary<int, string> PreComputedTitles = new Dictionary<int, string> + private static readonly Dictionary<int, string> PreComputedTitles = new Dictionary<int, string> { { 999999999, "a to z" }, }; diff --git a/src/NzbDrone.Core/Movies/RefreshMovieService.cs b/src/NzbDrone.Core/Movies/RefreshMovieService.cs index 9498c60cc..19807fcc1 100644 --- a/src/NzbDrone.Core/Movies/RefreshMovieService.cs +++ b/src/NzbDrone.Core/Movies/RefreshMovieService.cs @@ -5,6 +5,7 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; + //using NzbDrone.Core.DataAugmentation.DailyMovie; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; @@ -86,6 +87,7 @@ namespace NzbDrone.Core.Movies movie.Certification = movieInfo.Certification; movie.InCinemas = movieInfo.InCinemas; movie.Website = movieInfo.Website; + //movie.AlternativeTitles = movieInfo.AlternativeTitles; movie.Year = movieInfo.Year; movie.PhysicalRelease = movieInfo.PhysicalRelease; @@ -134,12 +136,12 @@ namespace NzbDrone.Core.Movies _logger.Info(ex, "Unable to communicate with Mappings Server."); } - _movieService.UpdateMovie(movie); try { var newTitles = movieInfo.AlternativeTitles.Except(movie.AlternativeTitles); + //_titleService.AddAltTitles(newTitles.ToList(), movie); } catch (Exception e) @@ -245,7 +247,6 @@ namespace NzbDrone.Core.Movies RescanMovie(movie, false, trigger); } - else { _logger.Info("Skipping refresh of movie: {0}", movie.Title); diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs index bea66105d..45ec3eed6 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs @@ -40,6 +40,7 @@ namespace NzbDrone.Core.NetImport.CouchPotato public bool? via_tmdb { get; set; } public string[] actors { get; set; } public string[] writers { get; set; } + //public int? runtime { get; set; } public string type { get; set; } public string released { get; set; } diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs index 5da56d71e..130eb1144 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs @@ -13,7 +13,8 @@ namespace NzbDrone.Core.NetImport.CouchPotato public CouchPotatoImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override INetImportRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs index 2a5ff2d64..bdbd399e6 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.CouchPotato { @@ -92,6 +92,5 @@ namespace NzbDrone.Core.NetImport.CouchPotato return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs index 2d3310c4d..10146a821 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.CouchPotato { diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs index c3cdd65f0..aa04cc178 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Validation; namespace NzbDrone.Core.NetImport.CouchPotato { - public class CouchPotatoSettingsValidator : AbstractValidator<CouchPotatoSettings> { public CouchPotatoSettingsValidator() @@ -48,5 +47,4 @@ namespace NzbDrone.Core.NetImport.CouchPotato return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs b/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs index 1447c55e1..d236c8daf 100644 --- a/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs +++ b/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs @@ -7,10 +7,10 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport.Exceptions; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { @@ -102,10 +102,10 @@ namespace NzbDrone.Core.NetImport { anyFailure = true; feedEx.Data.Add("FeedUrl", url); - _logger.Error(feedEx, "An error occurred while processing list feed {0}", url); + _logger.Error(feedEx, "An error occurred while processing list feed {0}", url); } - return new NetImportFetchResult {Movies = movies, AnyFailure = anyFailure}; + return new NetImportFetchResult { Movies = movies, AnyFailure = anyFailure }; } protected virtual IList<Movie> FetchPage(NetImportRequest request, IParseNetImportResponse parser) @@ -114,11 +114,11 @@ namespace NzbDrone.Core.NetImport return parser.ParseResponse(response).ToList().Select(m => { - m.RootFolderPath = ((NetImportDefinition) Definition).RootFolderPath; - m.ProfileId = ((NetImportDefinition) Definition).ProfileId; - m.Monitored = ((NetImportDefinition) Definition).ShouldMonitor; - m.MinimumAvailability = ((NetImportDefinition) Definition).MinimumAvailability; - m.Tags = ((NetImportDefinition) Definition).Tags; + m.RootFolderPath = ((NetImportDefinition)Definition).RootFolderPath; + m.ProfileId = ((NetImportDefinition)Definition).ProfileId; + m.Monitored = ((NetImportDefinition)Definition).ShouldMonitor; + m.MinimumAvailability = ((NetImportDefinition)Definition).MinimumAvailability; + m.Tags = ((NetImportDefinition)Definition).Tags; return m; }).ToList(); } @@ -171,5 +171,4 @@ namespace NzbDrone.Core.NetImport return null; } } - } diff --git a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs index 7291971b4..afbd6a0c8 100644 --- a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs +++ b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.NetImport.ImportExclusions public string MovieTitle { get; set; } public int MovieYear { get; set; } - new public string ToString() + public new string ToString() { return string.Format("Excluded Movie: [{0}][{1} {2}]", TmdbId, MovieTitle, MovieYear); } diff --git a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs index 46e44fed4..26452f599 100644 --- a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs +++ b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.NetImport.ImportExclusions { @@ -22,7 +22,6 @@ namespace NzbDrone.Core.NetImport.ImportExclusions private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - public ImportExclusionsService(IImportExclusionsRepository exclusionRepository, IEventAggregator eventAggregator, IConfigService configService, @@ -40,6 +39,7 @@ namespace NzbDrone.Core.NetImport.ImportExclusions { return _exclusionRepository.GetByTmdbid(exclusion.TmdbId); } + return _exclusionRepository.Insert(exclusion); } diff --git a/src/NzbDrone.Core/NetImport/NetImportBase.cs b/src/NzbDrone.Core/NetImport/NetImportBase.cs index 2345d46aa..a12fcab84 100644 --- a/src/NzbDrone.Core/NetImport/NetImportBase.cs +++ b/src/NzbDrone.Core/NetImport/NetImportBase.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using FluentValidation.Results; using NLog; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { @@ -47,7 +47,7 @@ namespace NzbDrone.Core.NetImport yield return new NetImportDefinition { - Name = this.Name, + Name = Name, Enabled = config.Validate().IsValid && Enabled, EnableAuto = true, ProfileId = 1, @@ -60,7 +60,10 @@ namespace NzbDrone.Core.NetImport public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary<string, string> query) { return null; } + public virtual object RequestAction(string action, IDictionary<string, string> query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; @@ -87,6 +90,5 @@ namespace NzbDrone.Core.NetImport { return Definition.Name; } - } } diff --git a/src/NzbDrone.Core/NetImport/NetImportDefinition.cs b/src/NzbDrone.Core/NetImport/NetImportDefinition.cs index d08b71b7f..380472246 100644 --- a/src/NzbDrone.Core/NetImport/NetImportDefinition.cs +++ b/src/NzbDrone.Core/NetImport/NetImportDefinition.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using Marr.Data; +using NzbDrone.Core.Movies; using NzbDrone.Core.Profiles; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { diff --git a/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs b/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs index 589c4844a..9b2f5ca87 100644 --- a/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs +++ b/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs @@ -27,7 +27,10 @@ namespace NzbDrone.Core.NetImport public void Add(IEnumerable<NetImportRequest> request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new NetImportPageableRequest(request)); } @@ -40,7 +43,10 @@ namespace NzbDrone.Core.NetImport public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List<NetImportPageableRequest>()); } diff --git a/src/NzbDrone.Core/NetImport/NetImportRepository.cs b/src/NzbDrone.Core/NetImport/NetImportRepository.cs index 83ebded94..77ccfa092 100644 --- a/src/NzbDrone.Core/NetImport/NetImportRepository.cs +++ b/src/NzbDrone.Core/NetImport/NetImportRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.NetImport { public interface INetImportRepository : IProviderRepository<NetImportDefinition> diff --git a/src/NzbDrone.Core/NetImport/NetImportSearchService.cs b/src/NzbDrone.Core/NetImport/NetImportSearchService.cs index 0fc8d11ad..6862fc8a9 100644 --- a/src/NzbDrone.Core/NetImport/NetImportSearchService.cs +++ b/src/NzbDrone.Core/NetImport/NetImportSearchService.cs @@ -1,15 +1,15 @@ using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Configuration; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Download; using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.RootFolders; namespace NzbDrone.Core.NetImport { @@ -31,10 +31,13 @@ namespace NzbDrone.Core.NetImport private readonly IProcessDownloadDecisions _processDownloadDecisions; private readonly IImportExclusionsService _exclusionService; - - public NetImportSearchService(INetImportFactory netImportFactory, IMovieService movieService, - ISearchForNewMovie movieSearch, IRootFolderService rootFolder, ISearchForNzb nzbSearchService, - IProcessDownloadDecisions processDownloadDecisions, IConfigService configService, + public NetImportSearchService(INetImportFactory netImportFactory, + IMovieService movieService, + ISearchForNewMovie movieSearch, + IRootFolderService rootFolder, + ISearchForNzb nzbSearchService, + IProcessDownloadDecisions processDownloadDecisions, + IConfigService configService, IImportExclusionsService exclusionService, Logger logger) { @@ -49,7 +52,6 @@ namespace NzbDrone.Core.NetImport _configService = configService; } - public NetImportFetchResult Fetch(int listId, bool onlyEnableAuto = false) { return MovieListSearch(listId, onlyEnableAuto); @@ -105,12 +107,10 @@ namespace NzbDrone.Core.NetImport }; } - - public void Execute(NetImportSyncCommand message) { //if there are no lists that are enabled for automatic import then dont do anything - if((_netImportFactory.GetAvailableProviders()).Where(a => ((NetImportDefinition)a.Definition).EnableAuto).Empty()) + if (_netImportFactory.GetAvailableProviders().Where(a => ((NetImportDefinition)a.Definition).EnableAuto).Empty()) { _logger.Info("No lists are enabled for auto-import."); return; @@ -182,8 +182,8 @@ namespace NzbDrone.Core.NetImport foundMatch = true; break; } - } + if (!foundMatch) { switch (_configService.ListSyncLevel) @@ -203,6 +203,7 @@ namespace NzbDrone.Core.NetImport case "removeAndDelete": _logger.Info("{0} was in your library, but not found in your lists --> Removing from library and deleting files", movie); _movieService.DeleteMovie(movie.Id, true); + //TODO: for some reason the files are not deleted in this case... any idea why? break; default: diff --git a/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs b/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs index 73a379baf..02584e348 100644 --- a/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs +++ b/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs @@ -4,9 +4,8 @@ namespace NzbDrone.Core.NetImport { public class NetImportSyncCommand : Command { - public override bool SendUpdatesToClient => true; - public int listId = 0; + public int ListId = 0; } } diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs index b5e16c57c..06dcd6f3d 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs @@ -15,7 +15,8 @@ namespace NzbDrone.Core.NetImport.RSSImport public RSSImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override IEnumerable<ProviderDefinition> DefaultDefinitions { @@ -25,6 +26,7 @@ namespace NzbDrone.Core.NetImport.RSSImport { yield return def; } + yield return new NetImportDefinition { Name = "IMDb List", diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs index 3aa2ba9ea..0e1df0b9c 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs @@ -1,6 +1,4 @@ -using NzbDrone.Core.NetImport.Exceptions; -using NzbDrone.Core.Movies; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -13,6 +11,8 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.Exceptions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.RSSImport { @@ -128,7 +128,6 @@ namespace NzbDrone.Core.NetImport.RSSImport releaseInfo = ProcessItem(item, releaseInfo); //_logger.Trace("Parsed: {0}", releaseInfo.Title); - return PostProcess(item, releaseInfo); } @@ -143,7 +142,7 @@ namespace NzbDrone.Core.NetImport.RSSImport } releaseInfo.Title = title; - var result = Parser.Parser.ParseMovieTitle(title, false);//Depreciated anyways + var result = Parser.Parser.ParseMovieTitle(title, false); //Depreciated anyways if (result != null) { @@ -158,7 +157,6 @@ namespace NzbDrone.Core.NetImport.RSSImport { releaseInfo.ImdbId = GetImdbId(item); } - } catch (Exception) { @@ -197,6 +195,7 @@ namespace NzbDrone.Core.NetImport.RSSImport { return ""; } + return Parser.Parser.ParseImdbId(url); } diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs index 04adc0163..9f59da5d4 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Core.NetImport.RSSImport //{ // return new NetImportPageableRequestChain(); //} - private IEnumerable<NetImportRequest> GetMovies(string searchParameters) { var request = new NetImportRequest($"{Settings.Link.Trim()}", HttpAccept.Rss); diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs index f5b734792..e0ec2bc07 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.MetadataSource; - namespace NzbDrone.Core.NetImport.Radarr { @@ -17,7 +16,10 @@ namespace NzbDrone.Core.NetImport.Radarr private readonly ISearchForNewMovie _skyhookProxy; - public RadarrLists(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, ISearchForNewMovie skyhookProxy, + public RadarrLists(IHttpClient httpClient, + IConfigService configService, + IParsingService parsingService, + ISearchForNewMovie skyhookProxy, Logger logger) : base(httpClient, configService, parsingService, logger) { diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs index 8a4b99570..fad9f082e 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs @@ -1,22 +1,22 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Common.Http; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Common.Http; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; namespace NzbDrone.Core.NetImport.Radarr { public class RadarrParser : IParseNetImportResponse { private readonly RadarrSettings _settings; - private NetImportResponse _importResponse; private readonly ISearchForNewMovie _skyhookProxy; + private NetImportResponse _importResponse; public RadarrParser(RadarrSettings settings, ISearchForNewMovie skyhookProxy) { - _skyhookProxy = skyhookProxy;//TinyIoC.TinyIoCContainer.Current.Resolve<ISearchForNewMovie>(); + _skyhookProxy = skyhookProxy; _settings = settings; } @@ -40,8 +40,6 @@ namespace NzbDrone.Core.NetImport.Radarr } return jsonResponse.SelectList(_skyhookProxy.MapMovie); - - } protected virtual bool PreProcess(NetImportResponse indexerResponse) @@ -60,7 +58,6 @@ namespace NzbDrone.Core.NetImport.Radarr //No error! } - if (indexerResponse.HttpResponse.StatusCode != System.Net.HttpStatusCode.OK) { throw new HttpException(indexerResponse.HttpRequest, indexerResponse.HttpResponse); @@ -68,6 +65,5 @@ namespace NzbDrone.Core.NetImport.Radarr return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs index 11ce376ee..60dbab9ad 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs @@ -1,8 +1,8 @@ using System; -using NzbDrone.Common.Http; using System.Collections.Generic; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.Radarr { diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs index 9ce34e3f2..cee94ad98 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Validation; namespace NzbDrone.Core.NetImport.Radarr { - public class RadarrSettingsValidator : AbstractValidator<RadarrSettings> { public RadarrSettingsValidator() @@ -35,5 +34,4 @@ namespace NzbDrone.Core.NetImport.Radarr return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs index 643d4dd4a..8ec74b9ca 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs @@ -13,7 +13,8 @@ namespace NzbDrone.Core.NetImport.StevenLu public StevenLuImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override INetImportRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs index eb9a8d8ca..47d6e9862 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.StevenLu { @@ -62,6 +62,5 @@ namespace NzbDrone.Core.NetImport.StevenLu return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs index d117279f5..4d44e3e69 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.StevenLu { diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs index 89fcdd488..cbc8c2c67 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Validation; namespace NzbDrone.Core.NetImport.StevenLu { - public class StevenLuSettingsValidator : AbstractValidator<StevenLuSettings> { public StevenLuSettingsValidator() @@ -30,7 +29,5 @@ namespace NzbDrone.Core.NetImport.StevenLu { return new NzbDroneValidationResult(Validator.Validate(this)); } - } - } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs index 53af40df1..ec32da5f3 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs @@ -4,7 +4,6 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; - namespace NzbDrone.Core.NetImport.TMDb { public class TMDbImport : HttpNetImportBase<TMDbSettings> @@ -15,7 +14,10 @@ namespace NzbDrone.Core.NetImport.TMDb private readonly ISearchForNewMovie _skyhookProxy; - public TMDbImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, ISearchForNewMovie skyhookProxy, + public TMDbImport(IHttpClient httpClient, + IConfigService configService, + IParsingService parsingService, + ISearchForNewMovie skyhookProxy, Logger logger) : base(httpClient, configService, parsingService, logger) { diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs index b0832b86b..0f904df73 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs @@ -1,18 +1,18 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.TMDb { public class TMDbParser : IParseNetImportResponse { private readonly TMDbSettings _settings; - private NetImportResponse _importResponse; private readonly ISearchForNewMovie _skyhookProxy; + private NetImportResponse _importResponse; public TMDbParser(TMDbSettings settings, ISearchForNewMovie skyhookProxy) { @@ -71,7 +71,6 @@ namespace NzbDrone.Core.NetImport.TMDb } } - return movies; } @@ -90,6 +89,5 @@ namespace NzbDrone.Core.NetImport.TMDb return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs index a7433b9b3..bba6cb3b0 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs @@ -1,8 +1,8 @@ using System; -using NzbDrone.Common.Http; using System.Collections.Generic; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.MetadataSource.SkyHook.Resource; @@ -72,6 +72,7 @@ namespace NzbDrone.Core.NetImport.TMDb requestBuilder.Resource(tmdbParams); var request = requestBuilder + // .AddQueryParam("api_key", "1a7373301961d03f97f853a876dd1212") .Accept(HttpAccept.Json) .Build(); @@ -112,7 +113,6 @@ namespace NzbDrone.Core.NetImport.TMDb Logger.Info($"Importing TMDb movies from: {baseUrl}"); yield return new NetImportRequest($"{baseUrl}", HttpAccept.Json); } - } } } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs index c1d4dbcb0..e76c46a79 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs @@ -1,13 +1,12 @@ -using FluentValidation; +using System.Text.RegularExpressions; +using FluentValidation; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.NetImport.TMDb { - public class TMDbSettingsValidator : AbstractValidator<TMDbSettings> { public TMDbSettingsValidator() @@ -49,7 +48,6 @@ namespace NzbDrone.Core.NetImport.TMDb .Matches(@"^\d+([,|]\d+)*$", RegexOptions.IgnoreCase) .When(c => c.ExcludeGenreIds.IsNotNullOrWhiteSpace()) .WithMessage("Genre Ids must be comma (,) or pipe (|) separated number ids"); - } } @@ -98,5 +96,4 @@ namespace NzbDrone.Core.NetImport.TMDb return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs index f161a2ab8..695e77703 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs @@ -1,10 +1,10 @@ -using NLog; +using System; +using System.Collections.Generic; +using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; using NzbDrone.Core.Validation; -using System; -using System.Collections.Generic; namespace NzbDrone.Core.NetImport.Trakt { @@ -57,7 +57,6 @@ namespace NzbDrone.Core.NetImport.Trakt { _logger.Warn($"Error refreshing trakt access token"); } - } public override INetImportRequestGenerator GetRequestGenerator() @@ -70,7 +69,7 @@ namespace NzbDrone.Core.NetImport.Trakt RefreshToken(); } - return new TraktRequestGenerator() { Settings = Settings, _configService=_configService, HttpClient = _httpClient, }; + return new TraktRequestGenerator() { Settings = Settings, _configService = _configService, HttpClient = _httpClient, }; } public override IParseNetImportResponse GetParser() diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs index 206af1093..72bde7be5 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.Trakt { @@ -27,7 +27,7 @@ namespace NzbDrone.Core.NetImport.Trakt return movies; } - if (_settings.ListType == (int) TraktListType.Popular) + if (_settings.ListType == (int)TraktListType.Popular) { var jsonResponse = JsonConvert.DeserializeObject<List<Movie>>(_importResponse.Content); @@ -38,7 +38,7 @@ namespace NzbDrone.Core.NetImport.Trakt Title = movie.title, ImdbId = movie.ids.imdb, TmdbId = movie.ids.tmdb, - Year = (movie.year ?? 0) + Year = movie.year ?? 0 }); } } @@ -59,13 +59,12 @@ namespace NzbDrone.Core.NetImport.Trakt Title = movie.movie.title, ImdbId = movie.movie.ids.imdb, TmdbId = movie.movie.ids.tmdb, - Year = (movie.movie.year ?? 0) + Year = movie.movie.year ?? 0 }); } } return movies; - } protected virtual bool PreProcess(NetImportResponse indexerResponse) @@ -83,6 +82,5 @@ namespace NzbDrone.Core.NetImport.Trakt return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs index c870390eb..85b1d18fb 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs @@ -1,9 +1,8 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; - namespace NzbDrone.Core.NetImport.Trakt { public class RefreshRequestResponse @@ -24,6 +23,7 @@ namespace NzbDrone.Core.NetImport.Trakt public TraktRequestGenerator() { } + public virtual NetImportPageableRequestChain GetMovies() { var pageableRequests = new NetImportPageableRequestChain(); diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs index b4fa9074d..7f189f09e 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs @@ -1,14 +1,13 @@ -using FluentValidation; +using System; +using System.Text.RegularExpressions; +using FluentValidation; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System; -using System.Text.RegularExpressions; namespace NzbDrone.Core.NetImport.Trakt { - public class TraktSettingsValidator : AbstractValidator<TraktSettings> { public TraktSettingsValidator() @@ -51,6 +50,7 @@ namespace NzbDrone.Core.NetImport.Trakt // Limit not smaller than 1 and not larger than 100 RuleFor(c => c.Limit) .GreaterThan(0) + // .InclusiveBetween(1, 500) .WithMessage("Must be integer greater than 0"); } @@ -121,13 +121,9 @@ namespace NzbDrone.Core.NetImport.Trakt [FieldDefinition(99, Label = "Authenticate with Trakt", Type = FieldType.OAuth)] public string SignIn { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); } } - - - } diff --git a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs index 248a07549..b2fc8ec1c 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Notifications.Boxcar public override void OnDownload(DownloadMessage message) { - _proxy.SendNotification(MOVIE_DOWNLOADED_TITLE , message.Message, Settings); + _proxy.SendNotification(MOVIE_DOWNLOADED_TITLE, message.Message, Settings); } public override void OnHealthIssue(HealthCheck.HealthCheck message) diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs index 139c3b1ab..6108d4aab 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Boxcar { public class BoxcarException : NzbDroneException { - public BoxcarException(string message) : base(message) + public BoxcarException(string message) + : base(message) { } - public BoxcarException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public BoxcarException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs index bf0e848f7..3bf8560d4 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs @@ -2,9 +2,9 @@ using System.Net; using FluentValidation.Results; using NLog; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Boxcar { @@ -16,8 +16,8 @@ namespace NzbDrone.Core.Notifications.Boxcar public class BoxcarProxy : IBoxcarProxy { - private readonly Logger _logger; private const string URL = "https://new.boxcar.io/api/notifications"; + private readonly Logger _logger; public BoxcarProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs b/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs index 4ccad0c37..f72bdb893 100755 --- a/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs +++ b/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs @@ -8,8 +8,8 @@ using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Processes; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.CustomScript @@ -124,6 +124,7 @@ namespace NzbDrone.Core.Notifications.CustomScript ExecuteScript(environmentVariables); } + public override ValidationResult Test() { var failures = new List<ValidationFailure>(); diff --git a/src/NzbDrone.Core/Notifications/Discord/Discord.cs b/src/NzbDrone.Core/Notifications/Discord/Discord.cs index ddacbc63e..cd44b6507 100644 --- a/src/NzbDrone.Core/Notifications/Discord/Discord.cs +++ b/src/NzbDrone.Core/Notifications/Discord/Discord.cs @@ -87,7 +87,6 @@ namespace NzbDrone.Core.Notifications.Discord var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (DiscordException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs index 1bc0d6294..79b2bbfaf 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs @@ -3,13 +3,15 @@ using NzbDrone.Common.Exceptions; namespace NzbDrone.Core.Notifications.Discord { - class DiscordException : NzbDroneException + public class DiscordException : NzbDroneException { - public DiscordException(string message) : base(message) + public DiscordException(string message) + : base(message) { } - public DiscordException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public DiscordException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs index 425364253..37ecf794d 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs @@ -34,7 +34,7 @@ namespace NzbDrone.Core.Notifications.Discord request.Headers.ContentType = "application/json"; request.SetContent(payload.ToJson()); - _httpClient.Execute(request); + _httpClient.Execute(request); } catch (RestException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs index e4ba51571..d98693824 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Core.Notifications.Discord [FieldDefinition(2, Label = "Avatar", HelpText = "Change the avatar that is used for messages from this integration", Type = FieldType.Textbox)] public string Avatar { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Notifications/Email/Email.cs b/src/NzbDrone.Core/Notifications/Email/Email.cs index 68f077727..1dd7623c4 100644 --- a/src/NzbDrone.Core/Notifications/Email/Email.cs +++ b/src/NzbDrone.Core/Notifications/Email/Email.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Notifications.Email public override string Name => "Email"; - public Email(IEmailService emailService) { _emailService = emailService; diff --git a/src/NzbDrone.Core/Notifications/Email/EmailService.cs b/src/NzbDrone.Core/Notifications/Email/EmailService.cs index d0cdbc497..8f8f88a62 100644 --- a/src/NzbDrone.Core/Notifications/Email/EmailService.cs +++ b/src/NzbDrone.Core/Notifications/Email/EmailService.cs @@ -35,13 +35,15 @@ namespace NzbDrone.Core.Notifications.Email NetworkCredential credentials = null; if (!string.IsNullOrWhiteSpace(settings.Username)) + { credentials = new NetworkCredential(settings.Username, settings.Password); + } try { Send(email, settings.Server, settings.Port, settings.Ssl, credentials); } - catch(Exception ex) + catch (Exception ex) { _logger.Error("Error sending email. Subject: {0}", email.Subject); _logger.Debug(ex, ex.Message); diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs index 8782d4dcd..9a5f9c5dc 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs @@ -1,5 +1,4 @@ namespace NzbDrone.Core.Notifications.Gotify - { public enum GotifyPriority { diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs index b14b530d3..a6e711516 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs @@ -1,5 +1,5 @@ -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Gotify { diff --git a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs index 0a4c20b4d..acdc931f9 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Gotify { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/GrabMessage.cs b/src/NzbDrone.Core/Notifications/GrabMessage.cs index ecc25c4f1..0a6d6488f 100644 --- a/src/NzbDrone.Core/Notifications/GrabMessage.cs +++ b/src/NzbDrone.Core/Notifications/GrabMessage.cs @@ -1,6 +1,6 @@ +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/INotification.cs b/src/NzbDrone.Core/Notifications/INotification.cs index 07c5ee588..ce589f618 100644 --- a/src/NzbDrone.Core/Notifications/INotification.cs +++ b/src/NzbDrone.Core/Notifications/INotification.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs index 92b977722..12c55b2c3 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinAuthException : JoinException { - public JoinAuthException(string message) : base(message) + public JoinAuthException(string message) + : base(message) { } - public JoinAuthException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinAuthException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinException.cs b/src/NzbDrone.Core/Notifications/Join/JoinException.cs index e0ad0e1c3..18ef5e2f2 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinException : NzbDroneException { - public JoinException(string message) : base(message) + public JoinException(string message) + : base(message) { } - public JoinException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs index a6463abb4..d79e989ec 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinInvalidDeviceException : JoinException { - public JoinInvalidDeviceException(string message) : base(message) + public JoinInvalidDeviceException(string message) + : base(message) { } - public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs index 2326fd5c6..d0d968ecb 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs @@ -2,9 +2,9 @@ using System; using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Join { @@ -16,8 +16,8 @@ namespace NzbDrone.Core.Notifications.Join public class JoinProxy : IJoinProxy { - private readonly Logger _logger; private const string URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?"; + private readonly Logger _logger; public JoinProxy(Logger logger) { @@ -49,7 +49,7 @@ namespace NzbDrone.Core.Notifications.Join SendNotification(title, body, settings); return null; } - catch(JoinInvalidDeviceException ex) + catch (JoinInvalidDeviceException ex) { _logger.Error(ex, "Unable to send test Join message. Invalid Device IDs supplied."); return new ValidationFailure("DeviceIds", "Device IDs appear invalid."); @@ -59,7 +59,7 @@ namespace NzbDrone.Core.Notifications.Join _logger.Error(ex, "Unable to send test Join message."); return new ValidationFailure("ApiKey", ex.Message); } - catch(RestException ex) + catch (RestException ex) { _logger.Error(ex, "Unable to send test Join message. Server connection failed."); return new ValidationFailure("ApiKey", "Unable to connect to Join API. Please try again later."); @@ -73,7 +73,6 @@ namespace NzbDrone.Core.Notifications.Join private void SendNotification(string title, string message, RestRequest request, JoinSettings settings) { - var client = RestClientFactory.BuildClient(URL); if (settings.DeviceNames.IsNotNullOrWhiteSpace()) @@ -99,7 +98,10 @@ namespace NzbDrone.Core.Notifications.Join var response = client.ExecuteAndValidate(request); var res = Json.Deserialize<JoinResponseModel>(response.Content); - if (res.success) return; + if (res.success) + { + return; + } if (res.userAuthError) { @@ -114,6 +116,7 @@ namespace NzbDrone.Core.Notifications.Join { throw new JoinInvalidDeviceException(res.errorMessage); } + // Oddly enough, rather than give us an "Invalid API key", the Join API seems to assume the key is valid, // but fails when doing a device lookup associated with that key. // In our case we are using "deviceIds" rather than "deviceId" so when the singular form error shows up @@ -122,6 +125,7 @@ namespace NzbDrone.Core.Notifications.Join { throw new JoinAuthException("Authentication failed."); } + throw new JoinException(res.errorMessage); } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs index 797e7230a..db5c8550a 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Core.Notifications.Join public class JoinSettings : IProviderConfig { - public JoinSettings() { Priority = (int)JoinPriority.Normal; diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs index 9b92dfb00..fa6d1102a 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Core.Notifications.Emby public override string Link => "https://emby.media/"; public override string Name => "Emby"; - public override void OnGrab(GrabMessage grabMessage) { if (Settings.Notify) diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs index 5042f9fc8..675d06435 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs @@ -22,11 +22,11 @@ namespace NzbDrone.Core.Notifications.Emby request.Headers.ContentType = "application/json"; request.SetContent(new - { - Name = title, - Description = message, - ImageUrl = "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png" - }.ToJson()); + { + Name = title, + Description = message, + ImageUrl = "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png" + }.ToJson()); ProcessRequest(request, settings); } diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs index f7a42ccd3..62565a9b2 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs @@ -2,8 +2,8 @@ using System; using System.Net; using FluentValidation.Results; using NLog; -using NzbDrone.Core.Rest; using NzbDrone.Core.Movies; +using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Emby { diff --git a/src/NzbDrone.Core/Notifications/NotificationBase.cs b/src/NzbDrone.Core/Notifications/NotificationBase.cs index 7cc132d2b..08841fdf0 100644 --- a/src/NzbDrone.Core/Notifications/NotificationBase.cs +++ b/src/NzbDrone.Core/Notifications/NotificationBase.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; using FluentValidation.Results; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Notifications { - public abstract class NotificationBase<TSettings> : INotification where TSettings : IProviderConfig, new() + public abstract class NotificationBase<TSettings> : INotification + where TSettings : IProviderConfig, new() { protected const string MOVIE_GRABBED_TITLE = "Movie Grabbed"; protected const string MOVIE_DOWNLOADED_TITLE = "Movie Downloaded"; @@ -31,22 +32,18 @@ namespace NzbDrone.Core.Notifications public virtual void OnGrab(GrabMessage grabMessage) { - } public virtual void OnDownload(DownloadMessage message) { - } public virtual void OnMovieRename(Movie movie) { - } public virtual void OnHealthIssue(HealthCheck.HealthCheck healthCheck) { - } public bool SupportsOnGrab => HasConcreteImplementation("OnGrab"); @@ -62,8 +59,10 @@ namespace NzbDrone.Core.Notifications return GetType().Name; } - public virtual object RequestAction(string action, IDictionary<string, string> query) { return null; } - + public virtual object RequestAction(string action, IDictionary<string, string> query) + { + return null; + } private bool HasConcreteImplementation(string methodName) { @@ -76,6 +75,5 @@ namespace NzbDrone.Core.Notifications return !method.DeclaringType.IsAbstract; } - } } diff --git a/src/NzbDrone.Core/Notifications/NotificationRepository.cs b/src/NzbDrone.Core/Notifications/NotificationRepository.cs index 6a67eb88b..ccdaaf541 100644 --- a/src/NzbDrone.Core/Notifications/NotificationRepository.cs +++ b/src/NzbDrone.Core/Notifications/NotificationRepository.cs @@ -2,12 +2,10 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Notifications { public interface INotificationRepository : IProviderRepository<NotificationDefinition> { - } public class NotificationRepository : ProviderRepository<NotificationDefinition>, INotificationRepository diff --git a/src/NzbDrone.Core/Notifications/NotificationService.cs b/src/NzbDrone.Core/Notifications/NotificationService.cs index 99cedefc2..302dff045 100644 --- a/src/NzbDrone.Core/Notifications/NotificationService.cs +++ b/src/NzbDrone.Core/Notifications/NotificationService.cs @@ -6,9 +6,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.HealthCheck; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications { @@ -17,7 +17,6 @@ namespace NzbDrone.Core.Notifications IHandle<MovieGrabbedEvent>, IHandle<MovieDownloadedEvent>, IHandle<HealthCheckFailedEvent> - { private readonly INotificationFactory _notificationFactory; private readonly Logger _logger; @@ -31,18 +30,18 @@ namespace NzbDrone.Core.Notifications private string GetMessage(Movie movie, QualityModel quality) { var qualityString = quality.Quality.ToString(); - var ImdbUrl = "https://www.imdb.com/title/" + movie.ImdbId + "/"; + var imdbUrl = "https://www.imdb.com/title/" + movie.ImdbId + "/"; if (quality.Revision.Version > 1) { - qualityString += " Proper"; + qualityString += " Proper"; } return string.Format("{0} ({1}) [{2}] {3}", movie.Title, movie.Year, qualityString, - ImdbUrl); + imdbUrl); } private bool ShouldHandleMovie(ProviderDefinition definition, Movie movie) @@ -95,10 +94,13 @@ namespace NzbDrone.Core.Notifications { try { - if (!ShouldHandleMovie(notification.Definition, message.Movie.Movie)) continue; + if (!ShouldHandleMovie(notification.Definition, message.Movie.Movie)) + { + continue; + } + notification.OnGrab(grabMessage); } - catch (Exception ex) { _logger.Error(ex, "Unable to send OnGrab notification to {0}", notification.Definition.Name); @@ -128,7 +130,6 @@ namespace NzbDrone.Core.Notifications } } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnDownload notification to: " + notification.Definition.Name); @@ -147,7 +148,6 @@ namespace NzbDrone.Core.Notifications notification.OnMovieRename(message.Movie); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnRename notification to: " + notification.Definition.Name); @@ -166,7 +166,6 @@ namespace NzbDrone.Core.Notifications notification.OnHealthIssue(message.HealthCheck); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnHealthIssue notification to: " + notification.Definition.Name); diff --git a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs index f0780642f..a23c83998 100644 --- a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs +++ b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs @@ -1,4 +1,3 @@ - using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs index d983c96c4..564d1b1ad 100644 --- a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs +++ b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs @@ -5,8 +5,8 @@ using System.Xml.Linq; using FluentValidation.Results; using NLog; using NzbDrone.Core.Exceptions; -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.NotifyMyAndroid { @@ -18,8 +18,8 @@ namespace NzbDrone.Core.Notifications.NotifyMyAndroid public class NotifyMyAndroidProxy : INotifyMyAndroidProxy { - private readonly Logger _logger; private const string URL = "https://www.notifymyandroid.com/publicapi"; + private readonly Logger _logger; public NotifyMyAndroidProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs index 86a0d15ec..4235168b4 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs @@ -2,7 +2,8 @@ { public class PlexAuthenticationException : PlexException { - public PlexAuthenticationException(string message) : base(message) + public PlexAuthenticationException(string message) + : base(message) { } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs index 402f4a448..c545c20f5 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs @@ -5,15 +5,18 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexException : NzbDroneException { - public PlexException(string message) : base(message) + public PlexException(string message) + : base(message) { } - public PlexException(string message, params object[] args) : base(message, args) + public PlexException(string message, params object[] args) + : base(message, args) { } - public PlexException(string message, Exception innerException) : base(message, innerException) + public PlexException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs b/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs index d54ea0fef..533f5d866 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs @@ -42,10 +42,10 @@ namespace NzbDrone.Core.Notifications.Plex.PlexTv var request = requestBuilder.Build(); return new PlexTvPinUrlResponse - { - Url = request.Url.ToString(), - Headers = request.Headers.ToDictionary(h => h.Key, h => h.Value) - }; + { + Url = request.Url.ToString(), + Headers = request.Headers.ToDictionary(h => h.Key, h => h.Value) + }; } public PlexTvSignInUrlResponse GetSignInUrl(string callbackUrl, int pinId, string pinCode) @@ -67,10 +67,10 @@ namespace NzbDrone.Core.Notifications.Plex.PlexTv var request = requestBuilder.Build(); return new PlexTvSignInUrlResponse - { - OauthUrl = request.Url.ToString(), - PinId = pinId - }; + { + OauthUrl = request.Url.ToString(), + PinId = pinId + }; } public string GetAuthToken(int pinId) diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs index 439cb57ac..42c7889da 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexVersionException : NzbDroneException { - public PlexVersionException(string message) : base(message) + public PlexVersionException(string message) + : base(message) { } - public PlexVersionException(string message, params object[] args) : base(message, args) + public PlexVersionException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs index db4cd299e..6412b6e2b 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Movies; +using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Plex.Server @@ -91,9 +91,9 @@ namespace NzbDrone.Core.Notifications.Plex.Server var authToken = _plexTvService.GetAuthToken(Convert.ToInt32(query["pinId"])); return new - { - authToken - }; + { + authToken + }; } return new { }; diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs index 253a5ec65..d90eb1365 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server private readonly IConfigService _configService; private readonly Logger _logger; - public PlexServerProxy(IHttpClient httpClient, IConfigService configService,Logger logger) + public PlexServerProxy(IHttpClient httpClient, IConfigService configService, Logger logger) { _httpClient = httpClient; _configService = configService; @@ -46,12 +46,12 @@ namespace NzbDrone.Core.Notifications.Plex.Server .Sections .Where(d => d.Type == "movie") .Select(s => new PlexSection - { - Id = s.Id, - Language = s.Language, - Locations = s.Locations, - Type = s.Type - }) + { + Id = s.Id, + Language = s.Language, + Locations = s.Locations, + Type = s.Type + }) .ToList(); } @@ -132,7 +132,6 @@ namespace NzbDrone.Core.Notifications.Plex.Server items = Json.Deserialize<PlexSectionResponseLegacy>(response) .Items; } - else { items = Json.Deserialize<PlexResponse<PlexSectionResponse>>(response) diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs index d73f54145..6b2d1ccce 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs @@ -47,14 +47,12 @@ namespace NzbDrone.Core.Notifications.Plex.Server { UpdatePartialSection(movie, sections, settings); } - else { sections.ForEach(s => UpdateSection(s.Id, settings)); } } - - catch(Exception ex) + catch (Exception ex) { _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host); throw; @@ -168,7 +166,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server return new ValidationFailure("Host", "At least one Movie library is required"); } } - catch(PlexAuthenticationException ex) + catch (PlexAuthenticationException ex) { _logger.Error(ex, "Unable to connect to Plex Server"); return new ValidationFailure("AuthToken", "Invalid authentication token"); diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs index c9f73def6..024244a0d 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs @@ -51,23 +51,23 @@ namespace NzbDrone.Core.Notifications.PushBullet if (Settings.ApiKey.IsNullOrWhiteSpace()) { return new - { - devices = new List<object>() - }; + { + devices = new List<object>() + }; } Settings.Validate().Filter("ApiKey").ThrowOnError(); var devices = _proxy.GetDevices(Settings); return new - { - options = devices.Where(d => d.Nickname.IsNotNullOrWhiteSpace()) + { + options = devices.Where(d => d.Nickname.IsNotNullOrWhiteSpace()) .OrderBy(d => d.Nickname, StringComparer.InvariantCultureIgnoreCase) .Select(d => new - { - id = d.Id, - name = d.Nickname - }) + { + id = d.Id, + name = d.Nickname + }) }; } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs index ce8b8417d..f8207ef01 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.PushBullet { public class PushBulletException : NzbDroneException { - public PushBulletException(string message) : base(message) + public PushBulletException(string message) + : base(message) { } - public PushBulletException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public PushBulletException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs index db5da246f..451f3b828 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs @@ -4,10 +4,10 @@ using System.Linq; using System.Net; using FluentValidation.Results; using NLog; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Rest; +using RestSharp; using RestSharp.Authenticators; namespace NzbDrone.Core.Notifications.PushBullet @@ -21,9 +21,9 @@ namespace NzbDrone.Core.Notifications.PushBullet public class PushBulletProxy : IPushBulletProxy { - private readonly Logger _logger; private const string PUSH_URL = "https://api.pushbullet.com/v2/pushes"; private const string DEVICE_URL = "https://api.pushbullet.com/v2/devices"; + private readonly Logger _logger; public PushBulletProxy(Logger logger) { @@ -154,7 +154,6 @@ namespace NzbDrone.Core.Notifications.PushBullet { request.AddParameter("device_id", integerId); } - else { request.AddParameter("device_iden", deviceId); diff --git a/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs b/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs index b30b92b90..02a61b418 100644 --- a/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs +++ b/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs @@ -16,8 +16,8 @@ namespace NzbDrone.Core.Notifications.Pushalot public class PushalotProxy : IPushalotProxy { - private readonly Logger _logger; private const string URL = "https://pushalot.com/api/sendmessage"; + private readonly Logger _logger; public PushalotProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs index 7e6fc1f4a..6f9c139a2 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Pushover { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs index 9960bc18a..fddae9d91 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs @@ -2,8 +2,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Pushover { @@ -15,8 +15,8 @@ namespace NzbDrone.Core.Notifications.Pushover public class PushoverProxy : IPushoverProxy { - private readonly Logger _logger; private const string URL = "https://api.pushover.net/1/messages.json"; + private readonly Logger _logger; public PushoverProxy(Logger logger) { @@ -44,7 +44,6 @@ namespace NzbDrone.Core.Notifications.Pushover request.AddParameter("sound", settings.Sound); } - client.ExecuteAndValidate(request); } diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs index 2f5c553a2..646538e38 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs @@ -1,8 +1,8 @@ -using FluentValidation; +using System.Collections.Generic; +using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System.Collections.Generic; namespace NzbDrone.Core.Notifications.Pushover { @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Notifications.Pushover [FieldDefinition(2, Label = "Devices", HelpText = "List of device names (leave blank to send to all devices)", Type = FieldType.Tag)] public IEnumerable<string> Devices { get; set; } - [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority) )] + [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority))] public int Priority { get; set; } [FieldDefinition(4, Label = "Retry", Type = FieldType.Textbox, HelpText = "Interval to retry Emergency alerts, minimum 30 seconds")] diff --git a/src/NzbDrone.Core/Notifications/Slack/Slack.cs b/src/NzbDrone.Core/Notifications/Slack/Slack.cs index 5173c36a3..b570d6aef 100644 --- a/src/NzbDrone.Core/Notifications/Slack/Slack.cs +++ b/src/NzbDrone.Core/Notifications/Slack/Slack.cs @@ -2,11 +2,10 @@ using System; using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Notifications.Slack.Payloads; using NzbDrone.Core.Movies; +using NzbDrone.Core.Notifications.Slack.Payloads; using NzbDrone.Core.Validation; - namespace NzbDrone.Core.Notifications.Slack { public class Slack : NotificationBase<SlackSettings> @@ -65,7 +64,7 @@ namespace NzbDrone.Core.Notifications.Slack } }; - var payload = CreatePayload("Renamed", attachments); + var payload = CreatePayload("Renamed", attachments); _proxy.SendPayload(payload, Settings); } @@ -105,7 +104,6 @@ namespace NzbDrone.Core.Notifications.Slack var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (SlackExeption ex) { diff --git a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs index 1d7fd9b85..952860b6d 100644 --- a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs +++ b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs @@ -3,13 +3,15 @@ using NzbDrone.Common.Exceptions; namespace NzbDrone.Core.Notifications.Slack { - class SlackExeption : NzbDroneException + public class SlackExeption : NzbDroneException { - public SlackExeption(string message) : base(message) + public SlackExeption(string message) + : base(message) { } - public SlackExeption(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public SlackExeption(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs index f7534671b..4c70e61b1 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Synology { public class SynologyException : NzbDroneException { - public SynologyException(string message) : base(message) + public SynologyException(string message) + : base(message) { } - public SynologyException(string message, params object[] args) : base(message, args) + public SynologyException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs index e6e457db5..828b5044e 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Core.Notifications.Synology public override string Link => "https://www.synology.com"; public override string Name => "Synology Indexer"; - public override void OnDownload(DownloadMessage message) { if (Settings.UpdateLibrary) diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs index 5f9be1a2f..7b1084570 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Core.Notifications.Synology { public SynologyIndexerSettingsValidator() { - } } diff --git a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs index 137e7322b..8ad8de02a 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Telegram { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs index 416373ced..cefc637ab 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs @@ -1,12 +1,12 @@ using System; using System.Net; +using System.Web; using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; -using RestSharp; using NzbDrone.Core.Rest; -using System.Web; +using RestSharp; namespace NzbDrone.Core.Notifications.Telegram { @@ -18,8 +18,8 @@ namespace NzbDrone.Core.Notifications.Telegram public class TelegramProxy : ITelegramProxy { - private readonly Logger _logger; private const string URL = "https://api.telegram.org"; + private readonly Logger _logger; public TelegramProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs index dde4bc1aa..8992ca0f8 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs @@ -1,4 +1,3 @@ - namespace NzbDrone.Core.Notifications.Twitter { public class OAuthToken diff --git a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs index b0ef75e61..38fd9ebb7 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs @@ -6,9 +6,8 @@ using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Twitter { - class Twitter : NotificationBase<TwitterSettings> + public class Twitter : NotificationBase<TwitterSettings> { - private readonly ITwitterService _twitterService; public Twitter(ITwitterService twitterService) @@ -72,6 +71,7 @@ namespace NzbDrone.Core.Notifications.Twitter accessTokenSecret = oauthToken.AccessTokenSecret }; } + return new { }; } @@ -84,5 +84,4 @@ namespace NzbDrone.Core.Notifications.Twitter return new ValidationResult(failures); } } - } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs index 99146fa71..77676fbf2 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Notifications.Twitter { public class TwitterException : NzbDroneException { - public TwitterException(string message, params object[] args) : base(message, args) + public TwitterException(string message, params object[] args) + : base(message, args) { } - public TwitterException(string message) : base(message) + public TwitterException(string message) + : base(message) { } - public TwitterException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public TwitterException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public TwitterException(string message, Exception innerException) : base(message, innerException) + public TwitterException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs index 87fb38eb9..39af507f3 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs @@ -1,10 +1,10 @@ -using FluentValidation.Results; -using NLog; -using System; -using System.Net; +using System; using System.Collections.Specialized; using System.IO; +using System.Net; using System.Web; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.OAuth; @@ -82,7 +82,6 @@ namespace NzbDrone.Core.Notifications.Twitter { twitter.DirectMessage(message, settings.Mention); } - else { if (settings.Mention.IsNotNullOrWhiteSpace()) @@ -131,6 +130,7 @@ namespace NzbDrone.Core.Notifications.Twitter _logger.Error(ex, "Unable to send test message"); return new ValidationFailure("Host", "Unable to send test message"); } + return null; } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs index 15e404e95..bc1cf49c6 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Core.Notifications.Twitter RuleFor(c => c.ConsumerSecret).NotEmpty(); RuleFor(c => c.AccessToken).NotEmpty(); RuleFor(c => c.AccessTokenSecret).NotEmpty(); + //TODO: Validate that it is a valid username (numbers, letters and underscores - I think) RuleFor(c => c.Mention).NotEmpty().When(c => c.DirectMessage); diff --git a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs index 1c90c54b8..caba855de 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; using FluentValidation.Results; -using NzbDrone.Core.Movies; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Webhook diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs index b422d8621..07d4c4666 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookException : NzbDroneException { - public WebhookException(string message) : base(message) + public WebhookException(string message) + : base(message) { } - public WebhookException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public WebhookException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs index 57d8f040a..aac72ff6f 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Notifications.Webhook { - class WebhookGrabPayload : WebhookPayload + public class WebhookGrabPayload : WebhookPayload { public WebhookRemoteMovie RemoteMovie { get; set; } public WebhookRelease Release { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs index 7043137c7..f89077cf2 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Notifications.Webhook { - class WebhookImportPayload : WebhookPayload + public class WebhookImportPayload : WebhookPayload { public WebhookRemoteMovie RemoteMovie { get; set; } public WebhookMovieFile MovieFile { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs index 459743f1d..40ff6b400 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs @@ -1,6 +1,6 @@ using System.IO; - using NzbDrone.Core.Movies; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications.Webhook { @@ -12,7 +12,9 @@ namespace NzbDrone.Core.Notifications.Webhook public string ReleaseDate { get; set; } public string FolderPath { get; set; } - public WebhookMovie() { } + public WebhookMovie() + { + } public WebhookMovie(Movie movie) { @@ -22,7 +24,8 @@ namespace NzbDrone.Core.Notifications.Webhook FolderPath = movie.Path; } - public WebhookMovie(Movie movie, MovieFile movieFile) : this(movie) + public WebhookMovie(Movie movie, MovieFile movieFile) + : this(movie) { FilePath = Path.Combine(movie.Path, movieFile.RelativePath); } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs index cd19f2923..b3005f233 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs @@ -2,9 +2,11 @@ using NzbDrone.Core.MediaFiles; namespace NzbDrone.Core.Notifications.Webhook { - class WebhookMovieFile + public class WebhookMovieFile { - public WebhookMovieFile() { } + public WebhookMovieFile() + { + } public WebhookMovieFile(MovieFile movieFile) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs index 9ef82e8f7..f7eedec69 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.Notifications.Webhook void SendWebhook(WebhookPayload payload, WebhookSettings settings); } - class WebhookProxy : IWebhookProxy + public class WebhookProxy : IWebhookProxy { private readonly IHttpClient _httpClient; @@ -35,6 +35,7 @@ namespace NzbDrone.Core.Notifications.Webhook { request.AddBasicAuthentication(settings.Username, settings.Password); } + _httpClient.Execute(request); } catch (RestException ex) diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs index 05d24ad99..2ba11f3cf 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs @@ -5,7 +5,9 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookRelease { - public WebhookRelease() { } + public WebhookRelease() + { + } public WebhookRelease(QualityModel quality, RemoteMovie remoteMovie) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs index cc8279290..d14af047f 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Core.Notifications.Webhook public string Title { get; set; } public int Year { get; set; } - public WebhookRemoteMovie() { } + public WebhookRemoteMovie() + { + } public WebhookRemoteMovie(RemoteMovie remoteMovie) { diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs index e85b5b4e1..a436dc62f 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs @@ -122,7 +122,6 @@ namespace NzbDrone.Core.Notifications.Xbmc private void CheckForError(IRestResponse response) { - if (string.IsNullOrWhiteSpace(response.Content)) { throw new XbmcJsonException("Invalid response from XBMC, the response is not valid JSON"); diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs index 9f96a68c7..2118dd971 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs @@ -68,10 +68,12 @@ namespace NzbDrone.Core.Notifications.Xbmc var matchingMovies = allMovies.FirstOrDefault(s => { return s.ImdbNumber == movie.ImdbId || s.Label == movie.Title; - }); - if (matchingMovies != null) return matchingMovies.File; + if (matchingMovies != null) + { + return matchingMovies.File; + } return null; } @@ -87,11 +89,9 @@ namespace NzbDrone.Core.Notifications.Xbmc moviePath = new OsPath(moviePath).Directory.FullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); _logger.Debug("Updating movie {0} (Path: {1}) on XBMC host: {2}", movie, moviePath, settings.Address); } - else { - _logger.Debug("Movie {0} doesn't exist on XBMC host: {1}, Updating Entire Library", movie, - settings.Address); + _logger.Debug("Movie {0} doesn't exist on XBMC host: {1}, Updating Entire Library", movie, settings.Address); } var response = _proxy.UpdateLibrary(settings, moviePath); @@ -101,7 +101,6 @@ namespace NzbDrone.Core.Notifications.Xbmc _logger.Debug("Failed to update library for: {0}", settings.Address); } } - catch (Exception ex) { _logger.Debug(ex, ex.Message); diff --git a/src/NzbDrone.Core/Organizer/Exception.cs b/src/NzbDrone.Core/Organizer/Exception.cs index c4e80b17d..18efe94cc 100644 --- a/src/NzbDrone.Core/Organizer/Exception.cs +++ b/src/NzbDrone.Core/Organizer/Exception.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Organizer { public class NamingFormatException : NzbDroneException { - public NamingFormatException(string message, params object[] args) : base(message, args) + public NamingFormatException(string message, params object[] args) + : base(message, args) { } - public NamingFormatException(string message) : base(message) + public NamingFormatException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs index d2a3f4ca6..0c4b57f38 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs @@ -9,8 +9,8 @@ using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Organizer { @@ -25,6 +25,8 @@ namespace NzbDrone.Core.Organizer public class FileNameBuilder : IBuildFileNames { + private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; + private readonly INamingConfigService _namingConfigService; private readonly IQualityDefinitionService _qualityDefinitionService; private readonly IUpdateMediaInfo _mediaInfoUpdater; @@ -142,9 +144,8 @@ namespace NzbDrone.Core.Organizer AddReleaseDateTokens(tokenHandlers, movie.Year); AddIdTokens(tokenHandlers, movie); - if(movie.MovieFile != null) + if (movie.MovieFile != null) { - AddQualityTokens(tokenHandlers, movie, movieFile); AddMediaInfoTokens(tokenHandlers, movieFile); AddMovieFileTokens(tokenHandlers, movieFile); @@ -155,7 +156,6 @@ namespace NzbDrone.Core.Organizer AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}" }); } - var directoryName = ReplaceTokens(pattern, tokenHandlers, namingConfig).Trim(); directoryName = FileNameCleanupRegex.Replace(directoryName, match => match.Captures[0].Value[0].ToString()); directoryName = TrimSeparatorsRegex.Replace(directoryName, string.Empty); @@ -166,7 +166,6 @@ namespace NzbDrone.Core.Organizer public BasicNamingConfig GetBasicNamingConfig(NamingConfig nameSpec) { return new BasicNamingConfig(); //For now let's be lazy - } public string GetMovieFolder(Movie movie, NamingConfig namingConfig = null) @@ -194,7 +193,7 @@ namespace NzbDrone.Core.Organizer } else { - AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}"}); + AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}" }); } string name = ReplaceTokens(namingConfig.MovieFolderFormat, tokenHandlers, namingConfig); @@ -286,6 +285,7 @@ namespace NzbDrone.Core.Organizer { tokenHandlers["{Original Title}"] = m => GetOriginalTitle(movieFile); tokenHandlers["{Original Filename}"] = m => GetOriginalFileName(movieFile); + //tokenHandlers["{IMDb Id}"] = m => tokenHandlers["{Release Group}"] = m => movieFile.ReleaseGroup ?? m.DefaultValue("Radarr"); } @@ -305,17 +305,16 @@ namespace NzbDrone.Core.Organizer var qualityProper = GetQualityProper(movie, movieFile.Quality); var qualityReal = GetQualityReal(movie, movieFile.Quality); - tokenHandlers["{Quality Full}"] = m => String.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); + tokenHandlers["{Quality Full}"] = m => string.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); tokenHandlers["{Quality Title}"] = m => qualityTitle; tokenHandlers["{Quality Proper}"] = m => qualityProper; tokenHandlers["{Quality Real}"] = m => qualityReal; } - private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; private static readonly IReadOnlyDictionary<string, int> MinimumMediaInfoSchemaRevisions = new Dictionary<string, int>(FileNameBuilderTokenEqualityComparer.Instance) { - {MediaInfoVideoDynamicRangeToken, 5} + { MediaInfoVideoDynamicRangeToken, 5 } }; private void AddMediaInfoTokens(Dictionary<string, Func<TokenMatch, string>> tokenHandlers, MovieFile movieFile) @@ -329,9 +328,8 @@ namespace NzbDrone.Core.Organizer var sceneName = movieFile.GetSceneOrFileName(); - - var videoCodec = MediaInfoFormatter.FormatVideoCodec(movieFile.MediaInfo, sceneName); - var audioCodec = MediaInfoFormatter.FormatAudioCodec(movieFile.MediaInfo, sceneName); + var videoCodec = MediaInfoFormatter.FormatVideoCodec(movieFile.MediaInfo, sceneName); + var audioCodec = MediaInfoFormatter.FormatAudioCodec(movieFile.MediaInfo, sceneName); var audioChannels = MediaInfoFormatter.FormatAudioChannels(movieFile.MediaInfo); var audioLanguages = movieFile.MediaInfo.AudioLanguages ?? string.Empty; var subtitles = movieFile.MediaInfo.Subtitles ?? string.Empty; @@ -389,7 +387,9 @@ namespace NzbDrone.Core.Organizer foreach (var item in mediaInfoLanguages.Split('/')) { if (!string.IsNullOrWhiteSpace(item)) + { tokens.Add(item.Trim()); + } } var cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); @@ -400,7 +400,9 @@ namespace NzbDrone.Core.Organizer var cultureInfo = cultures.FirstOrDefault(p => p.EnglishName == tokens[i]); if (cultureInfo != null) + { tokens[i] = cultureInfo.TwoLetterISOLanguageName.ToUpper(); + } } catch { @@ -483,7 +485,10 @@ namespace NzbDrone.Core.Organizer private string ReplaceNumberToken(string token, int value) { var split = token.Trim('{', '}').Split(':'); - if (split.Length == 1) return value.ToString("0"); + if (split.Length == 1) + { + return value.ToString("0"); + } return value.ToString(split[1]); } @@ -495,7 +500,7 @@ namespace NzbDrone.Core.Organizer return "Proper"; } - return String.Empty; + return string.Empty; } private string GetQualityReal(Movie movie, QualityModel quality) diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs index 1b11f81c2..e5ffe79f5 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Organizer private FileNameBuilderTokenEqualityComparer() { - } public bool Equals(string s1, string s2) diff --git a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs index 90ac35482..ad93b1a1d 100644 --- a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs @@ -1,7 +1,7 @@ using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Organizer { diff --git a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs index 83c9eb798..86d3911eb 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Organizer var validationFailure = new ValidationFailure("MovieFormat", ERROR_MESSAGE); var parsedMovieInfo = Parser.Parser.ParseMovieTitle(sampleResult.FileName, false); //We are not lenient when testing naming schemes - if(parsedMovieInfo == null) + if (parsedMovieInfo == null) { return validationFailure; } diff --git a/src/NzbDrone.Core/Organizer/NamingConfig.cs b/src/NzbDrone.Core/Organizer/NamingConfig.cs index 036ac20f2..6c9ad3589 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfig.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfig.cs @@ -30,10 +30,9 @@ namespace NzbDrone.Core.Organizer SpaceDashSpace = 3 } - static class ColonReplacementFormatMethods + public static class ColonReplacementFormatMethods { - - public static String GetFormatString(this ColonReplacementFormat format) + public static string GetFormatString(this ColonReplacementFormat format) { switch (format) { diff --git a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs index 6c32eee62..ca0138b67 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Organizer { public interface INamingConfigRepository : IBasicRepository<NamingConfig> { - } public class NamingConfigRepository : BasicRepository<NamingConfig>, INamingConfigRepository @@ -14,6 +13,5 @@ namespace NzbDrone.Core.Organizer : base(database, eventAggregator) { } - } } diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs index e50f82a5e..54528815a 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs @@ -7,7 +7,6 @@ using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithAdditionalFormats : IAugmentParsedMovieInfo - { public Type HelperType { @@ -28,7 +27,7 @@ namespace NzbDrone.Core.Parser.Augmenters } else { - movieInfo.ExtraInfo["AdditionalFormats"] = new List<CustomFormat>{format}; + movieInfo.ExtraInfo["AdditionalFormats"] = new List<CustomFormat> { format }; } } diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs index 77bfd29e7..770eb8820 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs @@ -4,7 +4,6 @@ using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithFileSize : IAugmentParsedMovieInfo - { public Type HelperType { diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs index 2ded7942c..daacb6d65 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs @@ -9,7 +9,6 @@ using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithHistory : IAugmentParsedMovieInfo - { private readonly IIndexerFactory _indexerFactory; private readonly IEnumerable<IAugmentParsedMovieInfo> _augmenters; diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs index 8fb41be3e..5c94dd84f 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs @@ -7,7 +7,6 @@ using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithMediaInfo : IAugmentParsedMovieInfo - { public Type HelperType { @@ -52,7 +51,6 @@ namespace NzbDrone.Core.Parser.Augmenters movieInfo.Quality = quality; } } - } return movieInfo; diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs index fd4df7400..34f380210 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs @@ -8,7 +8,6 @@ using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithReleaseInfo : IAugmentParsedMovieInfo - { private readonly IIndexerFactory _indexerFactory; @@ -29,15 +28,16 @@ namespace NzbDrone.Core.Parser.Augmenters { if (helper is ReleaseInfo releaseInfo) { - IIndexerSettings indexerSettings = null; - try { + try + { indexerSettings = _indexerFactory.Get(releaseInfo.IndexerId)?.Settings as IIndexerSettings; } catch (Exception) { //_logger.Debug("Indexer with id {0} does not exist, skipping minimum seeder checks.", subject.Release.IndexerId); } // First, let's augment the language! + var languageTitle = movieInfo.SimpleReleaseTitle; if (movieInfo.MovieTitle.IsNotNullOrWhiteSpace()) { @@ -45,12 +45,13 @@ namespace NzbDrone.Core.Parser.Augmenters { foreach (var i in indexerSettings.MultiLanguages) { - var language = (Language) i; + var language = (Language)i; if (!movieInfo.Languages.Contains(language)) + { movieInfo.Languages.Add(language); + } } } - } //Next, let's add other useful info to the extra info dict @@ -58,8 +59,8 @@ namespace NzbDrone.Core.Parser.Augmenters { movieInfo.ExtraInfo["Size"] = releaseInfo.Size; } - movieInfo.ExtraInfo["IndexerFlags"] = releaseInfo.IndexerFlags; + movieInfo.ExtraInfo["IndexerFlags"] = releaseInfo.IndexerFlags; } return movieInfo; diff --git a/src/NzbDrone.Core/Parser/InvalidDateException.cs b/src/NzbDrone.Core/Parser/InvalidDateException.cs index 722517d0e..97c5da581 100644 --- a/src/NzbDrone.Core/Parser/InvalidDateException.cs +++ b/src/NzbDrone.Core/Parser/InvalidDateException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Parser { public class InvalidDateException : NzbDroneException { - public InvalidDateException(string message, params object[] args) : base(message, args) + public InvalidDateException(string message, params object[] args) + : base(message, args) { } - public InvalidDateException(string message) : base(message) + public InvalidDateException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Parser/IsoLanguage.cs b/src/NzbDrone.Core/Parser/IsoLanguage.cs index dcf33e88a..20ada2859 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguage.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguage.cs @@ -26,6 +26,5 @@ namespace NzbDrone.Core.Parser Language = language; AltCodes.AddRange(twoLetterCodes); } - } } diff --git a/src/NzbDrone.Core/Parser/IsoLanguages.cs b/src/NzbDrone.Core/Parser/IsoLanguages.cs index 86cb82140..d6789ec6b 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguages.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguages.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Parser { private static readonly HashSet<IsoLanguage> All = new HashSet<IsoLanguage> { - new IsoLanguage(new List<string> {"en", "us", "uk"}, "eng", Language.English), + new IsoLanguage(new List<string> { "en", "us", "uk" }, "eng", Language.English), new IsoLanguage("fr", "fra", Language.French), new IsoLanguage("es", "spa", Language.Spanish), new IsoLanguage("de", "deu", Language.German), @@ -16,6 +16,7 @@ namespace NzbDrone.Core.Parser new IsoLanguage("da", "dan", Language.Danish), new IsoLanguage("nl", "nld", Language.Dutch), new IsoLanguage("ja", "jpn", Language.Japanese), + // new IsoLanguage("", "", Language.Cantonese), // new IsoLanguage("", "", Language.Mandarin), new IsoLanguage("ru", "rus", Language.Russian), @@ -26,6 +27,7 @@ namespace NzbDrone.Core.Parser new IsoLanguage("fi", "fin", Language.Finnish), new IsoLanguage("tr", "tur", Language.Turkish), new IsoLanguage("pt", "por", Language.Portuguese), + // new IsoLanguage("nl", "nld", Language.Flemish), new IsoLanguage("el", "ell", Language.Greek), new IsoLanguage("ko", "kor", Language.Korean), diff --git a/src/NzbDrone.Core/Parser/LanguageParser.cs b/src/NzbDrone.Core/Parser/LanguageParser.cs index 6fc88a477..641279c79 100644 --- a/src/NzbDrone.Core/Parser/LanguageParser.cs +++ b/src/NzbDrone.Core/Parser/LanguageParser.cs @@ -25,100 +25,161 @@ namespace NzbDrone.Core.Parser var languages = new List<Language>(); if (lowerTitle.Contains("english")) + { languages.Add(Language.English); + } if (lowerTitle.Contains("french")) + { languages.Add(Language.French); + } if (lowerTitle.Contains("spanish")) - languages.Add( Language.Spanish); + { + languages.Add(Language.Spanish); + } if (lowerTitle.Contains("danish")) - languages.Add( Language.Danish); + { + languages.Add(Language.Danish); + } if (lowerTitle.Contains("dutch")) - languages.Add( Language.Dutch); + { + languages.Add(Language.Dutch); + } if (lowerTitle.Contains("japanese")) - languages.Add( Language.Japanese); + { + languages.Add(Language.Japanese); + } if (lowerTitle.Contains("icelandic")) - languages.Add( Language.Icelandic); + { + languages.Add(Language.Icelandic); + } if (lowerTitle.Contains("mandarin") || lowerTitle.Contains("cantonese") || lowerTitle.Contains("chinese")) - languages.Add( Language.Chinese); + { + languages.Add(Language.Chinese); + } if (lowerTitle.Contains("korean")) - languages.Add( Language.Korean); + { + languages.Add(Language.Korean); + } if (lowerTitle.Contains("russian")) - languages.Add( Language.Russian); + { + languages.Add(Language.Russian); + } if (lowerTitle.Contains("polish")) - languages.Add( Language.Polish); + { + languages.Add(Language.Polish); + } if (lowerTitle.Contains("vietnamese")) - languages.Add( Language.Vietnamese); + { + languages.Add(Language.Vietnamese); + } if (lowerTitle.Contains("swedish")) - languages.Add( Language.Swedish); + { + languages.Add(Language.Swedish); + } if (lowerTitle.Contains("norwegian")) - languages.Add( Language.Norwegian); + { + languages.Add(Language.Norwegian); + } if (lowerTitle.Contains("nordic")) - languages.Add( Language.Norwegian); + { + languages.Add(Language.Norwegian); + } if (lowerTitle.Contains("finnish")) - languages.Add( Language.Finnish); + { + languages.Add(Language.Finnish); + } if (lowerTitle.Contains("turkish")) - languages.Add( Language.Turkish); + { + languages.Add(Language.Turkish); + } if (lowerTitle.Contains("portuguese")) - languages.Add( Language.Portuguese); + { + languages.Add(Language.Portuguese); + } if (lowerTitle.Contains("hungarian")) - languages.Add( Language.Hungarian); + { + languages.Add(Language.Hungarian); + } if (lowerTitle.Contains("hebrew")) - languages.Add( Language.Hebrew); + { + languages.Add(Language.Hebrew); + } if (lowerTitle.Contains("czech")) - languages.Add( Language.Czech); + { + languages.Add(Language.Czech); + } var match = LanguageRegex.Match(title); if (match.Groups["italian"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Italian); + { + languages.Add(Language.Italian); + } if (match.Groups["german"].Captures.Cast<Capture>().Any()) - languages.Add( Language.German); + { + languages.Add(Language.German); + } if (match.Groups["flemish"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Flemish); + { + languages.Add(Language.Flemish); + } if (match.Groups["greek"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Greek); + { + languages.Add(Language.Greek); + } if (match.Groups["french"].Success) - languages.Add( Language.French); + { + languages.Add(Language.French); + } if (match.Groups["russian"].Success) - languages.Add( Language.Russian); + { + languages.Add(Language.Russian); + } if (match.Groups["dutch"].Success) - languages.Add( Language.Dutch); + { + languages.Add(Language.Dutch); + } if (match.Groups["hungarian"].Success) - languages.Add( Language.Hungarian); + { + languages.Add(Language.Hungarian); + } if (match.Groups["hebrew"].Success) - languages.Add( Language.Hebrew); + { + languages.Add(Language.Hebrew); + } if (match.Groups["czech"].Success) - languages.Add( Language.Czech); - + { + languages.Add(Language.Czech); + } return languages.DistinctBy(l => (int)l).ToList(); } @@ -134,7 +195,10 @@ namespace NzbDrone.Core.Parser } } - if (!languages.Any()) languages.Add(Language.English); + if (!languages.Any()) + { + languages.Add(Language.English); + } return languages; } diff --git a/src/NzbDrone.Core/Parser/Model/LocalMovie.cs b/src/NzbDrone.Core/Parser/Model/LocalMovie.cs index b0999f55e..d1f96956c 100644 --- a/src/NzbDrone.Core/Parser/Model/LocalMovie.cs +++ b/src/NzbDrone.Core/Parser/Model/LocalMovie.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { @@ -26,7 +26,6 @@ namespace NzbDrone.Core.Parser.Model public string ReleaseGroup { get; set; } public string Edition { get; set; } - public override string ToString() { return Path; diff --git a/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs index e22c02cba..a9dbc2c18 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs @@ -1,42 +1,27 @@ using System.Collections.Generic; using Newtonsoft.Json; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { - /// <summary> - /// Object containing all info our intelligent parser could find out from release / file title, release info and media info. - /// </summary> public class ParsedMovieInfo { - /// <summary> - /// The fully Parsed title. This is useful for finding the matching movie in the database. - /// </summary> public string MovieTitle { get; set; } - /// <summary> - /// The simple release title replaces the actual movie title parsed with A Movie in the release / file title. - /// This is useful to not accidentaly identify stuff inside the actual movie title as quality tags, etc. - /// It also removes unecessary stuff such as file extensions. - /// </summary> public string SimpleReleaseTitle { get; set; } public QualityModel Quality { get; set; } - /// <summary> - /// Extra info is a dictionary containing extra info needed for correct quality assignement. - /// It is expanded by the augmenters. - /// </summary> [JsonIgnore] public Dictionary<string, object> ExtraInfo = new Dictionary<string, object>(); public List<Language> Languages = new List<Language>(); public string ReleaseGroup { get; set; } public string ReleaseHash { get; set; } - public string Edition { get; set;} + public string Edition { get; set; } public int Year { get; set; } public string ImdbId { get; set; } public override string ToString() { - return String.Format("{0} - {1} {2}", MovieTitle, Year, Quality); + return string.Format("{0} - {1} {2}", MovieTitle, Year, Quality); } #if LIBRARY diff --git a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs index 42f61184c..3c18a2814 100644 --- a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs @@ -26,14 +26,11 @@ namespace NzbDrone.Core.Parser.Model public string Codec { get; set; } public string Resolution { get; set; } - public IndexerFlags IndexerFlags { get; set; } + public IndexerFlags IndexerFlags { get; set; } public int Age { - get - { - return DateTime.UtcNow.Subtract(PublishDate).Days; - } + get { return DateTime.UtcNow.Subtract(PublishDate).Days; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? @@ -42,10 +39,7 @@ namespace NzbDrone.Core.Parser.Model public double AgeHours { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalHours; - } + get { return DateTime.UtcNow.Subtract(PublishDate).TotalHours; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? @@ -54,10 +48,7 @@ namespace NzbDrone.Core.Parser.Model public double AgeMinutes { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; - } + get { return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? diff --git a/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs b/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs index 26758db08..9274fcaff 100644 --- a/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs +++ b/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Movies; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Movies; namespace NzbDrone.Core.Parser.Model { diff --git a/src/NzbDrone.Core/Parser/Parser.cs b/src/NzbDrone.Core/Parser/Parser.cs index 5eee7b420..102c1e923 100644 --- a/src/NzbDrone.Core/Parser/Parser.cs +++ b/src/NzbDrone.Core/Parser/Parser.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Parser.Model; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation; +using NzbDrone.Core.Parser.Model; #if !LIBRARY #endif @@ -37,7 +37,6 @@ namespace NzbDrone.Core.Parser //As a last resort for movies that have ( or [ in their title. new Regex(@"^(?<title>.+?)?(?:(?:[-_\W](?<![)\[!]))*(?<year>(1(8|9)|20)\d{2}(?!p|i|\d+|\]|\W\d+)))+(\W+|_|$)(?!\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled), - }; private static readonly Regex[] ReportMovieTitleFolderRegex = new[] @@ -54,7 +53,6 @@ namespace NzbDrone.Core.Parser private static readonly Regex[] ReportMovieTitleLenientRegexAfter = new Regex[] { - }; private static readonly Regex[] RejectHashedReleasesRegex = new Regex[] @@ -138,11 +136,11 @@ namespace NzbDrone.Core.Parser private static readonly Regex ReportEditionRegex = new Regex(@"\b(?<edition>(((Extended.|Ultimate.)?(Director.?s|Collector.?s|Theatrical|Ultimate|Final(?=(.(Cut|Edition|Version)))|Extended|Rogue|Special|Despecialized|\d{2,3}(th)?.Anniversary)(.(Cut|Edition|Version))?(.(Extended|Uncensored|Remastered|Unrated|Uncut|IMAX|Fan.?Edit))?|((Uncensored|Remastered|Unrated|Uncut|IMAX|Fan.?Edit|Edition|Restored|((2|3|4)in1))))))\)?\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly string[] Numbers = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; - private static Dictionary<String, String> _umlautMappings = new Dictionary<string, string> + private static Dictionary<string, string> _umlautMappings = new Dictionary<string, string> { - {"ö", "oe"}, - {"ä", "ae"}, - {"ü", "ue"}, + { "ö", "oe" }, + { "ä", "ae" }, + { "ü", "ue" }, }; public static ParsedMovieInfo ParseMoviePath(string path, bool isLenient) @@ -164,14 +162,16 @@ namespace NzbDrone.Core.Parser } return result; - } public static ParsedMovieInfo ParseMovieTitle(string title, bool isLenient, bool isDir = false) { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}'", title); @@ -234,7 +234,6 @@ namespace NzbDrone.Core.Parser if (result != null) { //TODO: Add tests for this! - var simpleReleaseTitle = SimpleReleaseTitleRegex.Replace(title, string.Empty); if (result.MovieTitle.IsNotNullOrWhiteSpace()) @@ -287,7 +286,9 @@ namespace NzbDrone.Core.Parser catch (Exception e) { if (!title.ToLower().Contains("password") && !title.ToLower().Contains("yenc")) + { Logger.Error(e, "An error has occurred while trying to parse {0}", title); + } } Logger.Debug("Unable to parse {0}", title); @@ -377,7 +378,9 @@ namespace NzbDrone.Core.Parser //If Title only contains numbers return it as is. if (long.TryParse(title, out number)) + { return title; + } return ReplaceGermanUmlauts(NormalizeRegex.Replace(title, string.Empty).ToLower()).RemoveAccent(); } @@ -445,6 +448,7 @@ namespace NzbDrone.Core.Parser { return string.Empty; } + return m.Value; }); @@ -458,7 +462,6 @@ namespace NzbDrone.Core.Parser return null; } - var movieName = matchCollection[0].Groups["title"].Value./*Replace('.', ' ').*/Replace('_', ' '); movieName = RequestInfoRegex.Replace(movieName, "").Trim(' '); @@ -469,10 +472,11 @@ namespace NzbDrone.Core.Parser string nextPart = ""; foreach (var part in parts) { - if (parts.Length >= n+2) + if (parts.Length >= n + 2) { - nextPart = parts[n+1]; + nextPart = parts[n + 1]; } + if (part.Length == 1 && part.ToLower() != "a" && !int.TryParse(part, out n)) { movieName += part + "."; @@ -490,8 +494,10 @@ namespace NzbDrone.Core.Parser movieName += " "; previousAcronym = false; } + movieName += part + " "; } + n++; } diff --git a/src/NzbDrone.Core/Parser/ParsingService.cs b/src/NzbDrone.Core/Parser/ParsingService.cs index a97b39505..2eac5bde0 100644 --- a/src/NzbDrone.Core/Parser/ParsingService.cs +++ b/src/NzbDrone.Core/Parser/ParsingService.cs @@ -8,12 +8,12 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.CustomFormats; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; +using NzbDrone.Core.Parser.Augmenters; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.RomanNumerals; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Parser.Augmenters; namespace NzbDrone.Core.Parser { @@ -82,7 +82,6 @@ namespace NzbDrone.Core.Parser // minimalInfo.Quality.Quality = QualityFinder.FindBySourceAndResolution(minimalInfo.Quality.Quality.Source, minimalInfo.Quality.Quality.Resolution, // minimalInfo.Quality.Quality.Modifier); - if (minimalInfo != null) { minimalInfo.Quality.CustomFormats = ParseCustomFormat(minimalInfo); @@ -190,8 +189,9 @@ namespace NzbDrone.Core.Parser { var result = GetMovie(parsedMovieInfo, imdbId, searchCriteria); - if (result == null) { - result = new MappingResult {MappingResultType = MappingResultType.Unknown}; + if (result == null) + { + result = new MappingResult { MappingResultType = MappingResultType.Unknown }; result.Movie = null; } @@ -204,7 +204,7 @@ namespace NzbDrone.Core.Parser { // TODO: Answer me this: Wouldn't it be smarter to start out looking for a movie if we have an ImDb Id? MappingResult result = null; - if (!String.IsNullOrWhiteSpace(imdbId) && imdbId != "0") + if (!string.IsNullOrWhiteSpace(imdbId) && imdbId != "0") { if (TryGetMovieByImDbId(parsedMovieInfo, imdbId, out result)) { @@ -233,17 +233,23 @@ namespace NzbDrone.Core.Parser private bool TryGetMovieByImDbId(ParsedMovieInfo parsedMovieInfo, string imdbId, out MappingResult result) { var movie = _movieService.FindByImdbId(imdbId); + //Should fix practically all problems, where indexer is shite at adding correct imdbids to movies. if (movie != null && parsedMovieInfo.Year > 1800 && (parsedMovieInfo.Year != movie.Year && movie.SecondaryYear != parsedMovieInfo.Year)) { - result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.WrongYear}; + result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.WrongYear }; return false; } - if (movie != null) { + + if (movie != null) + { result = new MappingResult { Movie = movie }; - } else { - result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.TitleNotFound}; } + else + { + result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.TitleNotFound }; + } + return movie != null; } @@ -264,7 +270,7 @@ namespace NzbDrone.Core.Parser movieByTitleAndOrYear = _movieService.FindByTitle(parsedMovieInfo.MovieTitle); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.WrongYear}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.WrongYear }; return false; } @@ -273,12 +279,12 @@ namespace NzbDrone.Core.Parser movieByTitleAndOrYear = _movieService.FindByTitleInexact(parsedMovieInfo.MovieTitle, parsedMovieInfo.Year); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult {Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } } - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound }; return false; } @@ -294,12 +300,12 @@ namespace NzbDrone.Core.Parser movieByTitleAndOrYear = _movieService.FindByTitleInexact(parsedMovieInfo.MovieTitle, null); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult {Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } } - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound }; return false; } @@ -331,7 +337,6 @@ namespace NzbDrone.Core.Parser string romanNumeral = numeralMapping.RomanNumeralLowerCase; //_logger.Debug(cleanTitle); - if (title.Replace(arabicNumeral, romanNumeral) == parsedMovieInfo.MovieTitle.CleanSeriesTitle()) { possibleMovie = searchCriteria.Movie; @@ -341,7 +346,6 @@ namespace NzbDrone.Core.Parser { possibleMovie = searchCriteria.Movie; } - } } @@ -352,6 +356,7 @@ namespace NzbDrone.Core.Parser result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.Success }; return true; } + result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.WrongYear }; return false; } @@ -362,9 +367,9 @@ namespace NzbDrone.Core.Parser cleanTitle.Contains(searchCriteria.Movie.CleanTitle)) { possibleMovie = searchCriteria.Movie; - if (parsedMovieInfo.Year > 1800 && parsedMovieInfo.Year == possibleMovie.Year || possibleMovie.SecondaryYear == parsedMovieInfo.Year) + if ((parsedMovieInfo.Year > 1800 && parsedMovieInfo.Year == possibleMovie.Year) || possibleMovie.SecondaryYear == parsedMovieInfo.Year) { - result = new MappingResult {Movie = possibleMovie, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } @@ -383,10 +388,8 @@ namespace NzbDrone.Core.Parser return false; } - } - public class MappingResult { public string Message @@ -417,8 +420,10 @@ namespace NzbDrone.Core.Parser public RemoteMovie RemoteMovie; public MappingResultType MappingResultType { get; set; } - public Movie Movie { - get { + public Movie Movie + { + get + { return RemoteMovie.Movie; } set @@ -428,6 +433,7 @@ namespace NzbDrone.Core.Parser { parsedInfo = RemoteMovie.ParsedMovieInfo; } + RemoteMovie = new RemoteMovie { Movie = value, @@ -438,11 +444,13 @@ namespace NzbDrone.Core.Parser public string ReleaseName { get; set; } - public override string ToString() { + public override string ToString() + { return string.Format(Message, RemoteMovie.Movie); } - public Rejection ToRejection() { + public Rejection ToRejection() + { switch (MappingResultType) { case MappingResultType.Success: diff --git a/src/NzbDrone.Core/Parser/QualityParser.cs b/src/NzbDrone.Core/Parser/QualityParser.cs index 992a64681..78606fb8c 100644 --- a/src/NzbDrone.Core/Parser/QualityParser.cs +++ b/src/NzbDrone.Core/Parser/QualityParser.cs @@ -128,7 +128,6 @@ namespace NzbDrone.Core.Parser { if (sourceMatch.Groups["bluray"].Success) { - if (brDiskMatch) { result.Quality = Quality.BRDISK; @@ -352,7 +351,6 @@ namespace NzbDrone.Core.Parser } } - // Anime Bluray matching if (AnimeBlurayRegex.Match(normalizedName).Success) { @@ -474,12 +472,35 @@ namespace NzbDrone.Core.Parser { var match = ResolutionRegex.Match(name); - if (!match.Success) return Resolution.Unknown; - if (match.Groups["R480p"].Success) return Resolution.R480p; - if (match.Groups["R576p"].Success) return Resolution.R576p; - if (match.Groups["R720p"].Success) return Resolution.R720p; - if (match.Groups["R1080p"].Success) return Resolution.R1080p; - if (match.Groups["R2160p"].Success) return Resolution.R2160p; + if (!match.Success) + { + return Resolution.Unknown; + } + + if (match.Groups["R480p"].Success) + { + return Resolution.R480p; + } + + if (match.Groups["R576p"].Success) + { + return Resolution.R576p; + } + + if (match.Groups["R720p"].Success) + { + return Resolution.R720p; + } + + if (match.Groups["R1080p"].Success) + { + return Resolution.R1080p; + } + + if (match.Groups["R2160p"].Success) + { + return Resolution.R2160p; + } return Resolution.Unknown; } @@ -488,9 +509,20 @@ namespace NzbDrone.Core.Parser { var match = OtherSourceRegex.Match(name); - if (!match.Success) return Quality.Unknown; - if (match.Groups["sdtv"].Success) return Quality.SDTV; - if (match.Groups["hdtv"].Success) return Quality.HDTV720p; + if (!match.Success) + { + return Quality.Unknown; + } + + if (match.Groups["sdtv"].Success) + { + return Quality.SDTV; + } + + if (match.Groups["hdtv"].Success) + { + return Quality.HDTV720p; + } return Quality.Unknown; } diff --git a/src/NzbDrone.Core/Parser/RegexReplace.cs b/src/NzbDrone.Core/Parser/RegexReplace.cs index b27f0c4c1..40ff075ce 100644 --- a/src/NzbDrone.Core/Parser/RegexReplace.cs +++ b/src/NzbDrone.Core/Parser/RegexReplace.cs @@ -23,18 +23,27 @@ namespace NzbDrone.Core.Parser public string Replace(string input) { if (_replacementFunc != null) + { return _regex.Replace(input, _replacementFunc); + } else + { return _regex.Replace(input, _replacementFormat); + } } public bool TryReplace(ref string input) { var result = _regex.IsMatch(input); if (_replacementFunc != null) + { input = _regex.Replace(input, _replacementFunc); + } else + { input = _regex.Replace(input, _replacementFormat); + } + return result; } } diff --git a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs index 233bad2bc..bec6cb7dc 100644 --- a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs +++ b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs @@ -9,8 +9,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals /// </summary> public class RomanNumeral : IComparable, IComparable<RomanNumeral>, IEquatable<RomanNumeral>, IRomanNumeral { - #region Fields - /// <summary> /// The numeric value of the roman numeral. /// </summary> @@ -31,10 +29,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals private static readonly string[] Tens = { "XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X" }; private static readonly string[] Units = { "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I" }; - #endregion - - #region Constructors - /// <summary> /// Initializes a new instance of the <see cref="RomanNumeral"/> class. /// </summary> @@ -66,10 +60,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals } } - #endregion - - #region Methods - /// <summary> /// Converts this instance to an integer. /// </summary> @@ -101,7 +91,11 @@ namespace NzbDrone.Core.Parser.RomanNumerals public static bool TryParse(string text, out int value) { value = 0; - if (string.IsNullOrEmpty(text)) return false; + if (string.IsNullOrEmpty(text)) + { + return false; + } + text = text.ToUpper(); int len = 0; @@ -188,10 +182,26 @@ namespace NzbDrone.Core.Parser.RomanNumerals tens = number / 10; units = number % 10; var sb = new StringBuilder(); - if (thousands > 0) sb.Append(Thousands[3 - thousands]); - if (hundreds > 0) sb.Append(Hundreds[9 - hundreds]); - if (tens > 0) sb.Append(Tens[9 - tens]); - if (units > 0) sb.Append(Units[9 - units]); + if (thousands > 0) + { + sb.Append(Thousands[3 - thousands]); + } + + if (hundreds > 0) + { + sb.Append(Hundreds[9 - hundreds]); + } + + if (tens > 0) + { + sb.Append(Tens[9 - tens]); + } + + if (units > 0) + { + sb.Append(Units[9 - units]); + } + return sb.ToString(); } @@ -199,7 +209,7 @@ namespace NzbDrone.Core.Parser.RomanNumerals /// Returns the Roman numeral that was passed in as either an Arabic numeral /// or a Roman numeral. /// </summary> - /// <returns>A <see cref="System.String" /> representing a Roman Numeral</returns> + /// <returns>A <see cref="System.string" /> representing a Roman Numeral</returns> public string ToRomanNumeral() { return ToString(); @@ -217,17 +227,16 @@ namespace NzbDrone.Core.Parser.RomanNumerals private static void RangeGuard(int number) { if (number > MaxValue) - throw new ArgumentOutOfRangeException(nameof(number), number, - $"Roman numerals can not be larger than {MaxValue}."); + { + throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be larger than {MaxValue}."); + } + if (number < MinValue) - throw new ArgumentOutOfRangeException(nameof(number), number, - $"Roman numerals can not be smaller than {MinValue}."); + { + throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be smaller than {MinValue}."); + } } - #endregion - - #region Operators - /// <summary> /// Implements the operator *. /// </summary> @@ -280,10 +289,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals return new RomanNumeral(firstNumeral._value - secondNumeral._value); } - #endregion - - #region Interface Implementations - /// <summary> /// </summary> /// <param name="obj">The object.</param> @@ -344,14 +349,11 @@ namespace NzbDrone.Core.Parser.RomanNumerals /// during creation. /// </summary> /// <returns> - /// A <see cref="System.String" /> that represents a Roman Numeral. + /// A <see cref="System.string" /> that represents a Roman Numeral. /// </returns> public override string ToString() { return ToRomanNumeral(_value); } - - #endregion } - } diff --git a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs index 38066af65..e8d6368d7 100644 --- a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs +++ b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs @@ -4,8 +4,6 @@ using System.Linq; namespace NzbDrone.Core.Parser.RomanNumerals { - - public static class RomanNumeralParser { private const int DICTIONARY_PREPOPULATION_SIZE = 20; @@ -21,13 +19,14 @@ namespace NzbDrone.Core.Parser.RomanNumerals private static void PopluateDictionariesReasonablyLarge() { - if(_simpleArabicNumeralMappings != null || _arabicRomanNumeralsMapping != null) + if (_simpleArabicNumeralMappings != null || _arabicRomanNumeralsMapping != null) { return; } + _arabicRomanNumeralsMapping = new HashSet<ArabicRomanNumeral>(); _simpleArabicNumeralMappings = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); - foreach (int arabicNumeral in Enumerable.Range(1,DICTIONARY_PREPOPULATION_SIZE +1)) + foreach (int arabicNumeral in Enumerable.Range(1, DICTIONARY_PREPOPULATION_SIZE + 1)) { string romanNumeralAsString, arabicNumeralAsString; GenerateRomanNumerals(arabicNumeral, out romanNumeralAsString, out arabicNumeralAsString); @@ -58,6 +57,7 @@ namespace NzbDrone.Core.Parser.RomanNumerals ArabicRomanNumeral arm = new ArabicRomanNumeral(arabicNumeral, arabicNumeralAsString, romanNumeral); additionalArabicRomanNumerals.Add(arm); } + return additionalArabicRomanNumerals; } @@ -71,18 +71,20 @@ namespace NzbDrone.Core.Parser.RomanNumerals if (upToArabicNumber < DICTIONARY_PREPOPULATION_SIZE) { return - (HashSet<ArabicRomanNumeral>) - new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping).Take(upToArabicNumber); + (HashSet<ArabicRomanNumeral>)new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping).Take(upToArabicNumber); } + if (upToArabicNumber >= DICTIONARY_PREPOPULATION_SIZE) { if (_arabicRomanNumeralsMapping.Count >= upToArabicNumber) { return new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping.Take(upToArabicNumber)); } + HashSet<ArabicRomanNumeral> largerMapping = GenerateAdditionalMappings(DICTIONARY_PREPOPULATION_SIZE + 1, upToArabicNumber); _arabicRomanNumeralsMapping = (HashSet<ArabicRomanNumeral>)_arabicRomanNumeralsMapping.Union(largerMapping); } + return _arabicRomanNumeralsMapping; } @@ -99,30 +101,32 @@ namespace NzbDrone.Core.Parser.RomanNumerals { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + if (upToArabicNumer > DICTIONARY_PREPOPULATION_SIZE) { if (_simpleArabicNumeralMappings.Count >= upToArabicNumer) { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + var moreSimpleNumerals = GenerateAdditionalSimpleNumerals(DICTIONARY_PREPOPULATION_SIZE, upToArabicNumer); _simpleArabicNumeralMappings = - (Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>) - _simpleArabicNumeralMappings.Union(moreSimpleNumerals); + (Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>)_simpleArabicNumeralMappings.Union(moreSimpleNumerals); return take(_simpleArabicNumeralMappings, _arabicRomanNumeralsMapping.Count); } + if (upToArabicNumer < DICTIONARY_PREPOPULATION_SIZE) { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + return _simpleArabicNumeralMappings; } - private static Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> GenerateAdditionalSimpleNumerals(int offset, int length) { - Dictionary<SimpleArabicNumeral,SimpleRomanNumeral> moreNumerals = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); + Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> moreNumerals = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); foreach (int arabicNumeral in Enumerable.Range(offset, length)) { string romanNumeral; @@ -130,16 +134,10 @@ namespace NzbDrone.Core.Parser.RomanNumerals GenerateRomanNumerals(arabicNumeral, out romanNumeral, out arabicNumeralAsString); SimpleArabicNumeral san = new SimpleArabicNumeral(arabicNumeral); SimpleRomanNumeral srn = new SimpleRomanNumeral(romanNumeral); - moreNumerals.Add(san,srn); + moreNumerals.Add(san, srn); } + return moreNumerals; } - - - - - - - } } diff --git a/src/NzbDrone.Core/Parser/SceneChecker.cs b/src/NzbDrone.Core/Parser/SceneChecker.cs index ba292da44..9989b3ad9 100644 --- a/src/NzbDrone.Core/Parser/SceneChecker.cs +++ b/src/NzbDrone.Core/Parser/SceneChecker.cs @@ -1,4 +1,4 @@ -namespace NzbDrone.Core.Parser +namespace NzbDrone.Core.Parser { public static class SceneChecker { @@ -6,8 +6,15 @@ //It's better not to use a title that might be scene than to use one that isn't scene public static bool IsSceneTitle(string title) { - if (!title.Contains(".")) return false; - if (title.Contains(" ")) return false; + if (!title.Contains(".")) + { + return false; + } + + if (title.Contains(" ")) + { + return false; + } var parsedTitle = Parser.ParseMovieTitle(title, false); //We are not lenient when it comes to scene checking! diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs index 3766cfbba..d268fbb6c 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Profiles.Delay { public interface IDelayProfileRepository : IBasicRepository<DelayProfile> { - } public class DelayProfileRepository : BasicRepository<DelayProfile>, IDelayProfileRepository diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs index 85d2aa054..0179205d4 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs @@ -55,7 +55,10 @@ namespace NzbDrone.Core.Profiles.Delay for (int i = 0; i < all.Count; i++) { - if (all[i].Id == 1) continue; + if (all[i].Id == 1) + { + continue; + } all[i].Order = i + 1; } @@ -127,18 +130,15 @@ namespace NzbDrone.Core.Profiles.Delay { delayProfile.Order = afterOrder + 1; } - else if (delayProfile.Id == after?.Id) { delayProfile.Order = afterOrder; } - else if (delayProfile.Order > afterOrder) { delayProfile.Order = afterCount; afterCount++; } - else if (delayProfile.Order > movingOrder) { delayProfile.Order--; diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs index 4e7ad94fb..cfd08a2f4 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs @@ -17,14 +17,20 @@ namespace NzbDrone.Core.Profiles.Delay protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; var collection = context.PropertyValue as HashSet<int>; - if (collection == null || collection.Empty()) return true; + if (collection == null || collection.Empty()) + { + return true; + } return _delayProfileService.All().None(d => d.Id != instanceId && d.Tags.Intersect(collection).Any()); } diff --git a/src/NzbDrone.Core/Profiles/ProfileInUseException.cs b/src/NzbDrone.Core/Profiles/ProfileInUseException.cs index 5753ef0cc..6d2fef2c9 100644 --- a/src/NzbDrone.Core/Profiles/ProfileInUseException.cs +++ b/src/NzbDrone.Core/Profiles/ProfileInUseException.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Profiles public ProfileInUseException(int profileId) : base("Profile [{0}] is in use.", profileId) { - } } } diff --git a/src/NzbDrone.Core/Profiles/ProfileService.cs b/src/NzbDrone.Core/Profiles/ProfileService.cs index a541978d8..80be98574 100644 --- a/src/NzbDrone.Core/Profiles/ProfileService.cs +++ b/src/NzbDrone.Core/Profiles/ProfileService.cs @@ -2,12 +2,12 @@ using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Core.CustomFormats; +using NzbDrone.Core.Languages; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Profiles { @@ -32,8 +32,11 @@ namespace NzbDrone.Core.Profiles private readonly ICustomFormatService _formatService; private readonly Logger _logger; - public ProfileService(IProfileRepository profileRepository, IMovieService movieService, - INetImportFactory netImportFactory, ICustomFormatService formatService, Logger logger) + public ProfileService(IProfileRepository profileRepository, + IMovieService movieService, + INetImportFactory netImportFactory, + ICustomFormatService formatService, + Logger logger) { _profileRepository = profileRepository; _movieService = movieService; @@ -111,11 +114,15 @@ namespace NzbDrone.Core.Profiles { // Hack to force custom formats to be loaded into memory, if you have a better solution please let me know. _formatService.All(); - if (All().Any()) return; + if (All().Any()) + { + return; + } _logger.Info("Setting up default quality profiles"); - AddDefaultProfile("Any", Quality.Bluray480p, + AddDefaultProfile("Any", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -145,7 +152,8 @@ namespace NzbDrone.Core.Profiles Quality.Remux2160p, Quality.BRDISK); - AddDefaultProfile("SD", Quality.Bluray480p, + AddDefaultProfile("SD", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -159,27 +167,31 @@ namespace NzbDrone.Core.Profiles Quality.Bluray480p, Quality.Bluray576p); - AddDefaultProfile("HD-720p", Quality.Bluray720p, + AddDefaultProfile("HD-720p", + Quality.Bluray720p, Quality.HDTV720p, Quality.WEBDL720p, Quality.WEBRip720p, Quality.Bluray720p); - AddDefaultProfile("HD-1080p", Quality.Bluray1080p, + AddDefaultProfile("HD-1080p", + Quality.Bluray1080p, Quality.HDTV1080p, Quality.WEBDL1080p, Quality.WEBRip1080p, Quality.Bluray1080p, Quality.Remux1080p); - AddDefaultProfile("Ultra-HD", Quality.Remux2160p, + AddDefaultProfile("Ultra-HD", + Quality.Remux2160p, Quality.HDTV2160p, Quality.WEBDL2160p, Quality.WEBRip2160p, Quality.Bluray2160p, Quality.Remux2160p); - AddDefaultProfile("HD - 720p/1080p", Quality.Bluray720p, + AddDefaultProfile("HD - 720p/1080p", + Quality.Bluray720p, Quality.HDTV720p, Quality.HDTV1080p, Quality.WEBDL720p, @@ -189,8 +201,7 @@ namespace NzbDrone.Core.Profiles Quality.Bluray720p, Quality.Bluray1080p, Quality.Remux1080p, - Quality.Remux2160p - ); + Quality.Remux2160p); } public Profile GetDefaultProfile(string name, Quality cutoff = null, params Quality[] allowed) diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs index 9911c4722..fba9ca3f3 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs @@ -20,7 +20,9 @@ namespace NzbDrone.Core.ProgressMessaging public static bool LockReentrancy() { if (_reentrancyLock) + { return false; + } _reentrancyLock = true; return true; diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs index 60a863e38..37885c47d 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs @@ -1,5 +1,5 @@ -using NLog.Config; -using NLog; +using NLog; +using NLog.Config; using NLog.Targets; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; @@ -23,9 +23,16 @@ namespace NzbDrone.Core.ProgressMessaging { var command = ProgressMessageContext.CommandModel; - if (!IsClientMessage(logEvent, command)) return; + if (!IsClientMessage(logEvent, command)) + { + return; + } + + if (!ProgressMessageContext.LockReentrancy()) + { + return; + } - if (!ProgressMessageContext.LockReentrancy()) return; try { _commandQueueManager.SetMessage(command, logEvent.FormattedMessage); diff --git a/src/NzbDrone.Core/Qualities/Quality.cs b/src/NzbDrone.Core/Qualities/Quality.cs index ed0f34e81..a39d60a33 100644 --- a/src/NzbDrone.Core/Qualities/Quality.cs +++ b/src/NzbDrone.Core/Qualities/Quality.cs @@ -39,15 +39,30 @@ namespace NzbDrone.Core.Qualities public bool Equals(Quality other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Quality); } @@ -192,7 +207,6 @@ namespace NzbDrone.Core.Qualities #endif } - public static readonly List<Quality> All; public static readonly Quality[] AllLookup; @@ -201,12 +215,17 @@ namespace NzbDrone.Core.Qualities #endif public static Quality FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } var quality = AllLookup[id]; if (quality == null) + { throw new ArgumentException("ID does not match a known quality", "id"); + } return quality; } diff --git a/src/NzbDrone.Core/Qualities/QualityDefinition.cs b/src/NzbDrone.Core/Qualities/QualityDefinition.cs index abdb7831f..74fb21793 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinition.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinition.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Qualities public QualityDefinition() { - } public QualityDefinition(Quality quality) diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs index 49941710c..8663b6b4a 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs @@ -1,7 +1,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Qualities { public interface IQualityDefinitionRepository : IBasicRepository<QualityDefinition> diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs index 31924867c..166532ee5 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using System; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Qualities { @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Qualities public QualityDefinitionService(IQualityDefinitionRepository repo, ICacheManager cacheManager, Logger logger) { _repo = repo; - _cache = cacheManager.GetCache<Dictionary<Quality, QualityDefinition>>(this.GetType()); + _cache = cacheManager.GetCache<Dictionary<Quality, QualityDefinition>>(GetType()); _logger = logger; } @@ -78,7 +78,6 @@ namespace NzbDrone.Core.Qualities { insertList.Add(definition); } - else { updateList.Add(existing); diff --git a/src/NzbDrone.Core/Qualities/QualityModel.cs b/src/NzbDrone.Core/Qualities/QualityModel.cs index 2dc53cb73..b9ba426c3 100644 --- a/src/NzbDrone.Core/Qualities/QualityModel.cs +++ b/src/NzbDrone.Core/Qualities/QualityModel.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Qualities public List<CustomFormat> CustomFormats { get; set; } - public Revision Revision { get; set; } public string HardcodedSubs { get; set; } @@ -23,7 +22,6 @@ namespace NzbDrone.Core.Qualities public QualityModel() : this(Quality.Unknown, new Revision()) { - } public QualityModel(Quality quality, Revision revision = null, List<CustomFormat> customFormats = null) @@ -40,27 +38,42 @@ namespace NzbDrone.Core.Qualities public override int GetHashCode() { - unchecked // Overflow is fine, just wrap + // Overflow is fine, just wrap + unchecked { int hash = 17; - hash = hash * 23 + Revision.GetHashCode(); - hash = hash * 23 + Quality.GetHashCode(); + hash = (hash * 23) + Revision.GetHashCode(); + hash = (hash * 23) + Quality.GetHashCode(); return hash; } } public bool Equals(QualityModel other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } return other.Quality.Id.Equals(Quality.Id) && other.Revision.Equals(Revision); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as QualityModel); } diff --git a/src/NzbDrone.Core/Qualities/Revision.cs b/src/NzbDrone.Core/Qualities/Revision.cs index d9590db59..4847150ff 100644 --- a/src/NzbDrone.Core/Qualities/Revision.cs +++ b/src/NzbDrone.Core/Qualities/Revision.cs @@ -22,17 +22,35 @@ namespace NzbDrone.Core.Qualities public bool Equals(Revision other) { - if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(null, other)) + { + return false; + } return other.Version.Equals(Version) && other.Real.Equals(Real); } public int CompareTo(Revision other) { - if (Real > other.Real) return 1; - if (Real < other.Real) return -1; - if (Version > other.Version) return 1; - if (Version < other.Version) return -1; + if (Real > other.Real) + { + return 1; + } + + if (Real < other.Real) + { + return -1; + } + + if (Version > other.Version) + { + return 1; + } + + if (Version < other.Version) + { + return -1; + } return 0; } @@ -58,8 +76,15 @@ namespace NzbDrone.Core.Qualities public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Revision); } @@ -76,32 +101,60 @@ namespace NzbDrone.Core.Qualities public static bool operator >(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) > 0; } public static bool operator <(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) < 0; } public static bool operator >=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) >= 0; } public static bool operator <=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) <= 0; } diff --git a/src/NzbDrone.Core/Queue/Queue.cs b/src/NzbDrone.Core/Queue/Queue.cs index 95dd8f159..a5f7463e2 100644 --- a/src/NzbDrone.Core/Queue/Queue.cs +++ b/src/NzbDrone.Core/Queue/Queue.cs @@ -4,9 +4,9 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Queue { diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs index c4a0bf81a..1aa7f18a9 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs @@ -1,6 +1,5 @@ using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RemotePathMappings { public class RemotePathMapping : ModelBase diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs index bfdfc0000..dc2274362 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RemotePathMappings { public interface IRemotePathMappingRepository : IBasicRepository<RemotePathMapping> { - } public class RemotePathMappingRepository : BasicRepository<RemotePathMapping>, IRemotePathMappingRepository { - public RemotePathMappingRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs index 3167a4945..859bcbee4 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs @@ -1,11 +1,11 @@ -using System.Linq; -using System; +using System; using System.Collections.Generic; using System.IO; +using System.Linq; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; -using NzbDrone.Common.Cache; using NzbDrone.Core.Download; namespace NzbDrone.Core.RemotePathMappings diff --git a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs index c674fc51e..e5bcdfb3a 100644 --- a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs +++ b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.Rest { public JsonNetSerializer() { - ContentType = "application/json"; + ContentType = "application/json"; } public string Serialize(object obj) diff --git a/src/NzbDrone.Core/Rest/RestClientFactory.cs b/src/NzbDrone.Core/Rest/RestClientFactory.cs index 99a3d1060..bcce3b825 100644 --- a/src/NzbDrone.Core/Rest/RestClientFactory.cs +++ b/src/NzbDrone.Core/Rest/RestClientFactory.cs @@ -1,5 +1,5 @@ -using RestSharp; using NzbDrone.Common.EnvironmentInfo; +using RestSharp; namespace NzbDrone.Core.Rest { @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Rest UserAgent = $"{BuildInfo.AppName}/{BuildInfo.Version} ({OsInfo.Os})" }; - return restClient; } } diff --git a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs index c18e0256f..938b8723d 100644 --- a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs +++ b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs @@ -1,5 +1,5 @@ -using System.Net; -using System.Linq; +using System.Linq; +using System.Net; using NLog; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Instrumentation; @@ -38,14 +38,17 @@ namespace NzbDrone.Core.Rest { return response; } + case HttpStatusCode.NoContent: { return response; } + case HttpStatusCode.Created: { return response; } + default: { Logger.Warn("[{0}] [{1}] Failed. [{2}]", response.Request.Method, response.ResponseUri.ToString(), response.StatusCode); @@ -54,7 +57,8 @@ namespace NzbDrone.Core.Rest } } - public static T Read<T>(this IRestResponse restResponse, IRestClient restClient) where T : class, new() + public static T Read<T>(this IRestResponse restResponse, IRestClient restClient) + where T : class, new() { restResponse.ValidateResponse(restClient); @@ -66,7 +70,8 @@ namespace NzbDrone.Core.Rest return Json.Deserialize<T>(restResponse.Content); } - public static T ExecuteAndValidate<T>(this IRestClient client, IRestRequest request) where T : class, new() + public static T ExecuteAndValidate<T>(this IRestClient client, IRestRequest request) + where T : class, new() { return client.Execute(request).Read<T>(client); } @@ -85,7 +90,10 @@ namespace NzbDrone.Core.Rest { var header = response.Headers.FirstOrDefault(v => v.Name == key); - if (header == null) return null; + if (header == null) + { + return null; + } return header.Value; } diff --git a/src/NzbDrone.Core/Restrictions/TermMatcher.cs b/src/NzbDrone.Core/Restrictions/TermMatcher.cs index 0913f8bcc..ceb5d66a9 100644 --- a/src/NzbDrone.Core/Restrictions/TermMatcher.cs +++ b/src/NzbDrone.Core/Restrictions/TermMatcher.cs @@ -38,7 +38,6 @@ namespace NzbDrone.Core.Restrictions else { return new CaseInsensitiveTermMatcher(term).IsMatch; - } } diff --git a/src/NzbDrone.Core/RootFolders/RootFolder.cs b/src/NzbDrone.Core/RootFolders/RootFolder.cs index 0ae3b0155..7e6c5444b 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolder.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RootFolders { public class RootFolder : ModelBase diff --git a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs index f51376d28..21a1a5264 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RootFolders { public interface IRootFolderRepository : IBasicRepository<RootFolder> { - } public class RootFolderRepository : BasicRepository<RootFolder>, IRootFolderRepository { - public RootFolderRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { diff --git a/src/NzbDrone.Core/RootFolders/RootFolderService.cs b/src/NzbDrone.Core/RootFolders/RootFolderService.cs index a58ed182c..0e0c2ad71 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderService.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderService.cs @@ -1,7 +1,7 @@ -using System.Linq; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common; @@ -43,7 +43,6 @@ namespace NzbDrone.Core.RootFolders ".grab" }; - public RootFolderService(IRootFolderRepository rootFolderRepository, IDiskProvider diskProvider, IMovieRepository movieRepository, @@ -77,6 +76,7 @@ namespace NzbDrone.Core.RootFolders GetDetails(folder); } } + //We don't want an exception to prevent the root folders from loading in the UI, so they can still be deleted catch (Exception ex) { @@ -152,7 +152,6 @@ namespace NzbDrone.Core.RootFolders { results.Add(new UnmappedFolder { Name = di.Name, Path = di.FullName }); } - } var setToRemove = SpecialFolders; diff --git a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs index 37dc83ea9..c1ceeb3ec 100644 --- a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs +++ b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs @@ -55,7 +55,6 @@ namespace NzbDrone.Core.Security return true; } - _logger.Error("Certificate validation for {0} failed. {1}", request.Address, sslPolicyErrors); return false; @@ -65,7 +64,7 @@ namespace NzbDrone.Core.Security { if (IPAddress.TryParse(host, out var ipAddress)) { - return new []{ ipAddress }; + return new[] { ipAddress }; } return Dns.GetHostEntry(host).AddressList; diff --git a/src/NzbDrone.Core/Tags/TagDetails.cs b/src/NzbDrone.Core/Tags/TagDetails.cs index af60d6fb6..80ee15fa8 100644 --- a/src/NzbDrone.Core/Tags/TagDetails.cs +++ b/src/NzbDrone.Core/Tags/TagDetails.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Tags { get { - return (MovieIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any()); + return MovieIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any(); } } } diff --git a/src/NzbDrone.Core/Tags/TagService.cs b/src/NzbDrone.Core/Tags/TagService.cs index 814c2d1fe..73c4d3c6a 100644 --- a/src/NzbDrone.Core/Tags/TagService.cs +++ b/src/NzbDrone.Core/Tags/TagService.cs @@ -2,11 +2,11 @@ using System.Collections.Generic; using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport; using NzbDrone.Core.Notifications; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Restrictions; -using NzbDrone.Core.Movies; -using NzbDrone.Core.NetImport; namespace NzbDrone.Core.Tags { @@ -115,8 +115,7 @@ namespace NzbDrone.Core.Tags NotificationIds = notifications.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), RestrictionIds = restrictions.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), MovieIds = movies.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList() - } - ); + }); } return details; diff --git a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs index 47d6ecdf3..83e4013ea 100644 --- a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs +++ b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs @@ -8,6 +8,5 @@ namespace NzbDrone.Core.ThingiProvider : base("Couldn't find config contract " + contract) { } - } } diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs index 802ca114e..421cc6899 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs @@ -2,8 +2,9 @@ namespace NzbDrone.Core.ThingiProvider { - public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> where TProvider : ModelBase, new() + public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> + where TProvider : ModelBase, new() { -// void DeleteImplementations(string implementation); + // void DeleteImplementations(string implementation); } } diff --git a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs index 019b50ee6..305f80efb 100644 --- a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs @@ -12,9 +12,9 @@ namespace NzbDrone.Core.ThingiProvider { } -// public void DeleteImplementations(string implementation) -// { -// DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); -// } + // public void DeleteImplementations(string implementation) + // { + // DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); + // } } } diff --git a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs index ca40daa8c..071f0ea9f 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.ThingiProvider.Status public class ProviderStatusRepository<TModel> : BasicRepository<TModel>, IProviderStatusRepository<TModel> where TModel : ProviderStatusBase, new() - { public ProviderStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/TinyTwitter.cs b/src/NzbDrone.Core/TinyTwitter.cs index c6bf228b3..b1448d7e8 100644 --- a/src/NzbDrone.Core/TinyTwitter.cs +++ b/src/NzbDrone.Core/TinyTwitter.cs @@ -28,16 +28,16 @@ namespace TinyTwitter public class TinyTwitter { - private readonly OAuthInfo oauth; + private readonly OAuthInfo _oauth; public TinyTwitter(OAuthInfo oauth) { - this.oauth = oauth; + _oauth = oauth; } public void UpdateStatus(string message) { - new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") + new RequestBuilder(_oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") .AddParameter("status", message) .Execute(); } @@ -49,38 +49,35 @@ namespace TinyTwitter * and added this banner so it's not blindly updated. * **/ - public void DirectMessage(string message, string screenName) { - new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") + new RequestBuilder(_oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") .AddParameter("text", message) .AddParameter("screen_name", screenName) .Execute(); } - #region RequestBuilder - public class RequestBuilder { private const string VERSION = "1.0"; private const string SIGNATURE_METHOD = "HMAC-SHA1"; - private readonly OAuthInfo oauth; - private readonly string method; - private readonly IDictionary<string, string> customParameters; - private readonly string url; + private readonly OAuthInfo _oauth; + private readonly string _method; + private readonly IDictionary<string, string> _customParameters; + private readonly string _url; public RequestBuilder(OAuthInfo oauth, string method, string url) { - this.oauth = oauth; - this.method = method; - this.url = url; - customParameters = new Dictionary<string, string>(); + _oauth = oauth; + _method = method; + _url = url; + _customParameters = new Dictionary<string, string>(); } public RequestBuilder AddParameter(string name, string value) { - customParameters.Add(name, value.EncodeRFC3986()); + _customParameters.Add(name, value.EncodeRFC3986()); return this; } @@ -89,14 +86,14 @@ namespace TinyTwitter var timespan = GetTimestamp(); var nonce = CreateNonce(); - var parameters = new Dictionary<string, string>(customParameters); + var parameters = new Dictionary<string, string>(_customParameters); AddOAuthParameters(parameters, timespan, nonce); var signature = GenerateSignature(parameters); var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); - request.Method = method; + request.Method = _method; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Authorization", headerValue); @@ -106,7 +103,6 @@ namespace TinyTwitter // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions // after some requests. Abort the request seems to work. More info: // http://stackoverflow.com/questions/2252762/getrequeststream-throws-timeout-exception-randomly - var response = request.GetResponse(); string content; @@ -126,25 +122,31 @@ namespace TinyTwitter private void WriteRequestBody(HttpWebRequest request) { - if (method == "GET") + if (_method == "GET") + { return; + } var requestBody = Encoding.ASCII.GetBytes(GetCustomParametersString()); using (var stream = request.GetRequestStream()) + { stream.Write(requestBody, 0, requestBody.Length); + } } private string GetRequestUrl() { - if (method != "GET" || customParameters.Count == 0) - return url; + if (_method != "GET" || _customParameters.Count == 0) + { + return _url; + } - return string.Format("{0}?{1}", url, GetCustomParametersString()); + return string.Format("{0}?{1}", _url, GetCustomParametersString()); } private string GetCustomParametersString() { - return customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); + return _customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); } private string GenerateAuthorizationHeaderValue(IEnumerable<KeyValuePair<string, string>> parameters, string signature) @@ -160,15 +162,15 @@ namespace TinyTwitter private string GenerateSignature(IEnumerable<KeyValuePair<string, string>> parameters) { var dataToSign = new StringBuilder() - .Append(method).Append("&") - .Append(url.EncodeRFC3986()).Append("&") + .Append(_method).Append("&") + .Append(_url.EncodeRFC3986()).Append("&") .Append(parameters .OrderBy(x => x.Key) .Select(x => string.Format("{0}={1}", x.Key, x.Value)) .Join("&") .EncodeRFC3986()); - var signatureKey = string.Format("{0}&{1}", oauth.ConsumerSecret.EncodeRFC3986(), oauth.AccessSecret.EncodeRFC3986()); + var signatureKey = string.Format("{0}&{1}", _oauth.ConsumerSecret.EncodeRFC3986(), _oauth.AccessSecret.EncodeRFC3986()); var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString())); @@ -178,11 +180,11 @@ namespace TinyTwitter private void AddOAuthParameters(IDictionary<string, string> parameters, string timestamp, string nonce) { parameters.Add("oauth_version", VERSION); - parameters.Add("oauth_consumer_key", oauth.ConsumerKey); + parameters.Add("oauth_consumer_key", _oauth.ConsumerKey); parameters.Add("oauth_nonce", nonce); parameters.Add("oauth_signature_method", SIGNATURE_METHOD); parameters.Add("oauth_timestamp", timestamp); - parameters.Add("oauth_token", oauth.AccessToken); + parameters.Add("oauth_token", _oauth.AccessToken); } private static string GetTimestamp() @@ -195,8 +197,6 @@ namespace TinyTwitter return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); } } - - #endregion } public static class TinyTwitterHelperExtensions @@ -214,9 +214,10 @@ namespace TinyTwitter public static string EncodeRFC3986(this string value) { // From Twitterizer http://www.twitterizer.net/ - if (string.IsNullOrEmpty(value)) + { return string.Empty; + } var encoded = Uri.EscapeDataString(value); diff --git a/src/NzbDrone.Core/Update/InstallUpdateService.cs b/src/NzbDrone.Core/Update/InstallUpdateService.cs index 356295587..ea644e2c3 100644 --- a/src/NzbDrone.Core/Update/InstallUpdateService.cs +++ b/src/NzbDrone.Core/Update/InstallUpdateService.cs @@ -34,7 +34,6 @@ namespace NzbDrone.Core.Update private readonly IBackupService _backupService; private readonly IOsInfo _osInfo; - public InstallUpdateService(ICheckUpdateService checkUpdateService, IAppFolderInfo appFolderInfo, IDiskProvider diskProvider, @@ -54,6 +53,7 @@ namespace NzbDrone.Core.Update { throw new ArgumentNullException(nameof(configFileProvider)); } + _checkUpdateService = checkUpdateService; _appFolderInfo = appFolderInfo; _diskProvider = diskProvider; diff --git a/src/NzbDrone.Core/Update/UpdateCheckService.cs b/src/NzbDrone.Core/Update/UpdateCheckService.cs index fcce36d59..46e4b6b63 100644 --- a/src/NzbDrone.Core/Update/UpdateCheckService.cs +++ b/src/NzbDrone.Core/Update/UpdateCheckService.cs @@ -13,7 +13,6 @@ namespace NzbDrone.Core.Update private readonly IUpdatePackageProvider _updatePackageProvider; private readonly IConfigFileProvider _configFileProvider; - public CheckUpdateService(IUpdatePackageProvider updatePackageProvider, IConfigFileProvider configFileProvider) { diff --git a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs index e4d7ff22b..91c8eff34 100644 --- a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs +++ b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs @@ -48,7 +48,10 @@ namespace NzbDrone.Core.Update var update = _httpClient.Get<UpdatePackageAvailable>(request.Build()).Resource; - if (!update.Available) return null; + if (!update.Available) + { + return null; + } return update.UpdatePackage; } diff --git a/src/NzbDrone.Core/Validation/FolderValidator.cs b/src/NzbDrone.Core/Validation/FolderValidator.cs index c3fce0d93..9eedeb459 100644 --- a/src/NzbDrone.Core/Validation/FolderValidator.cs +++ b/src/NzbDrone.Core/Validation/FolderValidator.cs @@ -12,7 +12,11 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs index c8db4a84b..0cd3c9026 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs @@ -11,13 +11,11 @@ namespace NzbDrone.Core.Validation public NzbDroneValidationFailure(string propertyName, string error) : base(propertyName, error) { - } public NzbDroneValidationFailure(string propertyName, string error, object attemptedValue) : base(propertyName, error, attemptedValue) { - } public NzbDroneValidationFailure(ValidationFailure validationFailure) diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs index bd8263b6b..5de154984 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs @@ -31,6 +31,7 @@ namespace NzbDrone.Core.Validation { failure = new NzbDroneValidationFailure(failureBase); } + if (failure.IsWarning) { warnings.Add(failure); diff --git a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs index 6e86db105..c58b5a273 100644 --- a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs @@ -16,9 +16,12 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderWritable(context.PropertyValue.ToString())); + return _diskProvider.FolderWritable(context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs index 28a3192ab..48e3da21e 100644 --- a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs @@ -22,13 +22,27 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; - if (OsInfo.IsNotWindows) return true; - if (!_runtimeInfo.IsWindowsService) return true; + if (context.PropertyValue == null) + { + return false; + } + + if (OsInfo.IsNotWindows) + { + return true; + } + + if (!_runtimeInfo.IsWindowsService) + { + return true; + } var path = context.PropertyValue.ToString(); - if (!DriveRegex.IsMatch(path)) return true; + if (!DriveRegex.IsMatch(path)) + { + return true; + } var mount = _diskProvider.GetMount(path); diff --git a/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs b/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs index 91df0ffa3..ad8ccf7eb 100644 --- a/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs @@ -17,7 +17,10 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_movieService.GetAllMovies().Any(s => context.PropertyValue.ToString().IsParentPath(s.Path)); } diff --git a/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs index 5b4a7745e..656e10872 100644 --- a/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs @@ -15,11 +15,14 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } int tmdbId = (int)context.PropertyValue; - return (_movieService.FindByTmdbId(tmdbId) == null); + return _movieService.FindByTmdbId(tmdbId) == null; } } } diff --git a/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs b/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs index bbd871432..a86d180c7 100644 --- a/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs +++ b/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs @@ -16,12 +16,15 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; - return (!_moviesService.GetAllMovies().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId)); + return !_moviesService.GetAllMovies().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs index 970ecb9e5..77398b5e8 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs @@ -15,9 +15,12 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderExists(context.PropertyValue.ToString())); + return _diskProvider.FolderExists(context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs index 69dcb2cca..c546d3e79 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs @@ -21,7 +21,11 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } diff --git a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs index 7f3b03d4b..8494ac28b 100644 --- a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs @@ -16,9 +16,12 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString()))); + return !_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString())); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs index 9f9dbb722..158a9ca31 100644 --- a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Validation.Paths { private readonly IAppFolderInfo _appFolderInfo; - public StartupFolderValidator(IAppFolderInfo appFolderInfo) : base("Path cannot be an ancestor of the start up folder") { @@ -17,7 +16,10 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_appFolderInfo.StartUpFolder.IsParentPath(context.PropertyValue.ToString()); } diff --git a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs index 5ff2dc6f9..d1875ecea 100644 --- a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs @@ -15,7 +15,10 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return _profileService.Exists((int)context.PropertyValue); } diff --git a/src/NzbDrone.Core/Validation/UrlValidator.cs b/src/NzbDrone.Core/Validation/UrlValidator.cs index 9a278bc4d..844ab80f2 100644 --- a/src/NzbDrone.Core/Validation/UrlValidator.cs +++ b/src/NzbDrone.Core/Validation/UrlValidator.cs @@ -21,7 +21,11 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsValidUrl(); } } diff --git a/src/NzbDrone.Host.Test/ContainerFixture.cs b/src/NzbDrone.Host.Test/ContainerFixture.cs index 1f1307ef6..8a7f8e021 100644 --- a/src/NzbDrone.Host.Test/ContainerFixture.cs +++ b/src/NzbDrone.Host.Test/ContainerFixture.cs @@ -1,22 +1,22 @@ using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common; +using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Download; +using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; using NzbDrone.Core.Jobs; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using Radarr.Host; -using NzbDrone.Test.Common; -using FluentAssertions; -using System.Linq; -using NzbDrone.Common.Composition; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.SignalR; -using Moq; +using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { diff --git a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs index 5ec9161b7..992c81938 100644 --- a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs +++ b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs @@ -3,8 +3,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Model; using NzbDrone.Common.Processes; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { @@ -35,7 +35,7 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(It.Is<string>(f => f.Contains("Radarr")))) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Subject.PreventStartIfAlreadyRunning(); @@ -50,8 +50,8 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(ProcessProvider.RADARR_CONSOLE_PROCESS_NAME)) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = 10}, - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = 10 }, + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Assert.Throws<TerminateApplicationException>(() => Subject.PreventStartIfAlreadyRunning()); @@ -66,9 +66,8 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(ProcessProvider.RADARR_PROCESS_NAME)) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID}, - new ProcessInfo {Id = 10} - + new ProcessInfo { Id = CURRENT_PROCESS_ID }, + new ProcessInfo { Id = 10 } }); Assert.Throws<TerminateApplicationException>(() => Subject.PreventStartIfAlreadyRunning()); diff --git a/src/NzbDrone.Host.Test/RouterTest.cs b/src/NzbDrone.Host.Test/RouterTest.cs index 9c570a5f3..fc6446707 100644 --- a/src/NzbDrone.Host.Test/RouterTest.cs +++ b/src/NzbDrone.Host.Test/RouterTest.cs @@ -4,8 +4,8 @@ using NUnit.Framework; using NzbDrone.Common; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Processes; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { @@ -18,7 +18,6 @@ namespace NzbDrone.App.Test WindowsOnly(); } - [Test] public void Route_should_call_install_service_when_application_mode_is_install() { @@ -36,7 +35,6 @@ namespace NzbDrone.App.Test serviceProviderMock.Verify(c => c.Install(ServiceProvider.SERVICE_NAME), Times.Once()); } - [Test] public void Route_should_call_uninstall_service_when_application_mode_is_uninstall() { @@ -77,7 +75,6 @@ namespace NzbDrone.App.Test serviceProvider.Verify(c => c.Run(It.IsAny<ServiceBase>()), Times.Once()); } - [Test] public void show_error_on_install_if_service_already_exist() { @@ -89,7 +86,6 @@ namespace NzbDrone.App.Test serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(true); Subject.Route(ApplicationModes.InstallService); - } [Test] @@ -103,7 +99,6 @@ namespace NzbDrone.App.Test serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(false); Subject.Route(ApplicationModes.UninstallService); - } } } diff --git a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs index a31c6ec59..232babb72 100644 --- a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs +++ b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs @@ -58,6 +58,7 @@ namespace Radarr.Host.AccessControl { _logger.Warn(ex, "Failed to check for open port in firewall"); } + return false; } @@ -87,7 +88,10 @@ namespace Radarr.Host.AccessControl private bool IsFirewallEnabled() { - if (OsInfo.IsNotWindows) return false; + if (OsInfo.IsNotWindows) + { + return false; + } try { diff --git a/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs b/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs index be7917f90..aad1f9b77 100644 --- a/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs +++ b/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs @@ -5,19 +5,23 @@ namespace Radarr.Host.AccessControl { public class RemoteAccessException : NzbDroneException { - public RemoteAccessException(string message, params object[] args) : base(message, args) + public RemoteAccessException(string message, params object[] args) + : base(message, args) { } - public RemoteAccessException(string message) : base(message) + public RemoteAccessException(string message) + : base(message) { } - public RemoteAccessException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public RemoteAccessException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public RemoteAccessException(string message, Exception innerException) : base(message, innerException) + public RemoteAccessException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Host/ApplicationServer.cs b/src/NzbDrone.Host/ApplicationServer.cs index e4cad8251..2e1bdf961 100644 --- a/src/NzbDrone.Host/ApplicationServer.cs +++ b/src/NzbDrone.Host/ApplicationServer.cs @@ -62,8 +62,8 @@ namespace Radarr.Host private readonly IBrowserService _browserService; private readonly IContainer _container; private readonly Logger _logger; - // private CancelHandler _cancelHandler; + // private CancelHandler _cancelHandler; public NzbDroneConsoleFactory(IConfigFileProvider configFileProvider, IHostController hostController, IRuntimeInfo runtimeInfo, @@ -99,7 +99,6 @@ namespace Radarr.Host _browserService.LaunchWebUI(); } - _container.Resolve<IEventAggregator>().PublishEvent(new ApplicationStartedEvent()); } diff --git a/src/NzbDrone.Host/Bootstrap.cs b/src/NzbDrone.Host/Bootstrap.cs index d4181f150..f0a7f473a 100644 --- a/src/NzbDrone.Host/Bootstrap.cs +++ b/src/NzbDrone.Host/Bootstrap.cs @@ -14,8 +14,8 @@ namespace Radarr.Host { public static class Bootstrap { - private static IContainer _container; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(Bootstrap)); + private static IContainer _container; public static void Start(StartupContext startupContext, IUserAlert userAlert, Action<IContainer> startCallback = null) { @@ -120,7 +120,6 @@ namespace Radarr.Host return ApplicationModes.RegisterUrl; } - if (OsInfo.IsWindows && startupContext.InstallService) { return ApplicationModes.InstallService; @@ -150,6 +149,7 @@ namespace Radarr.Host { return true; } + default: { return false; diff --git a/src/NzbDrone.Host/CancelHandler.cs b/src/NzbDrone.Host/CancelHandler.cs index 7aa785b6d..ad7a3f328 100644 --- a/src/NzbDrone.Host/CancelHandler.cs +++ b/src/NzbDrone.Host/CancelHandler.cs @@ -9,11 +9,11 @@ namespace Radarr.Host void Attach(); } - class CancelHandler : ICancelHandler + internal class CancelHandler : ICancelHandler { + private readonly ILifecycleService _lifecycleService; private object _syncRoot; private volatile bool _cancelInitiated; - private readonly ILifecycleService _lifecycleService; public CancelHandler(ILifecycleService lifecycleService) { @@ -52,6 +52,7 @@ namespace Radarr.Host private void GracefulShutdown() { Console.WriteLine("Shutdown requested, press Ctrl+C again to terminate directly."); + // TODO: Sent ApplicationShutdownRequested event or something like it. _lifecycleService.Shutdown(); } @@ -59,6 +60,7 @@ namespace Radarr.Host private void UngracefulShutdown() { Console.WriteLine("Termination requested."); + // TODO: Kill it. Shutdown NLog and invoke Environment.Exit. LogManager.Configuration = null; Environment.Exit(0); diff --git a/src/NzbDrone.Host/MainAppContainerBuilder.cs b/src/NzbDrone.Host/MainAppContainerBuilder.cs index 96307356f..8092854fe 100644 --- a/src/NzbDrone.Host/MainAppContainerBuilder.cs +++ b/src/NzbDrone.Host/MainAppContainerBuilder.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using Nancy.Bootstrapper; -using Radarr.Http; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.SignalR; +using Radarr.Http; namespace Radarr.Host { diff --git a/src/NzbDrone.Host/PlatformValidation.cs b/src/NzbDrone.Host/PlatformValidation.cs index 20662d6ec..d1ec5522f 100644 --- a/src/NzbDrone.Host/PlatformValidation.cs +++ b/src/NzbDrone.Host/PlatformValidation.cs @@ -9,10 +9,10 @@ namespace Radarr.Host { public static class PlatformValidation { - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); - private const string DOWNLOAD_LINK = "http://www.microsoft.com/en-us/download/details.aspx?id=42643"; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); + public static bool IsValidate(IUserAlert userAlert) { if (OsInfo.IsNotWindows) @@ -39,7 +39,6 @@ namespace Radarr.Host return true; } - private static bool IsAssemblyAvailable(string assemblyString) { try @@ -52,7 +51,6 @@ namespace Radarr.Host Logger.Warn("Couldn't load {0}", e.Message); return false; } - } } } diff --git a/src/NzbDrone.Host/Router.cs b/src/NzbDrone.Host/Router.cs index 1ed08de23..e56b92ab3 100644 --- a/src/NzbDrone.Host/Router.cs +++ b/src/NzbDrone.Host/Router.cs @@ -5,7 +5,6 @@ using NzbDrone.Common.Processes; using Radarr.Host.AccessControl; using IServiceProvider = NzbDrone.Common.IServiceProvider; - namespace Radarr.Host { public class Router @@ -57,6 +56,7 @@ namespace Radarr.Host _nzbDroneConsoleFactory.Start(); break; } + case ApplicationModes.InstallService: { _logger.Debug("Install Service selected"); @@ -74,8 +74,10 @@ namespace Radarr.Host // Ensures that there isn't an instance of Radarr already running that the service account cannot stop. _processProvider.SpawnNewProcess("sc.exe", $"start {ServiceProvider.SERVICE_NAME}", null, true); } + break; } + case ApplicationModes.UninstallService: { _logger.Debug("Uninstall Service selected"); @@ -90,6 +92,7 @@ namespace Radarr.Host break; } + case ApplicationModes.RegisterUrl: { _logger.Debug("Regiser URL selected"); @@ -97,6 +100,7 @@ namespace Radarr.Host break; } + default: { _consoleService.PrintHelp(); diff --git a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs index 326f358d7..01de0cb6d 100644 --- a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs +++ b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs @@ -68,10 +68,10 @@ namespace Radarr.Host.Middleware x.MapHub<MessageHub>("/signalr/messages"); }); #endif + // This is a side effect of haing multiple IoC containers, TinyIoC and whatever // Kestrel/SignalR is using. Ideally we'd have one IoC container, but that's non-trivial with TinyIoC // TODO: Use a single IoC container if supported for TinyIoC or if we switch to another system (ie Autofac). - var hubContext = appBuilder.ApplicationServices.GetService<IHubContext<MessageHub>>(); _container.Register(hubContext); } diff --git a/src/NzbDrone.Host/WebHost/WebHostController.cs b/src/NzbDrone.Host/WebHost/WebHostController.cs index 2ad8f7691..69ffa4e78 100644 --- a/src/NzbDrone.Host/WebHost/WebHostController.cs +++ b/src/NzbDrone.Host/WebHost/WebHostController.cs @@ -92,14 +92,17 @@ namespace Radarr.Host services .AddSignalR() #if !NETCOREAPP - .AddJsonProtocol( + .AddJsonProtocol(options => + { + options.PayloadSerializerSettings = Json.GetSerializerSettings(); + }); #else - .AddNewtonsoftJsonProtocol( + .AddNewtonsoftJsonProtocol(options => + { + options.PayloadSerializerSettings = Json.GetSerializerSettings(); + }); #endif - options => - { - options.PayloadSerializerSettings = Json.GetSerializerSettings(); - }); + }) .Configure(app => { diff --git a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs index 1a8815e0c..5f3a180c1 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs @@ -1,10 +1,10 @@ -using FluentAssertions; -using NUnit.Framework; -using Radarr.Api.V3.Movies; -using NzbDrone.Integration.Test.Client; using System; using System.Collections.Generic; using System.Linq; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Integration.Test.Client; +using Radarr.Api.V3.Movies; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs index 1fd49f6a6..3eabc8b79 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using Radarr.Api.V3.DiskSpace; using NzbDrone.Integration.Test.Client; +using Radarr.Api.V3.DiskSpace; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs index 6f0bd9b44..25b512a92 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs @@ -7,8 +7,8 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class DownloadClientFixture : IntegrationTest { - - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_name_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -24,7 +24,8 @@ namespace NzbDrone.Integration.Test.ApiTests DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_nzbfolder_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -40,7 +41,8 @@ namespace NzbDrone.Integration.Test.ApiTests DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_watchfolder_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -56,7 +58,8 @@ namespace NzbDrone.Integration.Test.ApiTests DownloadClients.InvalidPost(schema); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_downloadclient() { EnsureNoDownloadClient(); @@ -73,7 +76,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Enable.Should().BeTrue(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_downloadclients() { EnsureDownloadClient(); @@ -83,7 +87,8 @@ namespace NzbDrone.Integration.Test.ApiTests clients.Should().NotBeNullOrEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_downloadclient_by_id() { var client = EnsureDownloadClient(); @@ -101,7 +106,8 @@ namespace NzbDrone.Integration.Test.ApiTests var result = DownloadClients.InvalidGet(1000000); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_downloadclient() { EnsureNoDownloadClient(); @@ -113,7 +119,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Should().NotBeNull(); } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_downloadclient() { var client = EnsureDownloadClient(); diff --git a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs index 3d2f47028..146e6f9e5 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs @@ -1,14 +1,14 @@ -using FluentAssertions; -using NUnit.Framework; +using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Net; +using System.Reflection; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common; +using NzbDrone.Common.Disk; using NzbDrone.Integration.Test.Client; using RestSharp; -using System.Net; -using NzbDrone.Common.Disk; -using System.Reflection; -using System.IO; -using System.Collections.Generic; -using NzbDrone.Common; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs index 35bb62397..ab8e1eb0d 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs @@ -1,8 +1,8 @@ +using System.Linq; using FluentAssertions; using NUnit.Framework; -using System.Linq; -using Radarr.Api.V3.Movies; using NzbDrone.Test.Common; +using Radarr.Api.V3.Movies; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs index 6616c0931..dca15687c 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs @@ -1,15 +1,16 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; using FluentAssertions; using NUnit.Framework; -using System.Linq; -using System.IO; -using System.Collections.Generic; namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] public class MovieFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_with_tags_should_store_them() { EnsureNoMovie(680, "Pulp Fiction"); @@ -28,7 +29,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Tags.Should().Equal(tag.Id); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_without_profileid_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -42,7 +44,8 @@ namespace NzbDrone.Integration.Test.ApiTests Movies.InvalidPost(movie); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_without_path_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -56,7 +59,8 @@ namespace NzbDrone.Integration.Test.ApiTests Movies.InvalidPost(movie); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_movie() { EnsureNoMovie(680, "Pulp Fiction"); @@ -74,8 +78,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Path.Should().Be(Path.Combine(MovieRootFolder, movie.Title)); } - - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_movies() { EnsureMovie(680, "Pulp Fiction"); @@ -86,7 +90,8 @@ namespace NzbDrone.Integration.Test.ApiTests Movies.All().Should().Contain(v => v.ImdbId == "tt0468569"); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_movie_by_id() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -104,7 +109,8 @@ namespace NzbDrone.Integration.Test.ApiTests var result = Movies.InvalidGet(1000000); } - [Test, Order(2)] + [Test] + [Order(2)] public void update_movie_profile_id() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -122,7 +128,8 @@ namespace NzbDrone.Integration.Test.ApiTests Movies.Get(movie.Id).QualityProfileId.Should().Be(profileId); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_movie_monitored() { var movie = EnsureMovie(680, "Pulp Fiction", false); @@ -136,7 +143,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Monitored.Should().BeTrue(); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_movie_tags() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -158,7 +166,8 @@ namespace NzbDrone.Integration.Test.ApiTests } } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_movie() { var movie = EnsureMovie(680, "Pulp Fiction"); diff --git a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs index 96cc07f52..e8f7bd3c6 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class NamingConfigFixture : IntegrationTest { - [Test] public void should_be_able_to_get() { @@ -31,7 +30,6 @@ namespace NzbDrone.Integration.Test.ApiTests var result = NamingConfig.Put(config); result.RenameMovies.Should().BeFalse(); result.StandardMovieFormat.Should().Be(config.StandardMovieFormat); - } [Test] diff --git a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs index fe3dd538f..fec812487 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs @@ -3,7 +3,6 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; - namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] diff --git a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs index 199ad94d1..d0aedb2c9 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs @@ -1,8 +1,8 @@ +using System.Linq; +using System.Net; using FluentAssertions; using NUnit.Framework; using Radarr.Api.V3.Indexers; -using System.Linq; -using System.Net; namespace NzbDrone.Integration.Test.ApiTests { @@ -38,7 +38,6 @@ namespace NzbDrone.Integration.Test.ApiTests // TODO: Maybe we should create a full mock Newznab server endpoint. //var result = Releases.Post(new ReleaseResource { Guid = releases.First().Guid }); //result.Guid.Should().Be(releases.First().Guid); - var result = Releases.Post(new ReleaseResource { Guid = releases.First().Guid }, HttpStatusCode.InternalServerError); } @@ -49,10 +48,10 @@ namespace NzbDrone.Integration.Test.ApiTests releaseResource.Title.Should().NotBeNullOrWhiteSpace(); releaseResource.DownloadUrl.Should().NotBeNullOrWhiteSpace(); releaseResource.MovieTitle.Should().NotBeNullOrWhiteSpace(); + //TODO: uncomment these after moving to restsharp for rss //releaseResource.NzbInfoUrl.Should().NotBeNullOrWhiteSpace(); //releaseResource.Size.Should().BeGreaterThan(0); - return true; } } diff --git a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs index 7d0db2368..bf2072aa6 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs @@ -32,12 +32,10 @@ namespace NzbDrone.Integration.Test.ApiTests RootFolders.All().Should().OnlyContain(c => c.Id == postResponse.Id); - RootFolders.Delete(postResponse.Id); RootFolders.All().Should().BeEmpty(); - SignalRMessages.Should().Contain(c => c.Name == "rootfolder"); } diff --git a/src/NzbDrone.Integration.Test/Client/ClientBase.cs b/src/NzbDrone.Integration.Test/Client/ClientBase.cs index 861f36ff8..3695b27e1 100644 --- a/src/NzbDrone.Integration.Test/Client/ClientBase.cs +++ b/src/NzbDrone.Integration.Test/Client/ClientBase.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; +using System.Linq; using System.Net; using FluentAssertions; using NLog; -using Radarr.Http.REST; -using Radarr.Http; using NzbDrone.Common.Serializer; +using Radarr.Http; +using Radarr.Http.REST; using RestSharp; -using System.Linq; namespace NzbDrone.Integration.Test.Client { @@ -60,7 +60,8 @@ namespace NzbDrone.Integration.Test.Client return response.Content; } - public T Execute<T>(IRestRequest request, HttpStatusCode statusCode) where T : class, new() + public T Execute<T>(IRestRequest request, HttpStatusCode statusCode) + where T : class, new() { var content = Execute(request, statusCode); @@ -83,7 +84,6 @@ namespace NzbDrone.Integration.Test.Client public ClientBase(IRestClient restClient, string apiKey, string resource = null) : base(restClient, apiKey, resource ?? new TResource().ResourceName) { - } public List<TResource> All() @@ -161,19 +161,22 @@ namespace NzbDrone.Integration.Test.Client return Put<object>(request, statusCode); } - public T Get<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.OK) where T : class, new() + public T Get<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.OK) + where T : class, new() { request.Method = Method.GET; return Execute<T>(request, statusCode); } - public T Post<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Created) where T : class, new() + public T Post<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Created) + where T : class, new() { request.Method = Method.POST; return Execute<T>(request, statusCode); } - public T Put<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Accepted) where T : class, new() + public T Put<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Accepted) + where T : class, new() { request.Method = Method.PUT; return Execute<T>(request, statusCode); diff --git a/src/NzbDrone.Integration.Test/Client/CommandClient.cs b/src/NzbDrone.Integration.Test/Client/CommandClient.cs index 7b96ae63c..eee3c7fd7 100644 --- a/src/NzbDrone.Integration.Test/Client/CommandClient.cs +++ b/src/NzbDrone.Integration.Test/Client/CommandClient.cs @@ -1,12 +1,12 @@ -using RestSharp; -using NzbDrone.Core.Messaging.Commands; -using FluentAssertions; -using System.Threading; -using NUnit.Framework; +using System; using System.Linq; -using System; -using Radarr.Http.REST; +using System.Threading; +using FluentAssertions; using Newtonsoft.Json; +using NUnit.Framework; +using NzbDrone.Core.Messaging.Commands; +using Radarr.Http.REST; +using RestSharp; namespace NzbDrone.Integration.Test.Client { @@ -27,7 +27,10 @@ namespace NzbDrone.Integration.Test.Client [JsonIgnore] public Command Body { get; set; } [JsonProperty("body")] - public Command BodyReadOnly { get { return Body; } } + public Command BodyReadOnly + { + get { return Body; } + } } public class CommandClient : ClientBase<SimpleCommandResource> @@ -37,7 +40,8 @@ namespace NzbDrone.Integration.Test.Client { } - public SimpleCommandResource PostAndWait<T>(T command) where T : Command, new() + public SimpleCommandResource PostAndWait<T>(T command) + where T : Command, new() { var request = BuildRequest(); request.AddJsonBody(command); diff --git a/src/NzbDrone.Integration.Test/Client/MovieClient.cs b/src/NzbDrone.Integration.Test/Client/MovieClient.cs index 52b508fca..87f10925c 100644 --- a/src/NzbDrone.Integration.Test/Client/MovieClient.cs +++ b/src/NzbDrone.Integration.Test/Client/MovieClient.cs @@ -31,7 +31,6 @@ namespace NzbDrone.Integration.Test.Client var request = BuildRequest(slug); return Get<MovieResource>(request, statusCode); } - } public class SystemInfoClient : ClientBase<MovieResource> diff --git a/src/NzbDrone.Integration.Test/GenericApiFixture.cs b/src/NzbDrone.Integration.Test/GenericApiFixture.cs index 52472dd5a..63c6e9dbc 100644 --- a/src/NzbDrone.Integration.Test/GenericApiFixture.cs +++ b/src/NzbDrone.Integration.Test/GenericApiFixture.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Integration.Test [TestCase("")] public void should_get_json_with_accept_header(string header) { - var request = new RestRequest("system/status") { RequestFormat = DataFormat.None diff --git a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs index b931620ca..8bd1a26fc 100644 --- a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs +++ b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs @@ -13,6 +13,5 @@ namespace NzbDrone.Integration.Test var text = new WebClient().DownloadString(RootUrl); text.Should().NotBeNullOrWhiteSpace(); } - } } diff --git a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs index 7da8593bb..3a9f92427 100644 --- a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs +++ b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs @@ -4,29 +4,29 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; +using Microsoft.AspNetCore.SignalR.Client; using NLog; using NLog.Config; using NLog.Targets; using NUnit.Framework; -using Radarr.Api.V3.Blacklist; -using Radarr.Api.V3.Config; -using Radarr.Api.V3.DownloadClient; -using Radarr.Api.V3.MovieFiles; -using Radarr.Api.V3.History; -using Radarr.Api.V3.Profiles.Quality; -using Radarr.Api.V3.RootFolders; -using Radarr.Api.V3.Movies; -using Radarr.Api.V3.Tags; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Qualities; using NzbDrone.Integration.Test.Client; using NzbDrone.SignalR; using NzbDrone.Test.Common.Categories; +using Radarr.Api.V3.Blacklist; +using Radarr.Api.V3.Config; +using Radarr.Api.V3.DownloadClient; +using Radarr.Api.V3.History; +using Radarr.Api.V3.MovieFiles; +using Radarr.Api.V3.Movies; +using Radarr.Api.V3.Profiles.Quality; +using Radarr.Api.V3.RootFolders; +using Radarr.Api.V3.Tags; using RestSharp; -using System.Threading.Tasks; -using Microsoft.AspNetCore.SignalR.Client; namespace NzbDrone.Integration.Test { @@ -134,7 +134,6 @@ namespace NzbDrone.Integration.Test { if (_signalrConnection != null) { - await _signalrConnection.StopAsync(); _signalrConnection = null; @@ -183,7 +182,6 @@ namespace NzbDrone.Integration.Test _signalRReceived = new List<SignalRMessage>(); _signalrConnection = new HubConnectionBuilder().WithUrl("http://localhost:7878/signalr/messages").Build(); - var cts = new CancellationTokenSource(); _signalrConnection.Closed += e => @@ -206,7 +204,7 @@ namespace NzbDrone.Integration.Test { Console.WriteLine("Connecting to signalR"); - await _signalrConnection.StartAsync(); + await _signalrConnection.StartAsync(); connected = true; break; } @@ -229,13 +227,17 @@ namespace NzbDrone.Integration.Test for (var i = 0; i < count; i++) { if (predicate()) + { return; + } Thread.Sleep(interval); } if (predicate()) + { return; + } Assert.Fail("Timed on wait"); } diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs index 17b513343..65c126403 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs @@ -13,7 +13,7 @@ using NzbDrone.Mono.Disk; namespace NzbDrone.Mono.Test.DiskProviderTests { [TestFixture] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public class DiskProviderFixture : DiskProviderFixtureBase<DiskProvider> { public DiskProviderFixture() @@ -29,7 +29,6 @@ namespace NzbDrone.Mono.Test.DiskProviderTests } // Remove Write permissions, we're still owner so we can clean it up, but we'll have to do that explicitly. - var entry = UnixFileSystemInfo.GetFileSystemEntry(path); if (writable) @@ -100,7 +99,8 @@ namespace NzbDrone.Mono.Test.DiskProviderTests Mocker.GetMock<IProcMountProvider>() .Setup(v => v.GetMounts()) - .Returns(new List<IMount> { + .Returns(new List<IMount> + { new ProcMount(DriveType.Fixed, rootDir, rootDir, "myfs", new MountOptions(new Dictionary<string, string>())) }); } diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs index 904693e11..619194cdd 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs @@ -5,7 +5,7 @@ using NzbDrone.Mono.Disk; namespace NzbDrone.Mono.Test.DiskProviderTests { [TestFixture] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public class FreeSpaceFixture : FreeSpaceFixtureBase<DiskProvider> { public FreeSpaceFixture() diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs index ab191f390..f0dbe0a85 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs @@ -38,7 +38,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters versionName.FullName.Should().Be("macOS " + versionString); } - [TestCase] public void should_detect_server() { diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs index 079586551..73726a18e 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs @@ -37,7 +37,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters Subject.Read().Should().BeNull(); } - [Test] public void should_return_null_if_release_file_doestn_exist() { @@ -76,7 +75,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters version.Name.Should().Be("ubuntu"); version.Version.Should().Be("14.04"); version.FullName.Should().Be("Ubuntu 14.04.5 LTS"); - } } } diff --git a/src/NzbDrone.Mono/Disk/DiskProvider.cs b/src/NzbDrone.Mono/Disk/DiskProvider.cs index cb2329db4..ca60c400f 100644 --- a/src/NzbDrone.Mono/Disk/DiskProvider.cs +++ b/src/NzbDrone.Mono/Disk/DiskProvider.cs @@ -14,15 +14,15 @@ namespace NzbDrone.Mono.Disk { public class DiskProvider : DiskProviderBase { + // Mono supports sending -1 for a uint to indicate that the owner or group should not be set + // `unchecked((uint)-1)` and `uint.MaxValue` are the same thing. + private const uint UNCHANGED_ID = uint.MaxValue; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProvider)); private readonly IProcMountProvider _procMountProvider; private readonly ISymbolicLinkResolver _symLinkResolver; - // Mono supports sending -1 for a uint to indicate that the owner or group should not be set - // `unchecked((uint)-1)` and `uint.MaxValue` are the same thing. - private const uint UNCHANGED_ID = uint.MaxValue; - public DiskProvider(IProcMountProvider procMountProvider, ISymbolicLinkResolver symLinkResolver) { _procMountProvider = procMountProvider; @@ -197,7 +197,10 @@ namespace NzbDrone.Mono.Disk { var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(source); - if (fileInfo.IsSymbolicLink) return false; + if (fileInfo.IsSymbolicLink) + { + return false; + } fileInfo.CreateLink(destination); return true; diff --git a/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs b/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs index 964eb3a08..488623093 100644 --- a/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs +++ b/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Mono.Disk { public class LinuxPermissionsException : NzbDroneException { - public LinuxPermissionsException(string message, params object[] args) : base(message, args) + public LinuxPermissionsException(string message, params object[] args) + : base(message, args) { } - public LinuxPermissionsException(string message) : base(message) + public LinuxPermissionsException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs index 88e834d8a..f95f2a88c 100644 --- a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs +++ b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs @@ -16,17 +16,17 @@ namespace NzbDrone.Mono.Disk public class ProcMountProvider : IProcMountProvider { - private static string[] _fixedTypes = new [] { "ext3", "ext2", "ext4", "vfat", "fuseblk", "xfs", "jfs", "msdos", "ntfs", "minix", "hfs", "hfsplus", "qnx4", "ufs", "btrfs" }; - private static string[] _networkDriveTypes = new [] { "cifs", "nfs", "nfs4", "nfsd", "sshfs" }; - private static readonly Regex OctalRegex = new Regex(@"\\\d{3}", RegexOptions.Compiled); - private const string PROC_MOUNTS_FILENAME = @"/proc/mounts"; private const string PROC_FILESYSTEMS_FILENAME = @"/proc/filesystems"; - private static Dictionary<string, bool> _fileSystems; - + private static readonly Regex OctalRegex = new Regex(@"\\\d{3}", RegexOptions.Compiled); private readonly Logger _logger; + private static string[] _fixedTypes = new[] { "ext3", "ext2", "ext4", "vfat", "fuseblk", "xfs", "jfs", "msdos", "ntfs", "minix", "hfs", "hfsplus", "qnx4", "ufs", "btrfs" }; + private static string[] _networkDriveTypes = new[] { "cifs", "nfs", "nfs4", "nfsd", "sshfs" }; + + private static Dictionary<string, bool> _fileSystems; + public ProcMountProvider(Logger logger) { _logger = logger; diff --git a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs index 91aec48c3..829197522 100644 --- a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs +++ b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs @@ -24,7 +24,10 @@ namespace NzbDrone.Mono.Disk public string GetCompleteRealPath(string path) { - if (path == null) return null; + if (path == null) + { + return null; + } try { @@ -39,6 +42,7 @@ namespace NzbDrone.Mono.Disk dir += dirs[0]; realPath.Append(GetRealPath(dir)); } + for (var i = 1; i < lastIndex; ++i) { realPath.Append("/").Append(dirs[i]); @@ -46,6 +50,7 @@ namespace NzbDrone.Mono.Disk realPath.Remove(0, realPath.Length); realPath.Append(realSubPath); } + return realPath.ToString(); } catch (Exception ex) @@ -55,7 +60,6 @@ namespace NzbDrone.Mono.Disk } } - private static void GetPathComponents(string path, out string[] components, out int lastIndex) { var dirs = path.Split(UnixPath.DirectorySeparatorChar); @@ -83,6 +87,7 @@ namespace NzbDrone.Mono.Disk dirs[target++] = dirs[i]; } } + components = dirs; lastIndex = target; } @@ -113,8 +118,8 @@ namespace NzbDrone.Mono.Disk path = UnixPath.GetDirectoryName(path) + UnixPath.DirectorySeparatorChar + link; path = UnixPath.GetCanonicalPath(path); } - } while (true); + } + while (true); } - } } diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs index 321a8c12e..2965f5a1a 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs @@ -30,7 +30,6 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var fileContent = _diskProvider.ReadAllText(issueFile); - // Ubuntu 14.04.5 LTS \n \l // Ubuntu 16.04.1 LTS \n \l diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs index c9521588e..175219d61 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs @@ -9,13 +9,10 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters { public class MacOsVersionAdapter : IOsVersionAdapter { - private static readonly Regex DarwinVersionRegex = new Regex("<string>(?<version>10\\.\\d{1,2}\\.?\\d{0,2}?)<\\/string>", - RegexOptions.Compiled | - RegexOptions.IgnoreCase - ); - private const string PLIST_DIR = "/System/Library/CoreServices/"; + private static readonly Regex DarwinVersionRegex = new Regex("<string>(?<version>10\\.\\d{1,2}\\.?\\d{0,2}?)<\\/string>", + RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly IDiskProvider _diskProvider; private readonly Logger _logger; @@ -40,8 +37,7 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var versionFile = allFiles.SingleOrDefault(c => c.EndsWith("SystemVersion.plist") || - c.EndsWith("ServerVersion.plist") - ); + c.EndsWith("ServerVersion.plist")); if (string.IsNullOrWhiteSpace(versionFile)) { @@ -52,8 +48,6 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var text = _diskProvider.ReadAllText(versionFile); var match = DarwinVersionRegex.Match(text); - - if (match.Success) { version = match.Groups["version"].Value; diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs index d0b5cb3be..78dcceec6 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters foreach (var releaseFile in releaseFiles) { var fileContent = _diskProvider.ReadAllText(releaseFile); - var lines = Regex.Split(fileContent, "\r\n|\r|\n"); ; + var lines = Regex.Split(fileContent, "\r\n|\r|\n"); foreach (var line in lines) { @@ -71,7 +71,6 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters } return new OsVersionModel(name, version, fullName); - } public bool Enabled => OsInfo.IsLinux; diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs index 02bba34b1..994867527 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs @@ -8,10 +8,9 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters { public class SynologyVersionAdapter : IOsVersionAdapter { - private readonly IDiskProvider _diskProvider; private const string NAME = "DSM"; private const string FULL_NAME = "Synology DSM"; - + private readonly IDiskProvider _diskProvider; public SynologyVersionAdapter(IDiskProvider diskProvider) { @@ -37,7 +36,7 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var minor = "0"; var fileContent = _diskProvider.ReadAllText(versionFile); - var lines = Regex.Split(fileContent, "\r\n|\r|\n"); ; + var lines = Regex.Split(fileContent, "\r\n|\r|\n"); foreach (var line in lines) { diff --git a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs index d3fef1dfe..04abf96e9 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs @@ -6,12 +6,12 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using Unity; using Moq; using Moq.Language.Flow; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common.AutoMoq.Unity; +using Unity; [assembly: InternalsVisibleTo("AutoMoq.Tests")] @@ -34,7 +34,6 @@ namespace NzbDrone.Test.Common.AutoMoq { DefaultBehavior = defaultBehavior; SetupAutoMoqer(new UnityContainer()); - } public AutoMoqer(IUnityContainer container) @@ -51,12 +50,14 @@ namespace NzbDrone.Test.Common.AutoMoq return result; } - public virtual Mock<T> GetMock<T>() where T : class + public virtual Mock<T> GetMock<T>() + where T : class { return GetMock<T>(DefaultBehavior); } - public virtual Mock<T> GetMock<T>(MockBehavior behavior) where T : class + public virtual Mock<T> GetMock<T>(MockBehavior behavior) + where T : class { ResolveType = null; var type = GetTheMockType<T>(); @@ -78,9 +79,14 @@ namespace NzbDrone.Test.Common.AutoMoq public virtual void SetMock(Type type, Mock mock) { if (_registeredMocks.ContainsKey(type) == false) + { _registeredMocks.Add(type, mock); + } + if (mock != null) + { _container.RegisterInstance(type, mock.Object); + } } public virtual void SetConstant<T>(T instance) @@ -89,32 +95,38 @@ namespace NzbDrone.Test.Common.AutoMoq SetMock(instance.GetType(), null); } - public ISetup<T> Setup<T>(Expression<Action<T>> expression) where T : class + public ISetup<T> Setup<T>(Expression<Action<T>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) where T : class + public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public void Verify<T>(Expression<Action<T>> expression) where T : class + public void Verify<T>(Expression<Action<T>> expression) + where T : class { GetMock<T>().Verify(expression); } - public void Verify<T>(Expression<Action<T>> expression, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, string failMessage) + where T : class { GetMock<T>().Verify(expression, failMessage); } - public void Verify<T>(Expression<Action<T>> expression, Times times) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times) + where T : class { GetMock<T>().Verify(expression, times); } - public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) + where T : class { GetMock<T>().Verify(expression, times, failMessage); } @@ -125,12 +137,12 @@ namespace NzbDrone.Test.Common.AutoMoq { var mock = registeredMock.Value as Mock; if (mock != null) + { mock.VerifyAll(); + } } } - #region private methods - private void SetupAutoMoqer(IUnityContainer container) { _container = container; @@ -140,9 +152,8 @@ namespace NzbDrone.Test.Common.AutoMoq _registeredMocks = new Dictionary<Type, object>(); AddTheAutoMockingContainerExtensionToTheContainer(container); - #if NETCOREAPP - ContainerBuilderBase.RegisterNativeResolver(new [] {"System.Data.SQLite", "Radarr.Core"}); + ContainerBuilderBase.RegisterNativeResolver(new[] { "System.Data.SQLite", "Radarr.Core" }); #endif } @@ -152,12 +163,14 @@ namespace NzbDrone.Test.Common.AutoMoq return; } - private Mock<T> TheRegisteredMockForThisType<T>(Type type) where T : class + private Mock<T> TheRegisteredMockForThisType<T>(Type type) + where T : class { return (Mock<T>)_registeredMocks.First(x => x.Key == type).Value; } - private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) where T : class + private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) + where T : class { var mock = new Mock<T>(behavior); _container.RegisterInstance(mock.Object); @@ -169,7 +182,8 @@ namespace NzbDrone.Test.Common.AutoMoq return _registeredMocks.ContainsKey(type) == false; } - private static Type GetTheMockType<T>() where T : class + private static Type GetTheMockType<T>() + where T : class { return typeof(T); } @@ -190,7 +204,5 @@ namespace NzbDrone.Test.Common.AutoMoq Assembly.Load(assemblyName); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs index 1756fe656..c841dc7d7 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Unity; using Moq; -using Unity.Strategies; +using Unity; using Unity.Builder; +using Unity.Strategies; namespace NzbDrone.Test.Common.AutoMoq.Unity { @@ -36,8 +36,6 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity } } - #region private methods - private bool AMockObjectShouldBeCreatedForThisType(Type type) { var mocker = _container.Resolve<AutoMoqer>(); @@ -78,7 +76,5 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity { return new[] { typeof(object[]) }; } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs index b764c929d..71838c545 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity { public class AutoMockingContainerExtension : UnityContainerExtension { - private readonly IList<Type> registeredTypes = new List<Type>(); + private readonly IList<Type> _registeredTypes = new List<Type>(); protected override void Initialize() { @@ -15,25 +15,21 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity SetBuildingStrategyForBuildingUnregisteredTypes(); } - #region private methods - private void SetEventsOnContainerToTrackAllRegisteredTypes() { - Context.Registering += ((sender, e) => RegisterType(e.TypeFrom)); - Context.RegisteringInstance += ((sender, e) => RegisterType(e.RegisteredType)); + Context.Registering += (sender, e) => RegisterType(e.TypeFrom); + Context.RegisteringInstance += (sender, e) => RegisterType(e.RegisteredType); } private void RegisterType(Type typeToRegister) { - registeredTypes.Add(typeToRegister); + _registeredTypes.Add(typeToRegister); } private void SetBuildingStrategyForBuildingUnregisteredTypes() { - var strategy = new AutoMockingBuilderStrategy(registeredTypes, Container); + var strategy = new AutoMockingBuilderStrategy(_registeredTypes, Container); Context.Strategies.Add(strategy, UnityBuildStage.PreCreation); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs index c9588d9cd..d62a0dce0 100644 --- a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public DiskAccessTestAttribute() : base("DiskAccessTest") { - } } } diff --git a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs index bae8833e4..f26c5e84e 100644 --- a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public IntegrationTestAttribute() : base("IntegrationTest") { - } } } diff --git a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs index 155322650..0dd8fdec3 100644 --- a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public ManualTestAttribute() : base("ManualTest") { - } } } diff --git a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs index 6f42624a6..6ee4554db 100644 --- a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs +++ b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs @@ -6,9 +6,9 @@ namespace NzbDrone.Test.Common { public class ConcurrencyCounter { + private readonly object _mutex = new object(); + private readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); private int _items; - readonly object _mutex = new object(); - readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); public int MaxThreads => _threads.Count; @@ -30,7 +30,6 @@ namespace NzbDrone.Test.Common int threadId = Thread.CurrentThread.ManagedThreadId; lock (_mutex) { - _threads[threadId] = 1; } diff --git a/src/NzbDrone.Test.Common/ExceptionVerification.cs b/src/NzbDrone.Test.Common/ExceptionVerification.cs index e6b8118b3..bcf417434 100644 --- a/src/NzbDrone.Test.Common/ExceptionVerification.cs +++ b/src/NzbDrone.Test.Common/ExceptionVerification.cs @@ -55,6 +55,7 @@ namespace NzbDrone.Test.Common errors += Environment.NewLine + string.Format("[{0}] {1}: {2} {3}", log.Level, log.LoggerName, log.FormattedMessage, exception); } + return errors; } @@ -75,7 +76,9 @@ namespace NzbDrone.Test.Common } if (!_waitEvent.Wait(msec)) + { break; + } } Expected(LogLevel.Error, count); @@ -142,9 +145,11 @@ namespace NzbDrone.Test.Common if (levelLogs.Count != count) { - var message = string.Format("{0} {1}(s) were expected but {2} were logged.\n\r{3}", - count, level, levelLogs.Count, GetLogsString(levelLogs)); + count, + level, + levelLogs.Count, + GetLogsString(levelLogs)); message = "\n\r****************************************************************************************\n\r" + message + diff --git a/src/NzbDrone.Test.Common/LoggingTest.cs b/src/NzbDrone.Test.Common/LoggingTest.cs index 45f666c09..f08d3aa4b 100644 --- a/src/NzbDrone.Test.Common/LoggingTest.cs +++ b/src/NzbDrone.Test.Common/LoggingTest.cs @@ -1,8 +1,8 @@ +using System; +using System.IO; using NLog; using NLog.Config; using NLog.Targets; -using System; -using System.IO; using NUnit.Framework; using NUnit.Framework.Interfaces; using NzbDrone.Common.EnvironmentInfo; diff --git a/src/NzbDrone.Test.Common/NzbDroneRunner.cs b/src/NzbDrone.Test.Common/NzbDroneRunner.cs index 413930194..55fce6be9 100644 --- a/src/NzbDrone.Test.Common/NzbDroneRunner.cs +++ b/src/NzbDrone.Test.Common/NzbDroneRunner.cs @@ -109,7 +109,6 @@ namespace NzbDrone.Test.Common { var args = "-nobrowser -data=\"" + AppData + "\""; _nzbDroneProcess = _processProvider.Start(outputRadarrConsoleExe, args, null, OnOutputDataReceived, OnOutputDataReceived); - } private void OnOutputDataReceived(string data) @@ -133,9 +132,7 @@ namespace NzbDrone.Test.Common new XDeclaration("1.0", "utf-8", "yes"), new XElement(ConfigFileProvider.CONFIG_ELEMENT_NAME, new XElement(nameof(ConfigFileProvider.ApiKey), apiKey), - new XElement(nameof(ConfigFileProvider.AnalyticsEnabled), false) - ) - ); + new XElement(nameof(ConfigFileProvider.AnalyticsEnabled), false))); var data = xDoc.ToString(); diff --git a/src/NzbDrone.Test.Common/StringExtensions.cs b/src/NzbDrone.Test.Common/StringExtensions.cs index 97b23ade6..659be6170 100644 --- a/src/NzbDrone.Test.Common/StringExtensions.cs +++ b/src/NzbDrone.Test.Common/StringExtensions.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Test.Common path = path.Replace(":", ""); path = Path.DirectorySeparatorChar + path; } + path = path.Replace("\\", Path.DirectorySeparatorChar.ToString()); } diff --git a/src/NzbDrone.Test.Common/TestBase.cs b/src/NzbDrone.Test.Common/TestBase.cs index 8b1e0fc9b..03876da68 100644 --- a/src/NzbDrone.Test.Common/TestBase.cs +++ b/src/NzbDrone.Test.Common/TestBase.cs @@ -14,16 +14,15 @@ using NzbDrone.Test.Common.AutoMoq; namespace NzbDrone.Test.Common { - public abstract class TestBase<TSubject> : TestBase where TSubject : class + public abstract class TestBase<TSubject> : TestBase + where TSubject : class { - private TSubject _subject; [SetUp] public void CoreTestSetup() { _subject = null; - } protected TSubject Subject @@ -37,14 +36,11 @@ namespace NzbDrone.Test.Common return _subject; } - } - } public abstract class TestBase : LoggingTest { - private static readonly Random _random = new Random(); private static int _nextUid; @@ -65,7 +61,6 @@ namespace NzbDrone.Test.Common } } - protected int RandomNumber { get @@ -80,7 +75,10 @@ namespace NzbDrone.Test.Common get { var virtualPath = Path.Combine(TempFolder, "VirtualNzbDrone"); - if (!Directory.Exists(virtualPath)) Directory.CreateDirectory(virtualPath); + if (!Directory.Exists(virtualPath)) + { + Directory.CreateDirectory(virtualPath); + } return virtualPath; } @@ -120,7 +118,6 @@ namespace NzbDrone.Test.Common DeleteTempFolder(_tempFolder); } - public static string GetUID() { return Process.GetCurrentProcess().Id + "_" + DateTime.Now.Ticks + "_" + Interlocked.Increment(ref _nextUid); @@ -133,7 +130,6 @@ namespace NzbDrone.Test.Common return; } - try { var tempFolder = new DirectoryInfo(folder); @@ -202,17 +198,20 @@ namespace NzbDrone.Test.Common return Path.Combine(TempFolder, Path.GetRandomFileName()); } - protected void VerifyEventPublished<TEvent>() where TEvent : class, IEvent + protected void VerifyEventPublished<TEvent>() + where TEvent : class, IEvent { VerifyEventPublished<TEvent>(Times.Once()); } - protected void VerifyEventPublished<TEvent>(Times times) where TEvent : class, IEvent + protected void VerifyEventPublished<TEvent>(Times times) + where TEvent : class, IEvent { Mocker.GetMock<IEventAggregator>().Verify(c => c.PublishEvent(It.IsAny<TEvent>()), times); } - protected void VerifyEventNotPublished<TEvent>() where TEvent : class, IEvent + protected void VerifyEventNotPublished<TEvent>() + where TEvent : class, IEvent { Mocker.GetMock<IEventAggregator>().Verify(c => c.PublishEvent(It.IsAny<TEvent>()), Times.Never()); } diff --git a/src/NzbDrone.Test.Dummy/DummyApp.cs b/src/NzbDrone.Test.Dummy/DummyApp.cs index 125c129a2..7d3482a9e 100644 --- a/src/NzbDrone.Test.Dummy/DummyApp.cs +++ b/src/NzbDrone.Test.Dummy/DummyApp.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Test.Dummy { public const string DUMMY_PROCCESS_NAME = "Radarr.Test.Dummy"; - static void Main(string[] args) + private static void Main(string[] args) { var process = Process.GetCurrentProcess(); diff --git a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs index 6d9a95687..91e41b692 100644 --- a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs +++ b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs @@ -13,8 +13,8 @@ namespace NzbDrone.Update.Test [TestFixture] public class InstallUpdateServiceFixture : TestBase<InstallUpdateService> { - private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); private const int _processId = 12; + private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); [SetUp] public void Setup() diff --git a/src/NzbDrone.Update.Test/ProgramFixture.cs b/src/NzbDrone.Update.Test/ProgramFixture.cs index abf8c24b7..78a4b4f63 100644 --- a/src/NzbDrone.Update.Test/ProgramFixture.cs +++ b/src/NzbDrone.Update.Test/ProgramFixture.cs @@ -11,15 +11,12 @@ namespace NzbDrone.Update.Test [TestFixture] public class ProgramFixture : TestBase<UpdateApp> { - - [Test] public void should_throw_if_null_passed_in() { Assert.Throws<ArgumentOutOfRangeException>(() => Subject.Start(null)); } - [TestCase("d", "")] [TestCase("", "")] [TestCase("0", "")] @@ -34,18 +31,14 @@ namespace NzbDrone.Update.Test [Test] public void should_call_update_with_correct_path() { - var ProcessPath = @"C:\Radarr\radarr.exe".AsOsAgnostic(); + var processPath = @"C:\Radarr\radarr.exe".AsOsAgnostic(); Mocker.GetMock<IProcessProvider>().Setup(c => c.GetProcessById(12)) - .Returns(new ProcessInfo() { StartPath = ProcessPath }); - - - Subject.Start(new[] { "12", "", ProcessPath }); + .Returns(new ProcessInfo() { StartPath = processPath }); + Subject.Start(new[] { "12", "", processPath }); Mocker.GetMock<IInstallUpdateService>().Verify(c => c.Start(@"C:\Radarr".AsOsAgnostic(), 12), Times.Once()); } - - } } diff --git a/src/NzbDrone.Update/UpdateApp.cs b/src/NzbDrone.Update/UpdateApp.cs index 3e91d4977..0cc7ab8da 100644 --- a/src/NzbDrone.Update/UpdateApp.cs +++ b/src/NzbDrone.Update/UpdateApp.cs @@ -15,10 +15,10 @@ namespace NzbDrone.Update { private readonly IInstallUpdateService _installUpdateService; private readonly IProcessProvider _processProvider; - private static IContainer _container; - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(UpdateApp)); + private static IContainer _container; + public UpdateApp(IInstallUpdateService installUpdateService, IProcessProvider processProvider) { _installUpdateService = installUpdateService; @@ -114,7 +114,6 @@ namespace NzbDrone.Update return exeFileInfo.DirectoryName; } - else { Logger.Debug("Using executing application: {0}", startupContext.ExecutingApplication); diff --git a/src/NzbDrone.Update/UpdateContainerBuilder.cs b/src/NzbDrone.Update/UpdateContainerBuilder.cs index ee5e086d2..942914d1a 100644 --- a/src/NzbDrone.Update/UpdateContainerBuilder.cs +++ b/src/NzbDrone.Update/UpdateContainerBuilder.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Update private UpdateContainerBuilder(IStartupContext startupContext, List<string> assemblies) : base(startupContext, assemblies) { - } public static IContainer Build(IStartupContext startupContext) diff --git a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs index 5dc752e30..a7f1c1b97 100644 --- a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs +++ b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs @@ -57,10 +57,14 @@ namespace NzbDrone.Update.UpdateEngine _logger.Info("Verifying requirements before update..."); if (string.IsNullOrWhiteSpace(targetFolder)) + { throw new ArgumentException("Target folder can not be null or empty"); + } if (!_diskProvider.FolderExists(targetFolder)) + { throw new DirectoryNotFoundException("Target folder doesn't exist " + targetFolder); + } if (processId < 1) { @@ -74,7 +78,9 @@ namespace NzbDrone.Update.UpdateEngine _logger.Info("Verifying Update Folder"); if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdatePackageFolder())) + { throw new DirectoryNotFoundException("Update folder doesn't exist " + _appFolderInfo.GetUpdatePackageFolder()); + } } public void Start(string installationFolder, int processId) @@ -157,7 +163,6 @@ namespace NzbDrone.Update.UpdateEngine } } } - } } } diff --git a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs index 341fd2527..c5968b202 100644 --- a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs @@ -37,7 +37,6 @@ namespace NzbDrone.Update.UpdateEngine try { StartService(); - } catch (InvalidOperationException e) { diff --git a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs index ac1b5bb6f..0f8d96c0a 100644 --- a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Windows.Test.DiskProviderTests protected override void SetWritePermissions(string path, bool writable) { // Remove Write permissions, we're owner and have Delete permissions, so we can still clean it up. - var owner = WindowsIdentity.GetCurrent().Owner; var accessControlType = writable ? AccessControlType.Allow : AccessControlType.Deny; diff --git a/src/NzbDrone.Windows/Disk/DiskProvider.cs b/src/NzbDrone.Windows/Disk/DiskProvider.cs index ba3d889a4..10d1fe116 100644 --- a/src/NzbDrone.Windows/Disk/DiskProvider.cs +++ b/src/NzbDrone.Windows/Disk/DiskProvider.cs @@ -14,14 +14,14 @@ namespace NzbDrone.Windows.Disk [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, + private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); + private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); public override long? GetAvailableSpace(string path) { @@ -30,7 +30,9 @@ namespace NzbDrone.Windows.Disk var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveFreeSpaceEx(root); } @@ -47,7 +49,6 @@ namespace NzbDrone.Windows.Disk public override void SetPermissions(string path, string mask, string user, string group) { - } public override long? GetTotalSize(string path) @@ -57,7 +58,9 @@ namespace NzbDrone.Windows.Disk var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveTotalSizeEx(root); } @@ -104,7 +107,6 @@ namespace NzbDrone.Windows.Disk return 0; } - public override bool TryCreateHardLink(string source, string destination) { try diff --git a/src/NzbDrone/Properties/Resources.Designer.cs b/src/NzbDrone/Properties/Resources.Designer.cs index 062c5f8d9..f63243173 100644 --- a/src/NzbDrone/Properties/Resources.Designer.cs +++ b/src/NzbDrone/Properties/Resources.Designer.cs @@ -23,23 +23,28 @@ namespace NzbDrone.Properties [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { + internal class Resources + { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { + internal Resources() + { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NzbDrone.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } @@ -52,11 +57,14 @@ namespace NzbDrone.Properties /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { + internal static global::System.Globalization.CultureInfo Culture + { + get + { return resourceCulture; } - set { + set + { resourceCulture = value; } } @@ -64,8 +72,10 @@ namespace NzbDrone.Properties /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> - internal static System.Drawing.Icon Radarr { - get { + internal static System.Drawing.Icon Radarr + { + get + { object obj = ResourceManager.GetObject("Radarr", resourceCulture); return ((System.Drawing.Icon)(obj)); } diff --git a/src/NzbDrone/SysTray/SysTrayApp.cs b/src/NzbDrone/SysTray/SysTrayApp.cs index 3c27e993b..157ce4e47 100644 --- a/src/NzbDrone/SysTray/SysTrayApp.cs +++ b/src/NzbDrone/SysTray/SysTrayApp.cs @@ -76,9 +76,8 @@ namespace NzbDrone.SysTray if (InvokeRequired) { - base.Invoke(new MethodInvoker(() => Dispose(isDisposing))); + Invoke(new MethodInvoker(() => Dispose(isDisposing))); } - else { base.Dispose(isDisposing); @@ -99,7 +98,6 @@ namespace NzbDrone.SysTray } catch (Exception) { - } } @@ -129,7 +127,6 @@ namespace NzbDrone.SysTray } catch (Exception) { - } } } diff --git a/src/NzbDrone/WindowsApp.cs b/src/NzbDrone/WindowsApp.cs index 8cd0fdc6f..803310240 100644 --- a/src/NzbDrone/WindowsApp.cs +++ b/src/NzbDrone/WindowsApp.cs @@ -3,8 +3,8 @@ using System.Windows.Forms; using NLog; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Instrumentation; -using Radarr.Host; using NzbDrone.SysTray; +using Radarr.Host; namespace NzbDrone { diff --git a/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs b/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs index eb95ccdc0..9cef0409e 100644 --- a/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs +++ b/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs @@ -26,7 +26,10 @@ namespace Radarr.Api.V3.Blacklist { public static BlacklistResource MapToResource(this NzbDrone.Core.Blacklisting.Blacklist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new BlacklistResource { diff --git a/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs b/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs index f32575cef..516c53830 100644 --- a/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs +++ b/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs @@ -1,4 +1,3 @@ -using Nancy; using System; using System.Collections.Generic; using System.Linq; @@ -6,10 +5,11 @@ using Ical.Net; using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; -using NzbDrone.Core.Movies; +using Nancy; using Nancy.Responses; -using NzbDrone.Core.Tags; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Tags; namespace Radarr.Api.V3.Calendar { @@ -24,7 +24,7 @@ namespace Radarr.Api.V3.Calendar _movieService = movieService; _tagService = tagService; - Get("/Radarr.ics", options => GetCalendarFeed()); + Get("/Radarr.ics", options => GetCalendarFeed()); } private object GetCalendarFeed() @@ -44,8 +44,15 @@ namespace Radarr.Api.V3.Calendar var queryUnmonitored = Request.Query.Unmonitored; var queryTags = Request.Query.Tags; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } if (queryPastDays.HasValue) { @@ -89,7 +96,6 @@ namespace Radarr.Api.V3.Calendar CreateEvent(calendar, movie, true); CreateEvent(calendar, movie, false); - } var serializer = (IStringSerializer)new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); diff --git a/src/Radarr.Api.V3/Calendar/CalendarModule.cs b/src/Radarr.Api.V3/Calendar/CalendarModule.cs index 72a06fdd0..2a43afaa2 100644 --- a/src/Radarr.Api.V3/Calendar/CalendarModule.cs +++ b/src/Radarr.Api.V3/Calendar/CalendarModule.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Api.V3.Movies; using NzbDrone.Core.Movies; using NzbDrone.SignalR; +using Radarr.Api.V3.Movies; using Radarr.Http; namespace Radarr.Api.V3.Calendar @@ -32,9 +32,20 @@ namespace Radarr.Api.V3.Calendar var queryEnd = Request.Query.End; var queryIncludeUnmonitored = Request.Query.Unmonitored; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); - if (queryIncludeUnmonitored.HasValue) includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } + + if (queryIncludeUnmonitored.HasValue) + { + includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + } var resources = _moviesService.GetMoviesBetweenDates(start, end, includeUnmonitored).Select(MapToResource); @@ -43,7 +54,10 @@ namespace Radarr.Api.V3.Calendar protected MovieResource MapToResource(Movie movie) { - if (movie == null) return null; + if (movie == null) + { + return null; + } var resource = movie.ToResource(); diff --git a/src/Radarr.Api.V3/Commands/CommandModule.cs b/src/Radarr.Api.V3/Commands/CommandModule.cs index 607f1b9ad..7ffdc966b 100644 --- a/src/Radarr.Api.V3/Commands/CommandModule.cs +++ b/src/Radarr.Api.V3/Commands/CommandModule.cs @@ -48,7 +48,7 @@ namespace Radarr.Api.V3.Commands private int StartCommand(CommandResource commandResource) { var commandType = - _serviceFactory.GetImplementations(typeof (Command)) + _serviceFactory.GetImplementations(typeof(Command)) .Single(c => c.Name.Replace("Command", "") .Equals(commandResource.Name, StringComparison.InvariantCultureIgnoreCase)); diff --git a/src/Radarr.Api.V3/Commands/CommandResource.cs b/src/Radarr.Api.V3/Commands/CommandResource.cs index 4474baa6f..c3d22c0a4 100644 --- a/src/Radarr.Api.V3/Commands/CommandResource.cs +++ b/src/Radarr.Api.V3/Commands/CommandResource.cs @@ -30,37 +30,51 @@ namespace Radarr.Api.V3.Commands { get { - - if (Started.HasValue) return Started.Value; + if (Started.HasValue) + { + return Started.Value; + } return Ended; } - set { } + set + { + } } public bool SendUpdatesToClient { get { - if (Body != null) return Body.SendUpdatesToClient; + if (Body != null) + { + return Body.SendUpdatesToClient; + } return false; } - set { } + set + { + } } public bool UpdateScheduledTask { get { - if (Body != null) return Body.UpdateScheduledTask; + if (Body != null) + { + return Body.UpdateScheduledTask; + } return false; } - set { } + set + { + } } public DateTime? LastExecutionTime { get; set; } @@ -70,7 +84,10 @@ namespace Radarr.Api.V3.Commands { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs b/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs index 7246eeda8..4ee70d056 100644 --- a/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs +++ b/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs @@ -7,7 +7,6 @@ namespace Radarr.Api.V3.Config public DownloadClientConfigModule(IConfigService configService) : base(configService) { - } protected override DownloadClientConfigResource ToResource(IConfigService model) diff --git a/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs b/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs index 58c7fd905..ad1ac291f 100644 --- a/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs +++ b/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/HostConfigModule.cs b/src/Radarr.Api.V3/Config/HostConfigModule.cs index 3cae0845c..1bd43d31c 100644 --- a/src/Radarr.Api.V3/Config/HostConfigModule.cs +++ b/src/Radarr.Api.V3/Config/HostConfigModule.cs @@ -51,7 +51,6 @@ namespace Radarr.Api.V3.Config SharedValidator.RuleFor(c => c.BackupFolder).IsValidPath().When(c => Path.IsPathRooted(c.BackupFolder)); SharedValidator.RuleFor(c => c.BackupInterval).InclusiveBetween(1, 7); SharedValidator.RuleFor(c => c.BackupRetention).InclusiveBetween(1, 90); - } private HostConfigResource GetHostConfig() diff --git a/src/Radarr.Api.V3/Config/HostConfigResource.cs b/src/Radarr.Api.V3/Config/HostConfigResource.cs index a0b651e17..0dbe541bb 100644 --- a/src/Radarr.Api.V3/Config/HostConfigResource.cs +++ b/src/Radarr.Api.V3/Config/HostConfigResource.cs @@ -1,9 +1,9 @@ -using Radarr.Http.REST; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; using NzbDrone.Core.Security; using NzbDrone.Core.Update; -using NzbDrone.Common.Http.Proxy; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { @@ -56,6 +56,7 @@ namespace Radarr.Api.V3.Config LaunchBrowser = model.LaunchBrowser, AuthenticationMethod = model.AuthenticationMethod, AnalyticsEnabled = model.AnalyticsEnabled, + //Username //Password LogLevel = model.LogLevel, diff --git a/src/Radarr.Api.V3/Config/IndexerConfigModule.cs b/src/Radarr.Api.V3/Config/IndexerConfigModule.cs index 93b8dcace..7ad2fe8d9 100644 --- a/src/Radarr.Api.V3/Config/IndexerConfigModule.cs +++ b/src/Radarr.Api.V3/Config/IndexerConfigModule.cs @@ -1,12 +1,11 @@ using FluentValidation; -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Config { public class IndexerConfigModule : RadarrConfigModule<IndexerConfigResource> { - public IndexerConfigModule(IConfigService configService) : base(configService) { diff --git a/src/Radarr.Api.V3/Config/IndexerConfigResource.cs b/src/Radarr.Api.V3/Config/IndexerConfigResource.cs index 7092c2971..3e9910460 100644 --- a/src/Radarr.Api.V3/Config/IndexerConfigResource.cs +++ b/src/Radarr.Api.V3/Config/IndexerConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs b/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs index ce5dcfd8f..5880b889b 100644 --- a/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs +++ b/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/NamingConfigModule.cs b/src/Radarr.Api.V3/Config/NamingConfigModule.cs index 306db7004..785ce954a 100644 --- a/src/Radarr.Api.V3/Config/NamingConfigModule.cs +++ b/src/Radarr.Api.V3/Config/NamingConfigModule.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; +using Nancy.ModelBinding; using NzbDrone.Common.Extensions; using NzbDrone.Core.Organizer; -using Nancy.ModelBinding; using Radarr.Http; namespace Radarr.Api.V3.Config @@ -30,7 +30,7 @@ namespace Radarr.Api.V3.Config GetResourceById = GetNamingConfig; UpdateResource = UpdateNamingConfig; - Get("/examples", x => GetExamples(this.Bind<NamingConfigResource>())); + Get("/examples", x => GetExamples(this.Bind<NamingConfigResource>())); SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat(); SharedValidator.RuleFor(c => c.MovieFolderFormat).ValidMovieFolderFormat(); diff --git a/src/Radarr.Api.V3/Config/NamingConfigResource.cs b/src/Radarr.Api.V3/Config/NamingConfigResource.cs index 336a53604..be0453710 100644 --- a/src/Radarr.Api.V3/Config/NamingConfigResource.cs +++ b/src/Radarr.Api.V3/Config/NamingConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Organizer; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/NamingExampleResource.cs b/src/Radarr.Api.V3/Config/NamingExampleResource.cs index a871d015e..dd57df6b7 100644 --- a/src/Radarr.Api.V3/Config/NamingExampleResource.cs +++ b/src/Radarr.Api.V3/Config/NamingExampleResource.cs @@ -21,6 +21,7 @@ namespace Radarr.Api.V3.Config ColonReplacementFormat = model.ColonReplacementFormat, StandardMovieFormat = model.StandardMovieFormat, MovieFolderFormat = model.MovieFolderFormat, + //IncludeQuality //ReplaceSpaces //Separator diff --git a/src/Radarr.Api.V3/Config/NetImportConfigModule.cs b/src/Radarr.Api.V3/Config/NetImportConfigModule.cs index f6c77d1c4..653e196d1 100644 --- a/src/Radarr.Api.V3/Config/NetImportConfigModule.cs +++ b/src/Radarr.Api.V3/Config/NetImportConfigModule.cs @@ -1,11 +1,10 @@ -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Config { public class NetImportConfigModule : RadarrConfigModule<NetImportConfigResource> { - public NetImportConfigModule(IConfigService configService) : base(configService) { diff --git a/src/Radarr.Api.V3/Config/NetImportConfigResource.cs b/src/Radarr.Api.V3/Config/NetImportConfigResource.cs index ad3b7cab7..8b4a2c803 100644 --- a/src/Radarr.Api.V3/Config/NetImportConfigResource.cs +++ b/src/Radarr.Api.V3/Config/NetImportConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/RadarrConfigModule.cs b/src/Radarr.Api.V3/Config/RadarrConfigModule.cs index 3f37ec9d0..ec21274b0 100644 --- a/src/Radarr.Api.V3/Config/RadarrConfigModule.cs +++ b/src/Radarr.Api.V3/Config/RadarrConfigModule.cs @@ -1,12 +1,13 @@ using System.Linq; using System.Reflection; +using NzbDrone.Core.Configuration; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Configuration; namespace Radarr.Api.V3.Config { - public abstract class RadarrConfigModule<TResource> : RadarrRestModule<TResource> where TResource : RestResource, new() + public abstract class RadarrConfigModule<TResource> : RadarrRestModule<TResource> + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ namespace Radarr.Api.V3.Config { } - protected RadarrConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected RadarrConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/Radarr.Api.V3/Config/UiConfigModule.cs b/src/Radarr.Api.V3/Config/UiConfigModule.cs index 5c3953b76..03308ccf2 100644 --- a/src/Radarr.Api.V3/Config/UiConfigModule.cs +++ b/src/Radarr.Api.V3/Config/UiConfigModule.cs @@ -7,7 +7,6 @@ namespace Radarr.Api.V3.Config public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) diff --git a/src/Radarr.Api.V3/Config/UiConfigResource.cs b/src/Radarr.Api.V3/Config/UiConfigResource.cs index f9bd8a51d..ed074313c 100644 --- a/src/Radarr.Api.V3/Config/UiConfigResource.cs +++ b/src/Radarr.Api.V3/Config/UiConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs b/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs index 66e6e53b8..358d6865e 100644 --- a/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs +++ b/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs @@ -17,28 +17,34 @@ namespace Radarr.Api.V3.CustomFilters { public static CustomFilterResource ToResource(this CustomFilter model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CustomFilterResource - { - Id = model.Id, - Type = model.Type, - Label = model.Label, - Filters = Json.Deserialize<List<dynamic>>(model.Filters) - }; + { + Id = model.Id, + Type = model.Type, + Label = model.Label, + Filters = Json.Deserialize<List<dynamic>>(model.Filters) + }; } public static CustomFilter ToModel(this CustomFilterResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new CustomFilter - { - Id = resource.Id, - Type = resource.Type, - Label = resource.Label, - Filters = Json.ToJson(resource.Filters) - }; + { + Id = resource.Id, + Type = resource.Type, + Label = resource.Label, + Filters = Json.ToJson(resource.Filters) + }; } public static List<CustomFilterResource> ToResource(this IEnumerable<CustomFilter> filters) diff --git a/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs b/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs index 00be647ff..4b192ff06 100644 --- a/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs +++ b/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs @@ -9,7 +9,7 @@ namespace Radarr.Api.V3.DiskSpace private readonly IDiskSpaceService _diskSpaceService; public DiskSpaceModule(IDiskSpaceService diskSpaceService) - :base("diskspace") + : base("diskspace") { _diskSpaceService = diskSpaceService; GetResourceAll = GetFreeSpace; diff --git a/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs b/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs index e56e571a4..9bc8f5d34 100644 --- a/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs +++ b/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ namespace Radarr.Api.V3.DiskSpace { public static DiskSpaceResource MapToResource(this NzbDrone.Core.DiskSpace.DiskSpace model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DiskSpaceResource { diff --git a/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs b/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs index d187e5f3a..e3633af22 100644 --- a/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs +++ b/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs @@ -13,7 +13,11 @@ namespace Radarr.Api.V3.DownloadClient protected override void Validate(DownloadClientDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs b/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs index 6282f8a3a..f3d846ab1 100644 --- a/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs +++ b/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs @@ -14,7 +14,10 @@ namespace Radarr.Api.V3.DownloadClient { public override DownloadClientResource ToResource(DownloadClientDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -27,7 +30,10 @@ namespace Radarr.Api.V3.DownloadClient public override DownloadClientDefinition ToModel(DownloadClientResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs b/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs index 939dccaea..7331e0674 100644 --- a/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs +++ b/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs @@ -22,9 +22,9 @@ namespace Radarr.Api.V3.FileSystem _fileSystemLookupService = fileSystemLookupService; _diskProvider = diskProvider; _diskScanService = diskScanService; - Get("/", x => GetContents()); - Get("/type", x => GetEntityType()); - Get("/mediafiles", x => GetMediaFiles()); + Get("/", x => GetContents()); + Get("/type", x => GetEntityType()); + Get("/mediafiles", x => GetMediaFiles()); } private object GetContents() @@ -60,7 +60,8 @@ namespace Radarr.Api.V3.FileSystem return new string[0]; } - return _diskScanService.GetVideoFiles(path).Select(f => new { + return _diskScanService.GetVideoFiles(path).Select(f => new + { Path = f, RelativePath = path.GetRelativePath(f), Name = Path.GetFileName(f) diff --git a/src/Radarr.Api.V3/Health/HealthResource.cs b/src/Radarr.Api.V3/Health/HealthResource.cs index 090d30cf3..ab5f8fe0a 100644 --- a/src/Radarr.Api.V3/Health/HealthResource.cs +++ b/src/Radarr.Api.V3/Health/HealthResource.cs @@ -18,7 +18,10 @@ namespace Radarr.Api.V3.Health { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/Radarr.Api.V3/History/HistoryModule.cs b/src/Radarr.Api.V3/History/HistoryModule.cs index 7feb64cd1..8c1f57a9f 100644 --- a/src/Radarr.Api.V3/History/HistoryModule.cs +++ b/src/Radarr.Api.V3/History/HistoryModule.cs @@ -28,9 +28,9 @@ namespace Radarr.Api.V3.History _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; - Get("/since", x => GetHistorySince()); - Get("/movie", x => GetMovieHistory()); - Post("/failed", x => MarkAsFailed()); + Get("/since", x => GetHistorySince()); + Get("/movie", x => GetMovieHistory()); + Post("/failed", x => MarkAsFailed()); } protected HistoryResource MapToResource(NzbDrone.Core.History.History model, bool includeMovie) diff --git a/src/Radarr.Api.V3/History/HistoryResource.cs b/src/Radarr.Api.V3/History/HistoryResource.cs index ec3d4c261..a235e3554 100644 --- a/src/Radarr.Api.V3/History/HistoryResource.cs +++ b/src/Radarr.Api.V3/History/HistoryResource.cs @@ -29,7 +29,10 @@ namespace Radarr.Api.V3.History { public static HistoryResource ToResource(this NzbDrone.Core.History.History model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -39,6 +42,7 @@ namespace Radarr.Api.V3.History SourceTitle = model.SourceTitle, Languages = model.Languages, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, diff --git a/src/Radarr.Api.V3/Indexers/IndexerModule.cs b/src/Radarr.Api.V3/Indexers/IndexerModule.cs index 5252de7e3..51ae28d30 100644 --- a/src/Radarr.Api.V3/Indexers/IndexerModule.cs +++ b/src/Radarr.Api.V3/Indexers/IndexerModule.cs @@ -13,7 +13,11 @@ namespace Radarr.Api.V3.Indexers protected override void Validate(IndexerDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Indexers/IndexerResource.cs b/src/Radarr.Api.V3/Indexers/IndexerResource.cs index f53dbcfdc..ae4e9413c 100644 --- a/src/Radarr.Api.V3/Indexers/IndexerResource.cs +++ b/src/Radarr.Api.V3/Indexers/IndexerResource.cs @@ -16,7 +16,10 @@ namespace Radarr.Api.V3.Indexers { public override IndexerResource ToResource(IndexerDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -32,7 +35,10 @@ namespace Radarr.Api.V3.Indexers public override IndexerDefinition ToModel(IndexerResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/Indexers/ReleaseModule.cs b/src/Radarr.Api.V3/Indexers/ReleaseModule.cs index c3bdfbc1d..67da1ae78 100644 --- a/src/Radarr.Api.V3/Indexers/ReleaseModule.cs +++ b/src/Radarr.Api.V3/Indexers/ReleaseModule.cs @@ -45,7 +45,7 @@ namespace Radarr.Api.V3.Indexers PostValidator.RuleFor(s => s.Guid).NotEmpty(); GetResourceAll = GetReleases; - Post("/", x => DownloadRelease(ReadResourceFromRequest())); + Post("/", x => DownloadRelease(ReadResourceFromRequest())); _remoteMovieCache = cacheManager.GetCache<RemoteMovie>(GetType(), "remoteMovies"); } diff --git a/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs b/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs index 7a4e315d1..109e77b8b 100644 --- a/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs +++ b/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs @@ -12,7 +12,7 @@ using NzbDrone.Core.Parser.Model; namespace Radarr.Api.V3.Indexers { - class ReleasePushModule : ReleaseModuleBase + public class ReleasePushModule : ReleaseModuleBase { private readonly IMakeDownloadDecision _downloadDecisionMaker; private readonly IProcessDownloadDecisions _downloadDecisionProcessor; @@ -34,7 +34,7 @@ namespace Radarr.Api.V3.Indexers PostValidator.RuleFor(s => s.Protocol).NotEmpty(); PostValidator.RuleFor(s => s.PublishDate).NotEmpty(); - Post("/push", x => ProcessRelease(ReadResourceFromRequest())); + Post("/push", x => ProcessRelease(ReadResourceFromRequest())); } private object ProcessRelease(ReleaseResource release) @@ -54,10 +54,10 @@ namespace Radarr.Api.V3.Indexers if (firstDecision?.RemoteMovie.ParsedMovieInfo == null) { - throw new ValidationException(new List<ValidationFailure>{ new ValidationFailure("Title", "Unable to parse", release.Title) }); + throw new ValidationException(new List<ValidationFailure> { new ValidationFailure("Title", "Unable to parse", release.Title) }); } - return MapDecisions(new [] { firstDecision }); + return MapDecisions(new[] { firstDecision }); } private void ResolveIndexer(ReleaseInfo release) diff --git a/src/Radarr.Api.V3/Indexers/ReleaseResource.cs b/src/Radarr.Api.V3/Indexers/ReleaseResource.cs index 3f2afc65b..514974ecb 100644 --- a/src/Radarr.Api.V3/Indexers/ReleaseResource.cs +++ b/src/Radarr.Api.V3/Indexers/ReleaseResource.cs @@ -53,10 +53,8 @@ namespace Radarr.Api.V3.Indexers public bool Special { get; set; } // Sent when queuing an unknown release - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? MovieId { get; set; } - } public static class ReleaseResourceMapper @@ -73,6 +71,7 @@ namespace Radarr.Api.V3.Indexers { Guid = releaseInfo.Guid, Quality = parsedMovieInfo.Quality, + //QualityWeight Age = releaseInfo.Age, AgeHours = releaseInfo.AgeHours, @@ -95,16 +94,14 @@ namespace Radarr.Api.V3.Indexers DownloadUrl = releaseInfo.DownloadUrl, InfoUrl = releaseInfo.InfoUrl, DownloadAllowed = remoteMovie.DownloadAllowed, + //ReleaseWeight - - MagnetUrl = torrentInfo.MagnetUrl, InfoHash = torrentInfo.InfoHash, Seeders = torrentInfo.Seeders, Leechers = (torrentInfo.Peers.HasValue && torrentInfo.Seeders.HasValue) ? (torrentInfo.Peers.Value - torrentInfo.Seeders.Value) : (int?)null, Protocol = releaseInfo.DownloadProtocol }; - } public static ReleaseInfo ToModel(this ReleaseResource resource) diff --git a/src/Radarr.Api.V3/Logs/LogFileModule.cs b/src/Radarr.Api.V3/Logs/LogFileModule.cs index e8a0c2ff9..43c670889 100644 --- a/src/Radarr.Api.V3/Logs/LogFileModule.cs +++ b/src/Radarr.Api.V3/Logs/LogFileModule.cs @@ -38,6 +38,5 @@ namespace Radarr.Api.V3.Logs return "logfile"; } } - } } diff --git a/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs b/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs index fbf72387a..a970f672a 100644 --- a/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs +++ b/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs @@ -26,7 +26,7 @@ namespace Radarr.Api.V3.Logs _configFileProvider = configFileProvider; GetResourceAll = GetLogFilesResponse; - Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); + Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); } private List<LogFileResource> GetLogFilesResponse() @@ -60,7 +60,9 @@ namespace Radarr.Api.V3.Logs var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); diff --git a/src/Radarr.Api.V3/Logs/LogResource.cs b/src/Radarr.Api.V3/Logs/LogResource.cs index 42721c2e3..51e682912 100644 --- a/src/Radarr.Api.V3/Logs/LogResource.cs +++ b/src/Radarr.Api.V3/Logs/LogResource.cs @@ -19,7 +19,10 @@ namespace Radarr.Api.V3.Logs { public static LogResource ToResource(this Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs b/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs index 5301f153d..5e3924bd1 100644 --- a/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs +++ b/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ namespace Radarr.Api.V3.Logs protected override IEnumerable<string> GetLogFiles() { - if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) return Enumerable.Empty<string>(); + if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) + { + return Enumerable.Empty<string>(); + } return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly) .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase)) diff --git a/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs b/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs index bed3c6fd6..5919596cc 100644 --- a/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs +++ b/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs @@ -29,19 +29,24 @@ namespace Radarr.Api.V3.ManualImport { public static ManualImportResource ToResource(this ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { Id = HashConverter.GetHashInt31(model.Path), Path = model.Path, RelativePath = model.RelativePath, + // FolderName = model.FolderName, Name = model.Name, Size = model.Size, Movie = model.Movie.ToResource(), Quality = model.Quality, Languages = model.Languages, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections diff --git a/src/Radarr.Api.V3/Metadata/MetadataModule.cs b/src/Radarr.Api.V3/Metadata/MetadataModule.cs index 252633309..cde0fed2a 100644 --- a/src/Radarr.Api.V3/Metadata/MetadataModule.cs +++ b/src/Radarr.Api.V3/Metadata/MetadataModule.cs @@ -13,7 +13,11 @@ namespace Radarr.Api.V3.Metadata protected override void Validate(MetadataDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Metadata/MetadataResource.cs b/src/Radarr.Api.V3/Metadata/MetadataResource.cs index 3dcf83e60..72e31307d 100644 --- a/src/Radarr.Api.V3/Metadata/MetadataResource.cs +++ b/src/Radarr.Api.V3/Metadata/MetadataResource.cs @@ -11,7 +11,10 @@ namespace Radarr.Api.V3.Metadata { public override MetadataResource ToResource(MetadataDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -22,7 +25,10 @@ namespace Radarr.Api.V3.Metadata public override MetadataDefinition ToModel(MetadataResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs b/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs index 4c455d49c..3a9e2b111 100644 --- a/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs +++ b/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs @@ -32,25 +32,24 @@ namespace Radarr.Api.V3.MovieFiles } return new MediaInfoResource - { - AudioAdditionalFeatures = model.AudioAdditionalFeatures, - AudioBitrate = model.AudioBitrate, - AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), - AudioLanguages = model.AudioLanguages, - AudioStreamCount = model.AudioStreamCount, - AudioCodec = MediaInfoFormatter.FormatAudioCodec(model, sceneName), - VideoBitDepth = model.VideoBitDepth, - VideoBitrate = model.VideoBitrate, - VideoCodec = MediaInfoFormatter.FormatVideoCodec(model, sceneName), - VideoFps = model.VideoFps, - Resolution = $"{model.Width}x{model.Height}", - RunTime = FormatRuntime(model.RunTime), - ScanType = model.ScanType, - Subtitles = model.Subtitles - }; + { + AudioAdditionalFeatures = model.AudioAdditionalFeatures, + AudioBitrate = model.AudioBitrate, + AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), + AudioLanguages = model.AudioLanguages, + AudioStreamCount = model.AudioStreamCount, + AudioCodec = MediaInfoFormatter.FormatAudioCodec(model, sceneName), + VideoBitDepth = model.VideoBitDepth, + VideoBitrate = model.VideoBitrate, + VideoCodec = MediaInfoFormatter.FormatVideoCodec(model, sceneName), + VideoFps = model.VideoFps, + Resolution = $"{model.Width}x{model.Height}", + RunTime = FormatRuntime(model.RunTime), + ScanType = model.ScanType, + Subtitles = model.Subtitles + }; } - private static string FormatRuntime(TimeSpan runTime) { var formattedRuntime = ""; diff --git a/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs b/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs index dece4d30d..771f1944c 100644 --- a/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs +++ b/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs @@ -46,8 +46,8 @@ namespace Radarr.Api.V3.MovieFiles UpdateResource = SetMovieFile; DeleteResource = DeleteMovieFile; - Put("/editor", movieFiles => SetMovieFile()); - Delete("/bulk", movieFiles => DeleteMovieFiles()); + Put("/editor", movieFiles => SetMovieFile()); + Delete("/bulk", movieFiles => DeleteMovieFiles()); } private MovieFileResource GetMovieFile(int id) @@ -75,7 +75,6 @@ namespace Radarr.Api.V3.MovieFiles return _mediaFileService.GetFilesByMovie(movieId).ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)); } - else { string movieFileIdsValue = movieFileIdsQuery.Value.ToString(); @@ -88,7 +87,7 @@ namespace Radarr.Api.V3.MovieFiles return movieFiles.GroupBy(e => e.MovieId) .SelectMany(f => f.ToList() - .ConvertAll( e => e.ToResource(_movieService.GetMovie(f.Key), _qualityUpgradableSpecification))) + .ConvertAll(e => e.ToResource(_movieService.GetMovie(f.Key), _qualityUpgradableSpecification))) .ToList(); } } @@ -108,24 +107,23 @@ namespace Radarr.Api.V3.MovieFiles foreach (var movieFile in movieFiles) { - if (resource.Quality != null) { movieFile.Quality = resource.Quality; } + if (resource.Languages != null) { movieFile.Languages = resource.Languages; } - } _mediaFileService.Update(movieFiles); var movie = _movieService.GetMovie(movieFiles.First().MovieId); - return ResponseWithCode(movieFiles.ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)) - , HttpStatusCode.Accepted); + return ResponseWithCode(movieFiles.ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)), + HttpStatusCode.Accepted); } private void DeleteMovieFile(int id) @@ -137,6 +135,7 @@ namespace Radarr.Api.V3.MovieFiles _logger.Info("Deleting movie file: {0}", fullPath); _recycleBinProvider.DeleteFile(fullPath); _mediaFileService.Delete(movieFile, DeleteMediaFileReason.Manual); + // TODO: Pull MediaFileDeletionService from Sonarr //_mediaFileDeletionService.Delete(series, episodeFile); } @@ -153,6 +152,7 @@ namespace Radarr.Api.V3.MovieFiles _logger.Info("Deleting movie file: {0}", fullPath); _recycleBinProvider.DeleteFile(fullPath); _mediaFileService.Delete(movieFile, DeleteMediaFileReason.Manual); + // TODO: Pull MediaFileDeletionService from Sonarr //_mediaFileDeletionService.DeleteEpisodeFile(movie, movieFile); } diff --git a/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs b/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs index 2f266671a..c6339f464 100644 --- a/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs +++ b/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs @@ -27,7 +27,10 @@ namespace Radarr.Api.V3.MovieFiles { private static MovieFileResource ToResource(this MovieFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { @@ -35,6 +38,7 @@ namespace Radarr.Api.V3.MovieFiles MovieId = model.MovieId, RelativePath = model.RelativePath, + //Path Size = model.Size, DateAdded = model.DateAdded, @@ -42,14 +46,17 @@ namespace Radarr.Api.V3.MovieFiles Quality = model.Quality, Languages = model.Languages, MediaInfo = model.MediaInfo.ToResource(model.SceneName), + //QualityCutoffNotMet }; - } public static MovieFileResource ToResource(this MovieFile model, NzbDrone.Core.Movies.Movie movie) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { @@ -64,13 +71,17 @@ namespace Radarr.Api.V3.MovieFiles Quality = model.Quality, Languages = model.Languages, MediaInfo = model.MediaInfo.ToResource(model.SceneName), + // QualityCutoffNotMet = upgradableSpecification.CutoffNotMet(movie.Profile.Value, model.Quality) }; } public static MovieFileResource ToResource(this MovieFile model, NzbDrone.Core.Movies.Movie movie, IUpgradableSpecification upgradableSpecification) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { diff --git a/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs b/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs index ecd6049d0..bf3005f9a 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies.Events; using Radarr.Http; diff --git a/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs b/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs index 93c2ed0b2..a85b40a42 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies.AlternativeTitles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -10,13 +10,11 @@ namespace Radarr.Api.V3.Movies { public AlternativeTitleResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public SourceType SourceType { get; set; } public int MovieId { get; set; } public string Title { get; set; } @@ -33,7 +31,10 @@ namespace Radarr.Api.V3.Movies { public static AlternativeTitleResource ToResource(this AlternativeTitle model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new AlternativeTitleResource { @@ -50,7 +51,10 @@ namespace Radarr.Api.V3.Movies public static AlternativeTitle ToModel(this AlternativeTitleResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new AlternativeTitle { diff --git a/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs b/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs index 2e4daefe3..94569efd1 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs @@ -6,13 +6,11 @@ namespace Radarr.Api.V3.Movies { public AlternativeYearResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public int Year { get; set; } diff --git a/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs b/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs index b910d0fa2..8fd4615d5 100644 --- a/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs +++ b/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using NzbDrone.Core.NetImport; using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport; using Radarr.Http; namespace Radarr.Api.V3.Movies @@ -19,13 +19,12 @@ namespace Radarr.Api.V3.Movies { _fetchNetImport = netImport; _movieSearch = movieSearch; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { - var results = _fetchNetImport.FetchAndFilter((int) Request.Query.listId, false); + var results = _fetchNetImport.FetchAndFilter((int)Request.Query.listId, false); List<Movie> realResults = new List<Movie>(); @@ -42,7 +41,6 @@ namespace Radarr.Api.V3.Movies return MapToResource(realResults); } - private static IEnumerable<MovieResource> MapToResource(IEnumerable<Movie> movies) { foreach (var currentSeries in movies) diff --git a/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs b/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs index e3de85f9c..f69d91448 100644 --- a/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; -using NzbDrone.Core.Movies; +using System.Linq; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using Radarr.Http; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using Radarr.Api.V3.NetImport; using NzbDrone.Core.Organizer; +using Radarr.Api.V3.NetImport; +using Radarr.Http; namespace Radarr.Api.V3.Movies { @@ -22,8 +22,8 @@ namespace Radarr.Api.V3.Movies _searchProxy = searchProxy; _netImportFactory = netImportFactory; _fileNameBuilder = fileNameBuilder; - Get("/lists", x => GetLists()); - Get("/{action?recommendations}", x => Search(x.action)); + Get("/lists", x => GetLists()); + Get("/{action?recommendations}", x => Search(x.action)); } private object Search(string action) @@ -36,7 +36,8 @@ namespace Radarr.Api.V3.Movies { var lists = _netImportFactory.Discoverable(); - return lists.Select(definition => { + return lists.Select(definition => + { var resource = new NetImportResource(); resource.Id = definition.Definition.Id; diff --git a/src/Radarr.Api.V3/Movies/MovieEditorModule.cs b/src/Radarr.Api.V3/Movies/MovieEditorModule.cs index d9c460deb..66f22257a 100644 --- a/src/Radarr.Api.V3/Movies/MovieEditorModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieEditorModule.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Http.Extensions; -using NzbDrone.Core.Movies; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Movies.Commands; using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.Commands; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.Movies { @@ -19,8 +19,8 @@ namespace Radarr.Api.V3.Movies { _movieService = movieService; _commandQueueManager = commandQueueManager; - Put("/", movie => SaveAll()); - Delete("/", movie => DeleteMovies()); + Put("/", movie => SaveAll()); + Delete("/", movie => DeleteMovies()); } private object SaveAll() @@ -86,8 +86,8 @@ namespace Radarr.Api.V3.Movies } return ResponseWithCode(_movieService.UpdateMovie(moviesToUpdate) - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteMovies() diff --git a/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs b/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs index f5af3f6a7..8fd1131cf 100644 --- a/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs +++ b/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs @@ -18,18 +18,27 @@ namespace Radarr.Api.V3.Movies protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var movieResource = context.Instance as MovieResource; - if (movieResource == null) return true; + if (movieResource == null) + { + return true; + } var rootFolderPath = context.PropertyValue.ToString(); var rootFolder = new DirectoryInfo(rootFolderPath).Name; var movie = movieResource.ToModel(); var movieFolder = _fileNameBuilder.GetMovieFolder(movie); - if (movieFolder == rootFolder) return false; + if (movieFolder == rootFolder) + { + return false; + } var distance = movieFolder.LevenshteinDistance(rootFolder); diff --git a/src/Radarr.Api.V3/Movies/MovieImportModule.cs b/src/Radarr.Api.V3/Movies/MovieImportModule.cs index 1886f5bc5..14b36d419 100644 --- a/src/Radarr.Api.V3/Movies/MovieImportModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieImportModule.cs @@ -14,10 +14,9 @@ namespace Radarr.Api.V3.Movies : base("/movie/import") { _movieService = movieService; - Post("/", x => Import()); + Post("/", x => Import()); } - private object Import() { var resource = Request.Body.FromJson<List<MovieResource>>(); diff --git a/src/Radarr.Api.V3/Movies/MovieLookupModule.cs b/src/Radarr.Api.V3/Movies/MovieLookupModule.cs index 3ffc0c9a6..e0a445a85 100644 --- a/src/Radarr.Api.V3/Movies/MovieLookupModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieLookupModule.cs @@ -1,13 +1,13 @@ +using System; using System.Collections.Generic; +using System.Linq; using Nancy; -using NzbDrone.Core.Movies; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using System; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Organizer; namespace Radarr.Api.V3.Movies { @@ -23,15 +23,15 @@ namespace Radarr.Api.V3.Movies _movieInfo = movieInfo; _searchProxy = searchProxy; _fileNameBuilder = fileNameBuilder; - Get("/", x => Search()); - Get("/tmdb", x => SearchByTmdbId()); - Get("/imdb", x => SearchByImdbId()); + Get("/", x => Search()); + Get("/tmdb", x => SearchByTmdbId()); + Get("/imdb", x => SearchByImdbId()); } private object SearchByTmdbId() { int tmdbId = -1; - if(Int32.TryParse(Request.Query.tmdbId, out tmdbId)) + if (int.TryParse(Request.Query.tmdbId, out tmdbId)) { var result = _movieInfo.GetMovieInfo(tmdbId, null, true); return result.ToResource(); diff --git a/src/Radarr.Api.V3/Movies/MovieModule.cs b/src/Radarr.Api.V3/Movies/MovieModule.cs index 3822c3f13..1fab16bea 100644 --- a/src/Radarr.Api.V3/Movies/MovieModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using FluentValidation; +using Nancy; using NzbDrone.Common.Extensions; -using Radarr.Http.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; @@ -9,11 +9,11 @@ using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Validation.Paths; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; using NzbDrone.SignalR; -using Nancy; using Radarr.Http; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.Movies { @@ -25,21 +25,19 @@ namespace Radarr.Api.V3.Movies IHandle<MovieDeletedEvent>, IHandle<MovieRenamedEvent>, IHandle<MediaCoversUpdatedEvent> - { protected readonly IMovieService _moviesService; private readonly IMapCoversToLocal _coverMapper; public MovieModule(IBroadcastSignalRMessage signalRBroadcaster, - IMovieService moviesService, - IMapCoversToLocal coverMapper, - RootFolderValidator rootFolderValidator, - MoviePathValidator moviesPathValidator, - MovieExistsValidator moviesExistsValidator, - MovieAncestorValidator moviesAncestorValidator, - ProfileExistsValidator profileExistsValidator, - MovieFolderAsRootFolderValidator movieFolderAsRootFolderValidator - ) + IMovieService moviesService, + IMapCoversToLocal coverMapper, + RootFolderValidator rootFolderValidator, + MoviePathValidator moviesPathValidator, + MovieExistsValidator moviesExistsValidator, + MovieAncestorValidator moviesAncestorValidator, + ProfileExistsValidator profileExistsValidator, + MovieFolderAsRootFolderValidator movieFolderAsRootFolderValidator) : base(signalRBroadcaster) { _moviesService = moviesService; @@ -93,7 +91,10 @@ namespace Radarr.Api.V3.Movies protected MovieResource MapToResource(Movie movies) { - if (movies == null) return null; + if (movies == null) + { + return null; + } var resource = movies.ToResource(); MapCoversToLocal(resource); @@ -159,7 +160,10 @@ namespace Radarr.Api.V3.Movies public void Handle(MovieFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId); } diff --git a/src/Radarr.Api.V3/Movies/MovieResource.cs b/src/Radarr.Api.V3/Movies/MovieResource.cs index ce220f148..4fae2d762 100644 --- a/src/Radarr.Api.V3/Movies/MovieResource.cs +++ b/src/Radarr.Api.V3/Movies/MovieResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Movies; using Radarr.Api.V3.MovieFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -33,6 +33,7 @@ namespace Radarr.Api.V3.Movies public string PhysicalReleaseNote { get; set; } public List<MediaCover> Images { get; set; } public string Website { get; set; } + //public bool Downloaded { get; set; } public string RemotePoster { get; set; } public int Year { get; set; } @@ -66,14 +67,16 @@ namespace Radarr.Api.V3.Movies public AddMovieOptions AddOptions { get; set; } public Ratings Ratings { get; set; } public MovieFileResource MovieFile { get; set; } - } public static class MovieResourceMapper { public static MovieResource ToResource(this Movie model) { - if (model == null) return null; + if (model == null) + { + return null; + } long size = model.MovieFile?.Size ?? 0; MovieFileResource movieFile = model.MovieFile?.ToResource(model); @@ -131,7 +134,10 @@ namespace Radarr.Api.V3.Movies public static Movie ToModel(this MovieResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Movie { diff --git a/src/Radarr.Api.V3/Movies/RenameMovieModule.cs b/src/Radarr.Api.V3/Movies/RenameMovieModule.cs index 849544184..964c28f6a 100644 --- a/src/Radarr.Api.V3/Movies/RenameMovieModule.cs +++ b/src/Radarr.Api.V3/Movies/RenameMovieModule.cs @@ -1,7 +1,7 @@ -using Radarr.Http.REST; -using NzbDrone.Core.MediaFiles; using System.Collections.Generic; +using NzbDrone.Core.MediaFiles; using Radarr.Http; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -21,7 +21,7 @@ namespace Radarr.Api.V3.Movies { int movieId; - if(Request.Query.MovieId.HasValue) + if (Request.Query.MovieId.HasValue) { movieId = (int)Request.Query.MovieId; } @@ -32,6 +32,5 @@ namespace Radarr.Api.V3.Movies return _renameMovieFileService.GetRenamePreviews(movieId).ToResource(); } - } } diff --git a/src/Radarr.Api.V3/Movies/RenameMovieResource.cs b/src/Radarr.Api.V3/Movies/RenameMovieResource.cs index c88fb701e..5f9f71061 100644 --- a/src/Radarr.Api.V3/Movies/RenameMovieResource.cs +++ b/src/Radarr.Api.V3/Movies/RenameMovieResource.cs @@ -1,7 +1,7 @@ -using NzbDrone.Core.MediaFiles; -using Radarr.Http.REST; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -17,7 +17,10 @@ namespace Radarr.Api.V3.Movies { public static RenameMovieResource ToResource(this RenameMovieFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameMovieResource { diff --git a/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs b/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs index 6d0737047..ad440f1ed 100644 --- a/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs +++ b/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs @@ -10,7 +10,8 @@ namespace Radarr.Api.V3.NetImport { private readonly IImportExclusionsService _exclusionService; - public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) : base("exclusions") + public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) + : base("exclusions") { _exclusionService = exclusionService; GetResourceAll = GetAll; @@ -38,11 +39,10 @@ namespace Radarr.Api.V3.NetImport var model = exclusionResource.ToModel(); // TODO: Add some more validation here and auto pull the title if not provided - return _exclusionService.AddExclusion(model).Id; } - public void RemoveExclusion (int id) + public void RemoveExclusion(int id) { _exclusionService.RemoveExclusion(new ImportExclusion { Id = id }); } diff --git a/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs b/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs index 68a2b3452..718819e0a 100644 --- a/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs +++ b/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs @@ -15,7 +15,10 @@ namespace Radarr.Api.V3.NetImport { public static ImportExclusionsResource ToResource(this NzbDrone.Core.NetImport.ImportExclusions.ImportExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportExclusionsResource { diff --git a/src/Radarr.Api.V3/NetImport/ListImportModule.cs b/src/Radarr.Api.V3/NetImport/ListImportModule.cs index b28a4ca29..6dad28771 100644 --- a/src/Radarr.Api.V3/NetImport/ListImportModule.cs +++ b/src/Radarr.Api.V3/NetImport/ListImportModule.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using Nancy; using Nancy.Extensions; -using Radarr.Http.Extensions; -using Radarr.Api.V3.Movies; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using Radarr.Api.V3.Movies; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.NetImport { @@ -19,16 +19,16 @@ namespace Radarr.Api.V3.NetImport { _movieService = movieService; _movieSearch = movieSearch; - Put("/", Movie => SaveAll()); + Put("/", movie => SaveAll()); } private object SaveAll() { var resources = Request.Body.FromJson<List<MovieResource>>(); - var Movies = resources.Select(MovieResource => _movieSearch.MapMovieToTmdbMovie(MovieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); + var movies = resources.Select(movieResource => _movieSearch.MapMovieToTmdbMovie(movieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); - return ResponseWithCode(_movieService.AddMovies(Movies).ToResource(), HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.AddMovies(movies).ToResource(), HttpStatusCode.Accepted); } } } diff --git a/src/Radarr.Api.V3/NetImport/NetImportModule.cs b/src/Radarr.Api.V3/NetImport/NetImportModule.cs index a93a340e1..390da99e0 100644 --- a/src/Radarr.Api.V3/NetImport/NetImportModule.cs +++ b/src/Radarr.Api.V3/NetImport/NetImportModule.cs @@ -18,7 +18,11 @@ namespace Radarr.Api.V3.NetImport protected override void Validate(NetImportDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Notifications/NotificationModule.cs b/src/Radarr.Api.V3/Notifications/NotificationModule.cs index 25b43fbc4..a6c37aeb5 100644 --- a/src/Radarr.Api.V3/Notifications/NotificationModule.cs +++ b/src/Radarr.Api.V3/Notifications/NotificationModule.cs @@ -13,7 +13,11 @@ namespace Radarr.Api.V3.Notifications protected override void Validate(NotificationDefinition definition, bool includeWarnings) { - if (!definition.OnGrab && !definition.OnDownload) return; + if (!definition.OnGrab && !definition.OnDownload) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Notifications/NotificationResource.cs b/src/Radarr.Api.V3/Notifications/NotificationResource.cs index 258799ae7..f04302fb0 100644 --- a/src/Radarr.Api.V3/Notifications/NotificationResource.cs +++ b/src/Radarr.Api.V3/Notifications/NotificationResource.cs @@ -23,7 +23,10 @@ namespace Radarr.Api.V3.Notifications { public override NotificationResource ToResource(NotificationDefinition definition) { - if (definition == null) return default(NotificationResource); + if (definition == null) + { + return default(NotificationResource); + } var resource = base.ToResource(definition); @@ -44,7 +47,10 @@ namespace Radarr.Api.V3.Notifications public override NotificationDefinition ToModel(NotificationResource resource) { - if (resource == null) return default(NotificationDefinition); + if (resource == null) + { + return default(NotificationDefinition); + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs index 1764f53b1..4af4bcd9e 100644 --- a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs +++ b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using FluentValidation; -using Radarr.Http.REST; -using Radarr.Http.Validation; using NzbDrone.Core.Profiles.Delay; using Radarr.Http; +using Radarr.Http.REST; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Profiles.Delay { diff --git a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs index 9b1350ea4..214f85f43 100644 --- a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs +++ b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Indexers; using NzbDrone.Core.Profiles.Delay; +using Radarr.Http.REST; namespace Radarr.Api.V3.Profiles.Delay { @@ -21,7 +21,10 @@ namespace Radarr.Api.V3.Profiles.Delay { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -39,7 +42,10 @@ namespace Radarr.Api.V3.Profiles.Delay public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs b/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs index f96e450a3..de5d0a87d 100644 --- a/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs +++ b/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs @@ -27,10 +27,10 @@ namespace Radarr.Api.V3.Profiles.Languages private List<LanguageResource> GetAll() { return Language.All.Select(l => new LanguageResource - { - Id = (int)l, - Name = l.ToString() - }) + { + Id = (int)l, + Name = l.ToString() + }) .OrderBy(l => l.Name) .ToList(); } diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs index 0d1e5ff45..8ef307784 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs @@ -18,7 +18,6 @@ namespace Radarr.Api.V3.Profiles.Quality public ValidCutoffValidator() : base("Cutoff must be an allowed quality or group") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -29,9 +28,15 @@ namespace Radarr.Api.V3.Profiles.Quality var cutoffItem = items.SingleOrDefault(i => (i.Quality == null && i.Id == cutoff) || i.Quality?.Id == cutoff); - if (cutoffItem == null) return false; + if (cutoffItem == null) + { + return false; + } - if (!cutoffItem.Allowed) return false; + if (!cutoffItem.Allowed) + { + return false; + } return true; } diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs index 025a71db3..ba74a24c8 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs @@ -26,7 +26,6 @@ namespace Radarr.Api.V3.Profiles.Quality public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -52,7 +51,6 @@ namespace Radarr.Api.V3.Profiles.Quality public GroupItemValidator() : base("Groups must contain multiple qualities") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -73,7 +71,6 @@ namespace Radarr.Api.V3.Profiles.Quality public QualityNameValidator() : base("Individual qualities should not be named") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -94,7 +91,6 @@ namespace Radarr.Api.V3.Profiles.Quality public ItemGroupNameValidator() : base("Groups must have a name") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -115,7 +111,6 @@ namespace Radarr.Api.V3.Profiles.Quality public ItemGroupIdValidator() : base("Groups must have an ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -136,7 +131,6 @@ namespace Radarr.Api.V3.Profiles.Quality public UniqueIdValidator() : base("Groups must have a unique ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -157,7 +151,6 @@ namespace Radarr.Api.V3.Profiles.Quality public UniqueQualityIdValidator() : base("Qualities can only be used once") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -179,7 +172,6 @@ namespace Radarr.Api.V3.Profiles.Quality qualityIds.Add(quality.Quality.Id); } } - else { if (qualityIds.Contains(item.Quality.Id)) diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs index 8e5aa2360..d453342b7 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs @@ -18,6 +18,7 @@ namespace Radarr.Api.V3.Profiles.Quality _profileService = profileService; _formatService = formatService; SharedValidator.RuleFor(c => c.Name).NotEmpty(); + // TODO: Need to validate the cutoff is allowed and the ID/quality ID exists // TODO: Need to validate the Items to ensure groups have names and at no item has no name, no items and no quality SharedValidator.RuleFor(c => c.Cutoff).ValidCutoff(); diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs index 8d2bb6502..a6bda6d6e 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Languages; using NzbDrone.Core.CustomFormats; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Profiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Profiles.Quality { @@ -42,7 +42,10 @@ namespace Radarr.Api.V3.Profiles.Quality { public static QualityProfileResource ToResource(this Profile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileResource { @@ -60,7 +63,10 @@ namespace Radarr.Api.V3.Profiles.Quality public static QualityProfileQualityItemResource ToResource(this ProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileQualityItemResource { @@ -83,7 +89,10 @@ namespace Radarr.Api.V3.Profiles.Quality public static Profile ToModel(this QualityProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Profile { @@ -101,7 +110,10 @@ namespace Radarr.Api.V3.Profiles.Quality public static ProfileQualityItem ToModel(this QualityProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileQualityItem { diff --git a/src/Radarr.Api.V3/ProviderModuleBase.cs b/src/Radarr.Api.V3/ProviderModuleBase.cs index 1f3f1c46b..54250be05 100644 --- a/src/Radarr.Api.V3/ProviderModuleBase.cs +++ b/src/Radarr.Api.V3/ProviderModuleBase.cs @@ -24,10 +24,10 @@ namespace Radarr.Api.V3 _providerFactory = providerFactory; _resourceMapper = resourceMapper; - Get("schema", x => GetTemplates()); - Post("test", x => Test(ReadResourceFromRequest(true))); - Post("testall", x => TestAll()); - Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); + Get("schema", x => GetTemplates()); + Post("test", x => Test(ReadResourceFromRequest(true))); + Post("testall", x => TestAll()); + Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); GetResourceAll = GetAll; GetResourceById = GetProviderById; @@ -36,7 +36,7 @@ namespace Radarr.Api.V3 DeleteResource = DeleteProvider; SharedValidator.RuleFor(c => c.Name).NotEmpty(); - SharedValidator.RuleFor(c => c.Name).Must((v,c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); + SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); SharedValidator.RuleFor(c => c.Implementation).NotEmpty(); SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty(); @@ -155,10 +155,10 @@ namespace Radarr.Api.V3 var validationResult = _providerFactory.Test(definition); result.Add(new ProviderTestAllResult - { - Id = definition.Id, - ValidationFailures = validationResult.Errors.ToList() - }); + { + Id = definition.Id, + ValidationFailures = validationResult.Errors.ToList() + }); } return ResponseWithCode(result, result.Any(c => !c.IsValid) ? HttpStatusCode.BadRequest : HttpStatusCode.OK); diff --git a/src/Radarr.Api.V3/ProviderResource.cs b/src/Radarr.Api.V3/ProviderResource.cs index e14944f69..376d8b5ae 100644 --- a/src/Radarr.Api.V3/ProviderResource.cs +++ b/src/Radarr.Api.V3/ProviderResource.cs @@ -25,7 +25,6 @@ namespace Radarr.Api.V3 where TProviderDefinition : ProviderDefinition, new() { public virtual TProviderResource ToResource(TProviderDefinition definition) - { return new TProviderResource { @@ -47,7 +46,10 @@ namespace Radarr.Api.V3 public virtual TProviderDefinition ToModel(TProviderResource resource) { - if (resource == null) return default(TProviderDefinition); + if (resource == null) + { + return default(TProviderDefinition); + } var definition = new TProviderDefinition { diff --git a/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs b/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs index f39a3c81b..b7c185dde 100644 --- a/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs +++ b/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs @@ -31,7 +31,7 @@ namespace Radarr.Api.V3.Qualities var allNewTags = c.Split(',').Select(t => t.ToLower()); var enumerable = allTags.ToList(); var newTags = allNewTags.ToList(); - return (enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count()); + return enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count(); }); }) .WithMessage("Should be unique."); @@ -46,11 +46,11 @@ namespace Radarr.Api.V3.Qualities DeleteResource = DeleteFormat; - Get("/test", x => Test()); + Get("/test", x => Test()); - Post("/test", x => TestWithNewModel()); + Post("/test", x => TestWithNewModel()); - Get("schema", x => GetTemplates()); + Get("schema", x => GetTemplates()); } private int Create(CustomFormatResource customFormatResource) @@ -95,11 +95,12 @@ namespace Radarr.Api.V3.Qualities private CustomFormatTestResource Test() { - var parsed = _parsingService.ParseMovieInfo((string) Request.Query.title, new List<object>()); + var parsed = _parsingService.ParseMovieInfo((string)Request.Query.title, new List<object>()); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), @@ -109,18 +110,19 @@ namespace Radarr.Api.V3.Qualities private CustomFormatTestResource TestWithNewModel() { - var queryTitle = (string) Request.Query.title; + var queryTitle = (string)Request.Query.title; var resource = ReadResourceFromRequest(); var model = resource.ToModel(); model.Name = model.Name += " (New)"; - var parsed = _parsingService.ParseMovieInfo(queryTitle, new List<object>{model}); + var parsed = _parsingService.ParseMovieInfo(queryTitle, new List<object> { model }); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), diff --git a/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs b/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs index 098de14fc..a7ba6b78c 100644 --- a/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs +++ b/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { diff --git a/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs b/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs index 2df880145..9890a2235 100644 --- a/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs +++ b/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Extensions; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { @@ -29,7 +29,10 @@ namespace Radarr.Api.V3.Qualities { public static FormatTagMatchResultResource ToResource(this FormatTagMatchResult model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new FormatTagMatchResultResource { diff --git a/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs b/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs index 0d7796674..bd0bcca36 100644 --- a/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs +++ b/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs @@ -7,7 +7,8 @@ namespace Radarr.Api.V3.Qualities { public class FormatTagValidator : PropertyValidator { - public FormatTagValidator() : base("{ValidationMessage}") + public FormatTagValidator() + : base("{ValidationMessage}") { } @@ -19,11 +20,14 @@ namespace Radarr.Api.V3.Qualities return false; } - var tags = (IEnumerable<string>) context.PropertyValue.ToString().Split(','); + var tags = (IEnumerable<string>)context.PropertyValue.ToString().Split(','); var invalidTags = tags.Where(t => !FormatTag.QualityTagRegex.IsMatch(t)); - if (invalidTags.Count() == 0) return true; + if (invalidTags.Count() == 0) + { + return true; + } var formatMessage = $"Format Tags ({string.Join(", ", invalidTags)}) are in an invalid format! Check the Wiki to learn how they should look."; diff --git a/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs b/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs index 281a8ac3c..82887084f 100644 --- a/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs +++ b/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs @@ -47,8 +47,8 @@ namespace Radarr.Api.V3.Qualities _qualityDefinitionService.UpdateMany(qualityDefinitions); return ResponseWithCode(_qualityDefinitionService.All() - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } } } diff --git a/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs b/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs index 716cfddfc..eb0c0ec18 100644 --- a/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs +++ b/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { @@ -21,7 +21,10 @@ namespace Radarr.Api.V3.Qualities { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -40,7 +43,10 @@ namespace Radarr.Api.V3.Qualities public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { diff --git a/src/Radarr.Api.V3/Queue/QueueActionModule.cs b/src/Radarr.Api.V3/Queue/QueueActionModule.cs index 66acba5a4..5d48c6e7f 100644 --- a/src/Radarr.Api.V3/Queue/QueueActionModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueActionModule.cs @@ -33,11 +33,11 @@ namespace Radarr.Api.V3.Queue _pendingReleaseService = pendingReleaseService; _downloadService = downloadService; - Post(@"/grab/(?<id>[\d]{1,10})", x => Grab((int)x.Id)); - Post("/grab/bulk", x => Grab()); + Post(@"/grab/(?<id>[\d]{1,10})", x => Grab((int)x.Id)); + Post("/grab/bulk", x => Grab()); - Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id)); - Delete("/bulk", x => Remove()); + Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id)); + Delete("/bulk", x => Remove()); } private object Grab(int id) diff --git a/src/Radarr.Api.V3/Queue/QueueModule.cs b/src/Radarr.Api.V3/Queue/QueueModule.cs index cb3223eb4..c9c52059e 100644 --- a/src/Radarr.Api.V3/Queue/QueueModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueModule.cs @@ -20,7 +20,7 @@ namespace Radarr.Api.V3.Queue private readonly IQueueService _queueService; private readonly IPendingReleaseService _pendingReleaseService; - private readonly QualityModelComparer QUALITY_COMPARER; + private readonly QualityModelComparer _qualityComparer; public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, @@ -32,7 +32,7 @@ namespace Radarr.Api.V3.Queue _pendingReleaseService = pendingReleaseService; GetResourcePaged = GetQueue; - QUALITY_COMPARER = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); + _qualityComparer = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); } private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pagingResource) @@ -61,7 +61,6 @@ namespace Radarr.Api.V3.Queue ? fullQueue.OrderBy(q => q.Timeleft, new TimeleftComparer()) : fullQueue.OrderByDescending(q => q.Timeleft, new TimeleftComparer()); } - else if (pagingSpec.SortKey == "estimatedCompletionTime") { ordered = ascending @@ -69,41 +68,36 @@ namespace Radarr.Api.V3.Queue : fullQueue.OrderByDescending(q => q.EstimatedCompletionTime, new EstimatedCompletionTimeComparer()); } - else if (pagingSpec.SortKey == "protocol") { ordered = ascending ? fullQueue.OrderBy(q => q.Protocol) : fullQueue.OrderByDescending(q => q.Protocol); } - else if (pagingSpec.SortKey == "indexer") { ordered = ascending ? fullQueue.OrderBy(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "downloadClient") { ordered = ascending ? fullQueue.OrderBy(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "quality") { ordered = ascending - ? fullQueue.OrderBy(q => q.Quality, QUALITY_COMPARER) - : fullQueue.OrderByDescending(q => q.Quality, QUALITY_COMPARER); + ? fullQueue.OrderBy(q => q.Quality, _qualityComparer) + : fullQueue.OrderByDescending(q => q.Quality, _qualityComparer); } - else { ordered = ascending ? fullQueue.OrderBy(orderByFunc) : fullQueue.OrderByDescending(orderByFunc); } - ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - q.Sizeleft / q.Size * 100); + ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - (q.Sizeleft / q.Size * 100)); pagingSpec.Records = ordered.Skip((pagingSpec.Page - 1) * pagingSpec.PageSize).Take(pagingSpec.PageSize).ToList(); pagingSpec.TotalRecords = fullQueue.Count; @@ -117,7 +111,7 @@ namespace Radarr.Api.V3.Queue return pagingSpec; } - private Func<NzbDrone.Core.Queue.Queue, Object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) + private Func<NzbDrone.Core.Queue.Queue, object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) { switch (pagingSpec.SortKey) { @@ -133,7 +127,7 @@ namespace Radarr.Api.V3.Queue return q => q.Quality; case "progress": // Avoid exploding if a download's size is 0 - return q => 100 - q.Sizeleft / Math.Max(q.Size * 100, 1); + return q => 100 - (q.Sizeleft / Math.Max(q.Size * 100, 1)); default: return q => q.Timeleft; } diff --git a/src/Radarr.Api.V3/Queue/QueueResource.cs b/src/Radarr.Api.V3/Queue/QueueResource.cs index b64b35433..5cffcae51 100644 --- a/src/Radarr.Api.V3/Queue/QueueResource.cs +++ b/src/Radarr.Api.V3/Queue/QueueResource.cs @@ -36,7 +36,10 @@ namespace Radarr.Api.V3.Queue { public static QueueResource ToResource(this NzbDrone.Core.Queue.Queue model, bool includeMovie) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/Radarr.Api.V3/Queue/QueueStatusModule.cs b/src/Radarr.Api.V3/Queue/QueueStatusModule.cs index c01bf1d30..cd7196122 100644 --- a/src/Radarr.Api.V3/Queue/QueueStatusModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueStatusModule.cs @@ -17,7 +17,6 @@ namespace Radarr.Api.V3.Queue private readonly IPendingReleaseService _pendingReleaseService; private readonly Debouncer _broadcastDebounce; - public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService) : base(broadcastSignalRMessage, "queue/status") { @@ -26,8 +25,7 @@ namespace Radarr.Api.V3.Queue _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5)); - - Get("/", x => GetQueueStatusResponse()); + Get("/", x => GetQueueStatusResponse()); } private object GetQueueStatusResponse() diff --git a/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs b/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs index 87f4c24de..fef52fd70 100644 --- a/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs @@ -16,7 +16,10 @@ namespace Radarr.Api.V3.RemotePathMappings { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ namespace Radarr.Api.V3.RemotePathMappings public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs b/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs index 91363f02a..38edc9476 100644 --- a/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs +++ b/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs @@ -10,7 +10,6 @@ namespace Radarr.Api.V3.Restrictions { private readonly IRestrictionService _restrictionService; - public RestrictionModule(IRestrictionService restrictionService) { _restrictionService = restrictionService; diff --git a/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs b/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs index 3ca323bd4..c40cb43b3 100644 --- a/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs +++ b/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs @@ -22,7 +22,10 @@ namespace Radarr.Api.V3.Restrictions { public static RestrictionResource ToResource(this Restriction model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RestrictionResource { @@ -37,7 +40,10 @@ namespace Radarr.Api.V3.Restrictions public static Restriction ToModel(this RestrictionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Restriction { diff --git a/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs b/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs index d8ac2240a..517b5fb9e 100644 --- a/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs +++ b/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs @@ -18,9 +18,8 @@ namespace Radarr.Api.V3.RootFolders MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) - : base(signalRBroadcaster) + FolderWritableValidator folderWritableValidator) + : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs b/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs index ed78d6f2b..88c97df63 100644 --- a/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs +++ b/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs @@ -19,7 +19,10 @@ namespace Radarr.Api.V3.RootFolders { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -34,13 +37,17 @@ namespace Radarr.Api.V3.RootFolders public static RootFolder ToModel(this RootFolderResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RootFolder { Id = resource.Id, Path = resource.Path + //Accessible //FreeSpace //UnmappedFolders diff --git a/src/Radarr.Api.V3/System/Backup/BackupModule.cs b/src/Radarr.Api.V3/System/Backup/BackupModule.cs index b3f7e0d2a..cfdda1ce1 100644 --- a/src/Radarr.Api.V3/System/Backup/BackupModule.cs +++ b/src/Radarr.Api.V3/System/Backup/BackupModule.cs @@ -30,8 +30,8 @@ namespace Radarr.Api.V3.System.Backup GetResourceAll = GetBackupFiles; DeleteResource = DeleteBackup; - Post(@"/restore/(?<id>[\d]{1,10})", x => Restore((int)x.Id)); - Post("/restore/upload", x => UploadAndRestore()); + Post(@"/restore/(?<id>[\d]{1,10})", x => Restore((int)x.Id)); + Post("/restore/upload", x => UploadAndRestore()); } public List<BackupResource> GetBackupFiles() @@ -39,13 +39,13 @@ namespace Radarr.Api.V3.System.Backup var backups = _backupService.GetBackups(); return backups.Select(b => new BackupResource - { - Id = GetBackupId(b), - Name = b.Name, - Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", - Type = b.Type, - Time = b.Time - }) + { + Id = GetBackupId(b), + Name = b.Name, + Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", + Type = b.Type, + Time = b.Time + }) .OrderByDescending(b => b.Time) .ToList(); } @@ -77,9 +77,9 @@ namespace Radarr.Api.V3.System.Backup _backupService.Restore(path); return new - { - RestartRequired = true - }; + { + RestartRequired = true + }; } public object UploadAndRestore() @@ -108,9 +108,9 @@ namespace Radarr.Api.V3.System.Backup _diskProvider.DeleteFile(path); return new - { - RestartRequired = true - }; + { + RestartRequired = true + }; } private string GetBackupPath(NzbDrone.Core.Backup.Backup backup) diff --git a/src/Radarr.Api.V3/System/Backup/BackupResource.cs b/src/Radarr.Api.V3/System/Backup/BackupResource.cs index 78d86f245..605e5fb98 100644 --- a/src/Radarr.Api.V3/System/Backup/BackupResource.cs +++ b/src/Radarr.Api.V3/System/Backup/BackupResource.cs @@ -1,6 +1,6 @@ using System; -using Radarr.Http.REST; using NzbDrone.Core.Backup; +using Radarr.Http.REST; namespace Radarr.Api.V3.System.Backup { diff --git a/src/Radarr.Api.V3/System/SystemModule.cs b/src/Radarr.Api.V3/System/SystemModule.cs index 0a6c9b658..7a3b27bb2 100644 --- a/src/Radarr.Api.V3/System/SystemModule.cs +++ b/src/Radarr.Api.V3/System/SystemModule.cs @@ -37,42 +37,42 @@ namespace Radarr.Api.V3.System _configFileProvider = configFileProvider; _database = database; _lifecycleService = lifecycleService; - Get("/status", x => GetStatus()); - Get("/routes", x => GetRoutes()); - Post("/shutdown", x => Shutdown()); - Post("/restart", x => Restart()); + Get("/status", x => GetStatus()); + Get("/routes", x => GetRoutes()); + Post("/shutdown", x => Shutdown()); + Post("/restart", x => Restart()); } private object GetStatus() { return new - { - Version = BuildInfo.Version.ToString(), - BuildTime = BuildInfo.BuildDateTime, - IsDebug = BuildInfo.IsDebug, - IsProduction = RuntimeInfo.IsProduction, - IsAdmin = _runtimeInfo.IsAdmin, - IsUserInteractive = RuntimeInfo.IsUserInteractive, - StartupPath = _appFolderInfo.StartUpFolder, - AppData = _appFolderInfo.GetAppDataPath(), - OsName = _osInfo.Name, - OsVersion = _osInfo.Version, - IsNetCore = PlatformInfo.IsNetCore, - IsMono = PlatformInfo.IsMono, - IsLinux = OsInfo.IsLinux, - IsOsx = OsInfo.IsOsx, - IsWindows = OsInfo.IsWindows, - IsDocker = _osInfo.IsDocker, - Mode = _runtimeInfo.Mode, - Branch = _configFileProvider.Branch, - Authentication = _configFileProvider.AuthenticationMethod, - SqliteVersion = _database.Version, - MigrationVersion = _database.Migration, - UrlBase = _configFileProvider.UrlBase, - RuntimeVersion = _platformInfo.Version, - RuntimeName = PlatformInfo.Platform, - StartTime = _runtimeInfo.StartTime - }; + { + Version = BuildInfo.Version.ToString(), + BuildTime = BuildInfo.BuildDateTime, + IsDebug = BuildInfo.IsDebug, + IsProduction = RuntimeInfo.IsProduction, + IsAdmin = _runtimeInfo.IsAdmin, + IsUserInteractive = RuntimeInfo.IsUserInteractive, + StartupPath = _appFolderInfo.StartUpFolder, + AppData = _appFolderInfo.GetAppDataPath(), + OsName = _osInfo.Name, + OsVersion = _osInfo.Version, + IsNetCore = PlatformInfo.IsNetCore, + IsMono = PlatformInfo.IsMono, + IsLinux = OsInfo.IsLinux, + IsOsx = OsInfo.IsOsx, + IsWindows = OsInfo.IsWindows, + IsDocker = _osInfo.IsDocker, + Mode = _runtimeInfo.Mode, + Branch = _configFileProvider.Branch, + Authentication = _configFileProvider.AuthenticationMethod, + SqliteVersion = _database.Version, + MigrationVersion = _database.Migration, + UrlBase = _configFileProvider.UrlBase, + RuntimeVersion = _platformInfo.Version, + RuntimeName = PlatformInfo.Platform, + StartTime = _runtimeInfo.StartTime + }; } private object GetRoutes() diff --git a/src/Radarr.Api.V3/System/Tasks/TaskModule.cs b/src/Radarr.Api.V3/System/Tasks/TaskModule.cs index 8949142f7..55548ae2d 100644 --- a/src/Radarr.Api.V3/System/Tasks/TaskModule.cs +++ b/src/Radarr.Api.V3/System/Tasks/TaskModule.cs @@ -47,15 +47,15 @@ namespace Radarr.Api.V3.System.Tasks var taskName = scheduledTask.TypeName.Split('.').Last().Replace("Command", ""); return new TaskResource - { - Id = scheduledTask.Id, - Name = taskName.SplitCamelCase(), - TaskName = taskName, - Interval = scheduledTask.Interval, - LastExecution = scheduledTask.LastExecution, - LastStartTime = scheduledTask.LastStartTime, - NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) - }; + { + Id = scheduledTask.Id, + Name = taskName.SplitCamelCase(), + TaskName = taskName, + Interval = scheduledTask.Interval, + LastExecution = scheduledTask.LastExecution, + LastStartTime = scheduledTask.LastStartTime, + NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) + }; } public void Handle(CommandExecutedEvent message) diff --git a/src/Radarr.Api.V3/Tags/TagDetailsResource.cs b/src/Radarr.Api.V3/Tags/TagDetailsResource.cs index 4ba530795..2981069f0 100644 --- a/src/Radarr.Api.V3/Tags/TagDetailsResource.cs +++ b/src/Radarr.Api.V3/Tags/TagDetailsResource.cs @@ -19,7 +19,10 @@ namespace Radarr.Api.V3.Tags { public static TagDetailsResource ToResource(this TagDetails model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagDetailsResource { diff --git a/src/Radarr.Api.V3/Tags/TagResource.cs b/src/Radarr.Api.V3/Tags/TagResource.cs index b890c4f10..0b8f39114 100644 --- a/src/Radarr.Api.V3/Tags/TagResource.cs +++ b/src/Radarr.Api.V3/Tags/TagResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Tags; +using Radarr.Http.REST; namespace Radarr.Api.V3.Tags { @@ -14,7 +14,10 @@ namespace Radarr.Api.V3.Tags { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -25,7 +28,10 @@ namespace Radarr.Api.V3.Tags public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/Radarr.Api.V3/Update/UpdateResource.cs b/src/Radarr.Api.V3/Update/UpdateResource.cs index d887371e9..127ae45b4 100644 --- a/src/Radarr.Api.V3/Update/UpdateResource.cs +++ b/src/Radarr.Api.V3/Update/UpdateResource.cs @@ -27,7 +27,10 @@ namespace Radarr.Api.V3.Update { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -37,6 +40,7 @@ namespace Radarr.Api.V3.Update ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/Radarr.Http/Authentication/AuthenticationModule.cs b/src/Radarr.Http/Authentication/AuthenticationModule.cs index a4a8d9a42..35c51f205 100644 --- a/src/Radarr.Http/Authentication/AuthenticationModule.cs +++ b/src/Radarr.Http/Authentication/AuthenticationModule.cs @@ -16,8 +16,8 @@ namespace Radarr.Http.Authentication { _authService = authService; _configFileProvider = configFileProvider; - Post("/login", x => Login(this.Bind<LoginResource>())); - Get("/logout", x => Logout()); + Post("/login", x => Login(this.Bind<LoginResource>())); + Get("/logout", x => Logout()); } private Response Login(LoginResource resource) diff --git a/src/Radarr.Http/Authentication/AuthenticationService.cs b/src/Radarr.Http/Authentication/AuthenticationService.cs index 17b6c7820..cb5c5e844 100644 --- a/src/Radarr.Http/Authentication/AuthenticationService.cs +++ b/src/Radarr.Http/Authentication/AuthenticationService.cs @@ -25,8 +25,8 @@ namespace Radarr.Http.Authentication public class AuthenticationService : IAuthenticationService { - private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private const string AnonymousUser = "Anonymous"; + private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private readonly IUserService _userService; private static string API_KEY; @@ -170,14 +170,20 @@ namespace Radarr.Http.Authentication private bool ValidUser(NancyContext context) { - if (context.CurrentUser != null) return true; + if (context.CurrentUser != null) + { + return true; + } return false; } private bool ValidApiKey(string apiKey) { - if (API_KEY.Equals(apiKey)) return true; + if (API_KEY.Equals(apiKey)) + { + return true; + } return false; } diff --git a/src/Radarr.Http/Authentication/EnableAuthInNancy.cs b/src/Radarr.Http/Authentication/EnableAuthInNancy.cs index 48da0683a..cff6ed3b9 100644 --- a/src/Radarr.Http/Authentication/EnableAuthInNancy.cs +++ b/src/Radarr.Http/Authentication/EnableAuthInNancy.cs @@ -19,7 +19,7 @@ namespace Radarr.Http.Authentication private readonly IAuthenticationService _authenticationService; private readonly IConfigService _configService; private readonly IConfigFileProvider _configFileProvider; - private FormsAuthenticationConfiguration FormsAuthConfig; + private FormsAuthenticationConfiguration _formsAuthConfig; public EnableAuthInNancy(IAuthenticationService authenticationService, IConfigService configService, @@ -39,7 +39,6 @@ namespace Radarr.Http.Authentication RegisterFormsAuth(pipelines); pipelines.AfterRequest.AddItemToEndOfPipeline((Action<NancyContext>)SlidingAuthenticationForFormsAuth); } - else if (_configFileProvider.AuthenticationMethod == AuthenticationType.Basic) { pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(_authenticationService, "Radarr")); @@ -57,7 +56,6 @@ namespace Radarr.Http.Authentication return null; } - private Response RequiresAuthentication(NancyContext context) { Response response = null; @@ -77,10 +75,9 @@ namespace Radarr.Http.Authentication var cryptographyConfiguration = new CryptographyConfiguration( new AesEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase, Encoding.ASCII.GetBytes(_configService.RijndaelSalt))), - new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt))) - ); + new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt)))); - FormsAuthConfig = new FormsAuthenticationConfiguration + _formsAuthConfig = new FormsAuthenticationConfiguration { RedirectUrl = _configFileProvider.UrlBase + "/login", UserMapper = _authenticationService, @@ -88,7 +85,7 @@ namespace Radarr.Http.Authentication CryptographyConfiguration = cryptographyConfiguration }; - FormsAuthentication.Enable(pipelines, FormsAuthConfig); + FormsAuthentication.Enable(pipelines, _formsAuthConfig); } private void RemoveLoginHooksForApiCalls(NancyContext context) @@ -118,7 +115,7 @@ namespace Radarr.Http.Authentication { var formsAuthCookieValue = context.Request.Cookies[formsAuthCookieName]; - if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, FormsAuthConfig).IsNotNullOrWhiteSpace()) + if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, _formsAuthConfig).IsNotNullOrWhiteSpace()) { var formsAuthCookie = new NancyCookie(formsAuthCookieName, formsAuthCookieValue, true, false, DateTime.UtcNow.AddDays(7)) { diff --git a/src/Radarr.Http/ClientSchema/SchemaBuilder.cs b/src/Radarr.Http/ClientSchema/SchemaBuilder.cs index 5f348c2d9..7c2fb8648 100644 --- a/src/Radarr.Http/ClientSchema/SchemaBuilder.cs +++ b/src/Radarr.Http/ClientSchema/SchemaBuilder.cs @@ -50,7 +50,6 @@ namespace Radarr.Http.ClientSchema } return target; - } public static T ReadFromSchema<T>(List<Field> fields) @@ -58,7 +57,6 @@ namespace Radarr.Http.ClientSchema return (T)ReadFromSchema(fields, typeof(T)); } - // Ideally this function should begin a System.Linq.Expression expression tree since it's faster. // But it's probably not needed till performance issues pop up. public static FieldMapping[] GetFieldMappings(Type type) @@ -78,6 +76,7 @@ namespace Radarr.Http.ClientSchema _mappings[type] = result; } + return result; } } @@ -156,32 +155,26 @@ namespace Radarr.Http.ClientSchema { return fieldValue => fieldValue?.ToString().ParseInt32() ?? 0; } - else if (propertyType == typeof(long)) { return fieldValue => fieldValue?.ToString().ParseInt64() ?? 0; } - else if (propertyType == typeof(double)) { return fieldValue => fieldValue?.ToString().ParseDouble() ?? 0.0; } - else if (propertyType == typeof(int?)) { return fieldValue => fieldValue?.ToString().ParseInt32(); } - - else if (propertyType == typeof(Int64?)) + else if (propertyType == typeof(long?)) { return fieldValue => fieldValue?.ToString().ParseInt64(); } - else if (propertyType == typeof(double?)) { return fieldValue => fieldValue?.ToString().ParseDouble(); } - else if (propertyType == typeof(IEnumerable<int>)) { return fieldValue => @@ -196,7 +189,6 @@ namespace Radarr.Http.ClientSchema } }; } - else if (propertyType == typeof(IEnumerable<string>)) { return fieldValue => @@ -211,7 +203,6 @@ namespace Radarr.Http.ClientSchema } }; } - else { return fieldValue => fieldValue; @@ -220,7 +211,7 @@ namespace Radarr.Http.ClientSchema private static string GetCamelCaseName(string name) { - return Char.ToLowerInvariant(name[0]) + name.Substring(1); + return char.ToLowerInvariant(name[0]) + name.Substring(1); } } } diff --git a/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs b/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs index 07ded72d1..08e50d6f8 100644 --- a/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs +++ b/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs @@ -69,10 +69,12 @@ namespace Radarr.Http.ErrorManagement if (context.Request.Method == "PUT" || context.Request.Method == "POST") { if (sqLiteException.Message.Contains("constraint failed")) + { return new ErrorModel { Message = exception.Message, }.AsResponse(context, HttpStatusCode.Conflict); + } } _logger.Error(sqLiteException, "[{0} {1}]", context.Request.Method, context.Request.Path); diff --git a/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs b/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs index d6306a5d0..7d6452f4a 100644 --- a/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs +++ b/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs @@ -8,7 +8,8 @@ namespace Radarr.Http.Exceptions { } - public InvalidApiKeyException(string message) : base(message) + public InvalidApiKeyException(string message) + : base(message) { } } diff --git a/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs index 77befa3b1..66d255737 100644 --- a/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs @@ -18,12 +18,15 @@ namespace Radarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) { - if (context.Request.Method == "OPTIONS") return; + if (context.Request.Method == "OPTIONS") + { + return; + } if (_cacheableSpecification.IsCacheable(context)) { diff --git a/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs index 3d8804195..6e9d69a91 100644 --- a/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs @@ -51,7 +51,6 @@ namespace Radarr.Http.Extensions.Pipelines response.Contents = responseStream => _writeGZipStream(contents, responseStream); } } - catch (Exception ex) { _logger.Error(ex, "Unable to gzip response"); diff --git a/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs index bcd050d87..b61437333 100644 --- a/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs @@ -18,7 +18,7 @@ namespace Radarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } private Response Handle(NancyContext context) diff --git a/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs index c71c927b8..d991bd239 100644 --- a/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs @@ -11,7 +11,7 @@ namespace Radarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) diff --git a/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs b/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs index 9d7768a78..0eedb208e 100644 --- a/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs @@ -22,7 +22,7 @@ namespace Radarr.Http.Extensions.Pipelines { if (_urlBase.IsNotNullOrWhiteSpace()) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } } diff --git a/src/Radarr.Http/Extensions/ReqResExtensions.cs b/src/Radarr.Http/Extensions/ReqResExtensions.cs index 6326d907a..d0265a996 100644 --- a/src/Radarr.Http/Extensions/ReqResExtensions.cs +++ b/src/Radarr.Http/Extensions/ReqResExtensions.cs @@ -14,7 +14,8 @@ namespace Radarr.Http.Extensions public static readonly string LastModified = BuildInfo.BuildDateTime.ToString("r"); - public static T FromJson<T>(this Stream body) where T : class, new() + public static T FromJson<T>(this Stream body) + where T : class, new() { return FromJson<T>(body, typeof(T)); } diff --git a/src/Radarr.Http/Extensions/RequestExtensions.cs b/src/Radarr.Http/Extensions/RequestExtensions.cs index 593fa0d01..9c5e61532 100644 --- a/src/Radarr.Http/Extensions/RequestExtensions.cs +++ b/src/Radarr.Http/Extensions/RequestExtensions.cs @@ -22,9 +22,9 @@ namespace Radarr.Http.Extensions public static bool IsLocalRequest(this Request request) { - return (request.UserHostAddress.Equals("localhost") || + return request.UserHostAddress.Equals("localhost") || request.UserHostAddress.Equals("127.0.0.1") || - request.UserHostAddress.Equals("::1")); + request.UserHostAddress.Equals("::1"); } public static bool IsLoginRequest(this Request request) diff --git a/src/Radarr.Http/Frontend/CacheableSpecification.cs b/src/Radarr.Http/Frontend/CacheableSpecification.cs index 7ef86febe..7d0ca8b44 100644 --- a/src/Radarr.Http/Frontend/CacheableSpecification.cs +++ b/src/Radarr.Http/Frontend/CacheableSpecification.cs @@ -19,19 +19,40 @@ namespace Radarr.Http.Frontend return false; } - if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) return true; + if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) + { + return true; + } if (context.Request.Path.StartsWith("/api", StringComparison.CurrentCultureIgnoreCase)) { - if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) return true; + if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) + { + return true; + } return false; } - if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) return false; - if (context.Request.Path.EndsWith("index.js")) return false; - if (context.Request.Path.EndsWith("initialize.js")) return false; - if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) return false; + if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } + + if (context.Request.Path.EndsWith("index.js")) + { + return false; + } + + if (context.Request.Path.EndsWith("initialize.js")) + { + return false; + } + + if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } if (context.Request.Path.StartsWith("/log", StringComparison.CurrentCultureIgnoreCase) && context.Request.Path.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase)) @@ -41,7 +62,10 @@ namespace Radarr.Http.Frontend if (context.Response != null) { - if (context.Response.ContentType.Contains("text/html")) return false; + if (context.Response.ContentType.Contains("text/html")) + { + return false; + } } return true; diff --git a/src/Radarr.Http/Frontend/InitializeJsModule.cs b/src/Radarr.Http/Frontend/InitializeJsModule.cs index ae1fb6001..c049f223f 100644 --- a/src/Radarr.Http/Frontend/InitializeJsModule.cs +++ b/src/Radarr.Http/Frontend/InitializeJsModule.cs @@ -27,7 +27,7 @@ namespace Radarr.Http.Frontend _apiKey = configFileProvider.ApiKey; _urlBase = configFileProvider.UrlBase; - Get("/initialize.js", x => Index()); + Get("/initialize.js", x => Index()); } private Response Index() diff --git a/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs b/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs index 250aa695e..65efb2903 100644 --- a/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs +++ b/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs @@ -11,7 +11,7 @@ namespace Radarr.Http.Frontend.Mappers private readonly IAppFolderInfo _appFolderInfo; private readonly IConfigFileProvider _configFileProvider; - public FaviconMapper(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider,IConfigFileProvider configFileProvider, Logger logger) + public FaviconMapper(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider, IConfigFileProvider configFileProvider, Logger logger) : base(diskProvider, logger) { _appFolderInfo = appFolderInfo; diff --git a/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs b/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs index c844313f1..4c5252303 100644 --- a/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs +++ b/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs @@ -18,7 +18,8 @@ namespace Radarr.Http.Frontend.Mappers protected HtmlMapperBase(IDiskProvider diskProvider, Func<ICacheBreakerProvider> cacheBreakProviderFactory, - Logger logger) : base(diskProvider, logger) + Logger logger) + : base(diskProvider, logger) { _diskProvider = diskProvider; _cacheBreakProviderFactory = cacheBreakProviderFactory; @@ -65,7 +66,6 @@ namespace Radarr.Http.Frontend.Mappers { url = match.Groups["path"].Value; } - else { url = cacheBreakProvider.AddCacheBreakerToPath(match.Groups["path"].Value); diff --git a/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs b/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs index aa2edb49b..0bdc8c600 100644 --- a/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs +++ b/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs @@ -1,5 +1,4 @@ - -using Nancy; +using Nancy; namespace Radarr.Http.Frontend.Mappers { diff --git a/src/Radarr.Http/Frontend/StaticResourceModule.cs b/src/Radarr.Http/Frontend/StaticResourceModule.cs index 5661f6276..83c162551 100644 --- a/src/Radarr.Http/Frontend/StaticResourceModule.cs +++ b/src/Radarr.Http/Frontend/StaticResourceModule.cs @@ -12,14 +12,13 @@ namespace Radarr.Http.Frontend private readonly IEnumerable<IMapHttpRequestsToDisk> _requestMappers; private readonly Logger _logger; - public StaticResourceModule(IEnumerable<IMapHttpRequestsToDisk> requestMappers, Logger logger) { _requestMappers = requestMappers; _logger = logger; - Get("/{resource*}", x => Index()); - Get("/", x => Index()); + Get("/{resource*}", x => Index()); + Get("/", x => Index()); } private Response Index() diff --git a/src/Radarr.Http/Mapping/MappingValidation.cs b/src/Radarr.Http/Mapping/MappingValidation.cs index 67db3c70e..059866919 100644 --- a/src/Radarr.Http/Mapping/MappingValidation.cs +++ b/src/Radarr.Http/Mapping/MappingValidation.cs @@ -10,7 +10,7 @@ namespace Radarr.Http.Mapping { public static void ValidateMapping(Type modelType, Type resourceType) { - var errors = modelType.GetSimpleProperties().Where(c=>!c.GetGetMethod().IsStatic).Select(p => GetError(resourceType, p)).Where(c => c != null).ToList(); + var errors = modelType.GetSimpleProperties().Where(c => !c.GetGetMethod().IsStatic).Select(p => GetError(resourceType, p)).Where(c => c != null).ToList(); if (errors.Any()) { diff --git a/src/Radarr.Http/Mapping/ResourceMappingException.cs b/src/Radarr.Http/Mapping/ResourceMappingException.cs index 425a0299d..e200ae678 100644 --- a/src/Radarr.Http/Mapping/ResourceMappingException.cs +++ b/src/Radarr.Http/Mapping/ResourceMappingException.cs @@ -9,7 +9,6 @@ namespace Radarr.Http.Mapping public ResourceMappingException(IEnumerable<string> error) : base(Environment.NewLine + string.Join(Environment.NewLine, error.OrderBy(c => c))) { - } } } diff --git a/src/Radarr.Http/PagingResource.cs b/src/Radarr.Http/PagingResource.cs index 15a34e156..867ee6551 100644 --- a/src/Radarr.Http/PagingResource.cs +++ b/src/Radarr.Http/PagingResource.cs @@ -29,7 +29,7 @@ namespace Radarr.Http if (pagingResource.SortKey == null) { pagingSpec.SortKey = defaultSortKey; - if(pagingResource.SortDirection == SortDirection.Default) + if (pagingResource.SortDirection == SortDirection.Default) { pagingSpec.SortDirection = defaultSortDirection; } diff --git a/src/Radarr.Http/REST/ResourceValidator.cs b/src/Radarr.Http/REST/ResourceValidator.cs index 421fad93a..1c6ccd496 100644 --- a/src/Radarr.Http/REST/ResourceValidator.cs +++ b/src/Radarr.Http/REST/ResourceValidator.cs @@ -23,7 +23,6 @@ namespace Radarr.Http.REST private static object GetValue(object container, Func<TResource, IEnumerable<Field>> fieldListAccessor, string fieldName) { - var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName); if (resource == null) diff --git a/src/Radarr.Http/REST/RestModule.cs b/src/Radarr.Http/REST/RestModule.cs index 214742513..815363837 100644 --- a/src/Radarr.Http/REST/RestModule.cs +++ b/src/Radarr.Http/REST/RestModule.cs @@ -16,7 +16,7 @@ namespace Radarr.Http.REST private const string ROOT_ROUTE = "/"; private const string ID_ROUTE = @"/(?<id>[\d]{1,10})"; - private HashSet<string> EXCLUDED_KEYS = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) + private readonly HashSet<string> _excludedKeys = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "page", "pageSize", @@ -56,10 +56,12 @@ namespace Radarr.Http.REST SharedValidator = new ResourceValidator<TResource>(); } - private void ValidateModule() { - if (GetResourceById != null) return; + if (GetResourceById != null) + { + return; + } if (CreateResource != null || UpdateResource != null) { @@ -69,7 +71,11 @@ namespace Radarr.Http.REST protected Action<int> DeleteResource { - private get { return _deleteResource; } + private get + { + return _deleteResource; + } + set { _deleteResource = value; @@ -85,7 +91,11 @@ namespace Radarr.Http.REST protected Func<int, TResource> GetResourceById { - get { return _getResourceById; } + get + { + return _getResourceById; + } + set { _getResourceById = value; @@ -113,11 +123,14 @@ namespace Radarr.Http.REST protected Func<List<TResource>> GetResourceAll { - private get { return _getResourceAll; } + private get + { + return _getResourceAll; + } + set { _getResourceAll = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceAll(); @@ -128,11 +141,14 @@ namespace Radarr.Http.REST protected Func<PagingResource<TResource>, PagingResource<TResource>> GetResourcePaged { - private get { return _getResourcePaged; } + private get + { + return _getResourcePaged; + } + set { _getResourcePaged = value; - Get(ROOT_ROUTE, options => { var resource = GetResourcePaged(ReadPagingResourceFromRequest()); @@ -143,11 +159,14 @@ namespace Radarr.Http.REST protected Func<TResource> GetResourceSingle { - private get { return _getResourceSingle; } + private get + { + return _getResourceSingle; + } + set { _getResourceSingle = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceSingle(); @@ -158,7 +177,11 @@ namespace Radarr.Http.REST protected Func<TResource, int> CreateResource { - private get { return _createResource; } + private get + { + return _createResource; + } + set { _createResource = value; @@ -172,7 +195,11 @@ namespace Radarr.Http.REST protected Action<TResource> UpdateResource { - private get { return _updateResource; } + private get + { + return _updateResource; + } + set { _updateResource = value; @@ -182,7 +209,6 @@ namespace Radarr.Http.REST UpdateResource(resource); return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted); }); - Put(ID_ROUTE, options => { var resource = ReadResourceFromRequest(); @@ -239,12 +265,17 @@ namespace Radarr.Http.REST { int pageSize; int.TryParse(Request.Query.PageSize.ToString(), out pageSize); - if (pageSize == 0) pageSize = 10; + if (pageSize == 0) + { + pageSize = 10; + } int page; int.TryParse(Request.Query.Page.ToString(), out page); - if (page == 0) page = 1; - + if (page == 0) + { + page = 1; + } var pagingResource = new PagingResource<TResource> { @@ -280,9 +311,9 @@ namespace Radarr.Http.REST if (Request.Query.FilterKey != null) { var filter = new PagingResourceFilter - { - Key = Request.Query.FilterKey.ToString() - }; + { + Key = Request.Query.FilterKey.ToString() + }; if (Request.Query.FilterValue != null) { @@ -293,19 +324,18 @@ namespace Radarr.Http.REST } // v3 uses filters in key=value format - foreach (var key in Request.Query) { - if (EXCLUDED_KEYS.Contains(key)) + if (_excludedKeys.Contains(key)) { continue; } pagingResource.Filters.Add(new PagingResourceFilter - { - Key = key, - Value = Request.Query[key] - }); + { + Key = key, + Value = Request.Query[key] + }); } return pagingResource; diff --git a/src/Radarr.Http/RadarrBootstrapper.cs b/src/Radarr.Http/RadarrBootstrapper.cs index 15b25cfcb..c6d5f7e8b 100644 --- a/src/Radarr.Http/RadarrBootstrapper.cs +++ b/src/Radarr.Http/RadarrBootstrapper.cs @@ -57,7 +57,8 @@ namespace Radarr.Http get { // We don't support Xml Serialization atm - return NancyInternalConfiguration.WithOverrides(x => { + return NancyInternalConfiguration.WithOverrides(x => + { x.ResponseProcessors.Remove(typeof(ViewProcessor)); x.ResponseProcessors.Remove(typeof(XmlProcessor)); }); diff --git a/src/Radarr.Http/RadarrRestModule.cs b/src/Radarr.Http/RadarrRestModule.cs index f1f36c6cb..e351314b5 100644 --- a/src/Radarr.Http/RadarrRestModule.cs +++ b/src/Radarr.Http/RadarrRestModule.cs @@ -5,11 +5,11 @@ using Radarr.Http.Validation; namespace Radarr.Http { - public abstract class RadarrRestModule<TResource> : RestModule<TResource> where TResource : RestResource, new() + public abstract class RadarrRestModule<TResource> : RestModule<TResource> + where TResource : RestResource, new() { protected string Resource { get; private set; } - private static string BaseUrl() { var isV3 = typeof(TResource).Namespace.Contains(".V3."); @@ -17,6 +17,7 @@ namespace Radarr.Http { return "/api/v3/"; } + return "/api/"; } diff --git a/src/Radarr.Http/RadarrRestModuleWithSignalR.cs b/src/Radarr.Http/RadarrRestModuleWithSignalR.cs index b67127ab3..67b6bec60 100644 --- a/src/Radarr.Http/RadarrRestModuleWithSignalR.cs +++ b/src/Radarr.Http/RadarrRestModuleWithSignalR.cs @@ -25,7 +25,10 @@ namespace Radarr.Http public void Handle(ModelEvent<TModel> message) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (message.Action == ModelAction.Deleted || message.Action == ModelAction.Sync) { @@ -37,11 +40,14 @@ namespace Radarr.Http protected void BroadcastResourceChange(ModelAction action, int id) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (action == ModelAction.Deleted) { - BroadcastResourceChange(action, new TResource {Id = id}); + BroadcastResourceChange(action, new TResource { Id = id }); } else { @@ -52,16 +58,19 @@ namespace Radarr.Http protected void BroadcastResourceChange(ModelAction action, TResource resource) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { var signalRMessage = new SignalRMessage - { - Name = Resource, - Body = new ResourceChangeMessage<TResource>(resource, action), - Action = action - }; + { + Name = Resource, + Body = new ResourceChangeMessage<TResource>(resource, action), + Action = action + }; _signalRBroadcaster.BroadcastMessage(signalRMessage); } @@ -69,16 +78,19 @@ namespace Radarr.Http protected void BroadcastResourceChange(ModelAction action) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { var signalRMessage = new SignalRMessage - { - Name = Resource, - Body = new ResourceChangeMessage<TResource>(action), - Action = action - }; + { + Name = Resource, + Body = new ResourceChangeMessage<TResource>(action), + Action = action + }; _signalRBroadcaster.BroadcastMessage(signalRMessage); } diff --git a/src/Radarr.Http/ResourceChangeMessage.cs b/src/Radarr.Http/ResourceChangeMessage.cs index 29aabc6b6..03b88fc11 100644 --- a/src/Radarr.Http/ResourceChangeMessage.cs +++ b/src/Radarr.Http/ResourceChangeMessage.cs @@ -4,7 +4,8 @@ using Radarr.Http.REST; namespace Radarr.Http { - public class ResourceChangeMessage<TResource> where TResource : RestResource + public class ResourceChangeMessage<TResource> + where TResource : RestResource { public TResource Resource { get; private set; } public ModelAction Action { get; private set; } @@ -25,5 +26,4 @@ namespace Radarr.Http Action = action; } } - } diff --git a/src/Radarr.Http/TinyIoCNancyBootstrapper.cs b/src/Radarr.Http/TinyIoCNancyBootstrapper.cs index ed9bdf89f..22506f309 100644 --- a/src/Radarr.Http/TinyIoCNancyBootstrapper.cs +++ b/src/Radarr.Http/TinyIoCNancyBootstrapper.cs @@ -1,17 +1,17 @@ -using TinyIoC; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy; -using Nancy.Diagnostics; using Nancy.Bootstrapper; using Nancy.Configuration; +using Nancy.Diagnostics; +using TinyIoC; + +#pragma warning disable SX1101 namespace Radarr.Http { - - /// <summary> /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behaviour can be overridden if required. @@ -53,42 +53,32 @@ namespace Radarr.Http return this.ApplicationContainer.Resolve<INancyEngine>(); } - // - // Summary: - // Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. - // - // Returns: - // An Nancy.Configuration.INancyEnvironmentConfigurator instance. + /// <summary></summary> + /// Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. + /// </summary> + /// <returns>An Nancy.Configuration.INancyEnvironmentConfigurator instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } - // - // Summary: - // Get the Nancy.Configuration.INancyEnvironment instance. - // - // Returns: - // An configured Nancy.Configuration.INancyEnvironment instance. - // - // Remarks: - // The boostrapper must be initialised (Nancy.Bootstrapper.INancyBootstrapper.Initialise) - // prior to calling this. + /// <summary> + /// Get the Nancy.Configuration.INancyEnvironment instance. + /// </summary> + /// <returns>An configured Nancy.Configuration.INancyEnvironment instance.</returns> + /// <remarks> + /// The boostrapper must be initialised (Nancy.Bootstrapper.INancyBootstrapper.Initialise) prior to calling this. + /// </remarks> public override INancyEnvironment GetEnvironment() { return this.ApplicationContainer.Resolve<INancyEnvironment>(); } - // - // Summary: - // Registers an Nancy.Configuration.INancyEnvironment instance in the container. - // - // Parameters: - // container: - // The container to register into. - // - // environment: - // The Nancy.Configuration.INancyEnvironment instance to register. + /// <summary> + /// Registers an Nancy.Configuration.INancyEnvironment instance in the container. + /// </summary> + /// <param name="container">The container to register into.</param> + /// <param name="environment">The Nancy.Configuration.INancyEnvironment instance to register.</param> protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment) { ApplicationContainer.Register<INancyEnvironment>(environment); diff --git a/src/Radarr.Http/Validation/EmptyCollectionValidator.cs b/src/Radarr.Http/Validation/EmptyCollectionValidator.cs index 1ebd9ed51..835832618 100644 --- a/src/Radarr.Http/Validation/EmptyCollectionValidator.cs +++ b/src/Radarr.Http/Validation/EmptyCollectionValidator.cs @@ -13,7 +13,10 @@ namespace Radarr.Http.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var collection = context.PropertyValue as IEnumerable<T>; diff --git a/src/ServiceHelpers/ServiceInstall/Program.cs b/src/ServiceHelpers/ServiceInstall/Program.cs index 02938247b..2cd9e7f37 100644 --- a/src/ServiceHelpers/ServiceInstall/Program.cs +++ b/src/ServiceHelpers/ServiceInstall/Program.cs @@ -2,7 +2,7 @@ { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/i"); } diff --git a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs index 2b8fa682b..a651ae317 100644 --- a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs @@ -31,18 +31,18 @@ namespace ServiceInstall } var startInfo = new ProcessStartInfo - { - FileName = RadarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = RadarrExe, + Arguments = arg, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); @@ -50,13 +50,11 @@ namespace ServiceInstall process.BeginOutputReadLine(); process.WaitForExit(); - } private static void OnDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } - } } diff --git a/src/ServiceHelpers/ServiceUninstall/Program.cs b/src/ServiceHelpers/ServiceUninstall/Program.cs index c8bc4f181..f57066bb7 100644 --- a/src/ServiceHelpers/ServiceUninstall/Program.cs +++ b/src/ServiceHelpers/ServiceUninstall/Program.cs @@ -2,7 +2,7 @@ { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/u"); } diff --git a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs index 22e08424f..174a79ffd 100644 --- a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs @@ -31,18 +31,18 @@ namespace ServiceUninstall } var startInfo = new ProcessStartInfo - { - FileName = RadarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = RadarrExe, + Arguments = arg, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); @@ -50,13 +50,11 @@ namespace ServiceUninstall process.BeginOutputReadLine(); process.WaitForExit(); - } private static void OnDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } - } } diff --git a/src/Stylecop.ruleset b/src/Stylecop.ruleset new file mode 100644 index 000000000..2cc451f2d --- /dev/null +++ b/src/Stylecop.ruleset @@ -0,0 +1,115 @@ +<RuleSet Name="Stylecop.ruleset" Description="Rules for Radarr" ToolsVersion="15.0"> + <Rules AnalyzerId="StyleCop.CSharp.SpecialRules" + RuleNamespace="StyleCop.CSharp.SpecialRules"> + <Rule Id="SA0001" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.SpacingRules" + RuleNamespace="StyleCop.CSharp.SpacingRules"> + <Rule Id="SA1005" Action="None" /> + <Rule Id="SA1025" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.ReadabilityRules" + RuleNamespace="StyleCop.CSharp.ReadabilityRules"> + <Rule Id="SA1101" Action="None" /> + <Rule Id="SA1116" Action="None" /> + <Rule Id="SA1118" Action="None" /> + <Rule Id="SA1122" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.OrderingRules" + RuleNamespace="StyleCop.CSharp.OrderingRules"> + <Rule Id="SA1201" Action="Info" /> + <Rule Id="SA1202" Action="Info" /> + <Rule Id="SA1204" Action="Info" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.NamingRules" + RuleNamespace="StyleCop.CSharp.NamingRules"> + <Rule Id="SA1300" Action="None" /> + <Rule Id="SA1301" Action="None" /> + <Rule Id="SA1303" Action="None" /> + <Rule Id="SA1304" Action="None" /> + <Rule Id="SA1306" Action="None" /> + <Rule Id="SA1309" Action="None" /> + <Rule Id="SA1310" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.MaintainabilityRules" + RuleNamespace="StyleCop.CSharp.MaintainabilityRules"> + <Rule Id="SA1400" Action="Warning" /> + <Rule Id="SA1401" Action="None" /> + <Rule Id="SA1402" Action="None" /> + <Rule Id="SA1404" Action="Info" /> + <Rule Id="SA1405" Action="Info" /> + <Rule Id="SA1406" Action="Info" /> + <Rule Id="SA1409" Action="Info" /> + <Rule Id="SA1410" Action="Info" /> + <Rule Id="SA1411" Action="Info" /> + <Rule Id="SA1412" Action="None" /> + <Rule Id="SA1413" Action="None" /> + <Rule Id="SA1414" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.LayoutRules" + RuleNamespace="StyleCop.CSharp.LayoutRules"> + <Rule Id="SA1516" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.DocumentationRules" + RuleNamespace="StyleCop.CSharp.DocumentationRules"> + <Rule Id="SA1600" Action="None" /> + <Rule Id="SA1601" Action="None" /> + <Rule Id="SA1602" Action="None" /> + <Rule Id="SA1603" Action="None" /> + <Rule Id="SA1604" Action="None" /> + <Rule Id="SA1605" Action="None" /> + <Rule Id="SA1606" Action="None" /> + <Rule Id="SA1607" Action="None" /> + <Rule Id="SA1608" Action="None" /> + <Rule Id="SA1609" Action="None" /> + <Rule Id="SA1610" Action="None" /> + <Rule Id="SA1611" Action="None" /> + <Rule Id="SA1612" Action="None" /> + <Rule Id="SA1613" Action="None" /> + <Rule Id="SA1614" Action="None" /> + <Rule Id="SA1615" Action="None" /> + <Rule Id="SA1616" Action="None" /> + <Rule Id="SA1617" Action="None" /> + <Rule Id="SA1618" Action="None" /> + <Rule Id="SA1619" Action="None" /> + <Rule Id="SA1620" Action="None" /> + <Rule Id="SA1621" Action="None" /> + <Rule Id="SA1622" Action="None" /> + <Rule Id="SA1623" Action="None" /> + <Rule Id="SA1624" Action="None" /> + <Rule Id="SA1625" Action="None" /> + <Rule Id="SA1626" Action="None" /> + <Rule Id="SA1627" Action="None" /> + <Rule Id="SA1628" Action="None" /> + <Rule Id="SA1629" Action="None" /> + <Rule Id="SA1630" Action="None" /> + <Rule Id="SA1631" Action="None" /> + <Rule Id="SA1632" Action="None" /> + <Rule Id="SA1633" Action="None" /> + <Rule Id="SA1634" Action="None" /> + <Rule Id="SA1635" Action="None" /> + <Rule Id="SA1636" Action="None" /> + <Rule Id="SA1637" Action="None" /> + <Rule Id="SA1638" Action="None" /> + <Rule Id="SA1639" Action="None" /> + <Rule Id="SA1640" Action="None" /> + <Rule Id="SA1641" Action="None" /> + <Rule Id="SA1642" Action="None" /> + <Rule Id="SA1643" Action="None" /> + <Rule Id="SA1644" Action="None" /> + <Rule Id="SA1645" Action="None" /> + <Rule Id="SA1646" Action="None" /> + <Rule Id="SA1647" Action="None" /> + <Rule Id="SA1648" Action="None" /> + <Rule Id="SA1649" Action="None" /> + <Rule Id="SA1650" Action="None" /> + <Rule Id="SA1651" Action="None" /> + <Rule Id="SA1652" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.AlternativeRules" + RuleNamespace="StyleCop.CSharp.AlternativeRules"> + <!-- Do not prefix local members with this --> + <Rule Id="SX1101" Action="Warning" /> + <Rule Id="SX1309" Action="Warning" /> + </Rules> +</RuleSet> diff --git a/src/stylecop.json b/src/stylecop.json new file mode 100644 index 000000000..b4321a13b --- /dev/null +++ b/src/stylecop.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "xmlHeader": false, + "documentInterfaces": false, + "documentInternalElements": false + }, + "indentation": { + "indentationSize": 4, + "useTabs": false + }, + "layoutRules": { + "newlineAtEndOfFile": "require" + }, + "orderingRules": { + "systemUsingDirectivesFirst": true, + "usingDirectivesPlacement": "outsideNamespace" + } + } +}