Reformat and apply Stylecop rules

This commit is contained in:
ta264 2019-12-22 22:08:53 +00:00 committed by Qstick
parent d4fa9b7345
commit f02fa629cc
1186 changed files with 7105 additions and 5616 deletions

View file

@ -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

1
.gitignore vendored
View file

@ -85,7 +85,6 @@ TestResults
[Tt]est[Rr]esult*
*.Cache
ClientBin
[Ss]tyle[Cc]op.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects

View file

@ -2,7 +2,7 @@
<!-- Common to all Radarr Projects -->
<PropertyGroup>
<CodeAnalysisRuleSet>$(SolutionDir)Stylecop.ruleset</CodeAnalysisRuleSet>
<!-- <TreatWarningsAsErrors>true</TreatWarningsAsErrors> -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<PlatformTarget>AnyCPU</PlatformTarget>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
@ -94,7 +94,7 @@
</ItemGroup>
<!-- Set up stylecop -->
<ItemGroup Condition="'$(RadarrProject)'=='true' and '$(RadarrOutputType)'!='Test'">
<ItemGroup Condition="'$(RadarrProject)'=='true'">
<!-- StyleCop analysis -->
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>

View file

@ -45,7 +45,7 @@ public object FromDB(ConverterContext context)
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)

View file

@ -50,4 +50,3 @@ public object ToDB(object clrValue)
#endregion
}
}

View file

@ -29,7 +29,7 @@ internal static class DataHelper
{
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;

View file

@ -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; }

View file

@ -167,7 +167,7 @@ private object GetRightValue(Expression expression)
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);
}

View file

@ -99,7 +99,7 @@ public override int LengthInBytes()
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 @@ public void Add(BEncodedValue item)
this.list.Add(item);
}
public void AddRange (IEnumerable<BEncodedValue> collection)
public void AddRange(IEnumerable<BEncodedValue> collection)
{
list.AddRange (collection);
list.AddRange(collection);
}
public void Clear()

View file

@ -101,16 +101,16 @@ internal override void DecodeInternal(RawReader reader)
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.");

View file

@ -97,7 +97,7 @@ public static implicit operator BEncodedString(byte[] value)
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 @@ public override int LengthInBytes()
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 @@ public int CompareTo(BEncodedString other)
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++)

View file

@ -32,11 +32,11 @@ public byte[] Encode()
/// <returns></returns>
public abstract int Encode(byte[] buffer, int offset);
public static T Clone <T> (T value)
public static T Clone<T>(T value)
where T : BEncodedValue
{
Check.Value (value);
return (T) BEncodedValue.Decode (value.Encode ());
Check.Value(value);
return (T)BEncodedValue.Decode(value.Encode());
}
/// <summary>

View file

@ -394,7 +394,7 @@ void Validate()
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
count += (((v + (v >> 4) & 0xF0F0F0F) * 0x1010101)) >> 24;
}
this.trueCount = (int)count ;
this.trueCount = (int)count;
}
void ZeroUnusedBits()

View file

@ -62,9 +62,9 @@ public static void Data(object data)
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 @@ public static void InfoHash(object infoHash)
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 @@ public static void Manager(object manager)
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 @@ public static void Metadata(object metadata)
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 @@ public static void Path(object path)
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 @@ public static void PathNotEmpty(string path)
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)

View file

@ -4,7 +4,7 @@
namespace MonoTorrent
{
public class InfoHash : IEquatable <InfoHash>
public class InfoHash : IEquatable<InfoHash>
{
static Dictionary<char, byte> base32DecodeTable;
@ -97,24 +97,25 @@ public string UrlEncode()
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 @@ public static InfoHash FromBase32(string infoHash)
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");

View file

@ -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<string> Webseeds {
get; private set;
}
public MagnetLink (string url)
public RawTrackerTier AnnounceUrls
{
Check.Url (url);
AnnounceUrls = new RawTrackerTier ();
Webseeds = new List<string> ();
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<string> Webseeds
{
get; private set;
}
public MagnetLink(string url)
{
Check.Url(url);
AnnounceUrls = new RawTrackerTier();
Webseeds = new List<string>();
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;
}
}
}

View file

@ -2,7 +2,7 @@ namespace MonoTorrent.Messages
{
interface IMessage
{
int ByteLength { get;}
int ByteLength { get; }
byte[] Encode();
int Encode(byte[] buffer, int offset);

View file

@ -7,90 +7,94 @@ namespace MonoTorrent
{
public class RawTrackerTier : IList<string>
{
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<string> announces)
: this ()
public RawTrackerTier(IEnumerable<string> 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<string> GetEnumerator ()
public IEnumerator<string> GetEnumerator()
{
foreach (BEncodedString v in Tier)
yield return v.Text;
}
IEnumerator IEnumerable.GetEnumerator ()
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator ();
return GetEnumerator();
}
}
}

View file

@ -7,98 +7,103 @@ namespace MonoTorrent
{
public class RawTrackerTiers : IList<RawTrackerTier>
{
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<RawTrackerTier> tiers)
public void Add(RawTrackerTier item)
{
Tiers.Add(item.Tier);
}
public void AddRange(IEnumerable<RawTrackerTier> 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<RawTrackerTier> GetEnumerator ()
public IEnumerator<RawTrackerTier> 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();
}
}
}

View file

@ -36,7 +36,8 @@ public static void RaiseAsyncEvent<T>(EventHandler<T> e, object o, T args)
if (e == null)
return;
ThreadPool.QueueUserWorkItem(delegate {
ThreadPool.QueueUserWorkItem(delegate
{
if (e != null)
e(o, args);
});

View file

@ -263,7 +263,7 @@ public List<string> GetRightHttpSeeds
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 @@ public override int GetHashCode()
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 @@ private void LoadTorrentFiles(BEncodedList list)
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 @@ private static Torrent Load(Stream stream, string path)
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 @@ private static Torrent Load(Stream stream, string path)
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 @@ protected void LoadInternal(BEncodedDictionary torrentInformation)
// 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 @@ protected void LoadInternal(BEncodedDictionary torrentInformation)
case ("info"):
using (SHA1 s = HashAlgoFactory.Create<SHA1>())
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 @@ protected void LoadInternal(BEncodedDictionary torrentInformation)
Toolbox.Randomize<string>(tier);
RawTrackerTier collection = new RawTrackerTier ();
RawTrackerTier collection = new RawTrackerTier();
for (int k = 0; k < tier.Count; k++)
collection.Add(tier[k]);

View file

@ -125,14 +125,14 @@ public TorrentFile(string path, long length)
}
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)
{
}

View file

@ -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 <byte> ();
var bytes = new List<byte>();
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 @@ static int GetChar (string str, int offset, int length)
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 @@ static int GetInt (byte b)
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<byte> buf, char ch, Encoding e)
static void WriteCharBytes(List<byte> 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);
}
}
}

View file

@ -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 @@ public void should_return_field_for_every_property()
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")]

View file

@ -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 @@ public static class BlacklistResourceMapper
{
public static BlacklistResource MapToResource(this Core.Blacklisting.Blacklist model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new BlacklistResource
{

View file

@ -1,4 +1,3 @@
using Nancy;
using System;
using System.Collections.Generic;
using System.Linq;
@ -6,10 +5,11 @@
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 @@ public CalendarFeedModule(IMovieService movieService, ITagService tagService)
_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 @@ private object GetCalendarFeed()
var start = DateTime.Today.AddDays(-pastDays);
var end = DateTime.Today.AddDays(futureDays);
var unmonitored = false;
//var premiersOnly = false;
var tags = new List<int>();
@ -45,11 +46,19 @@ private object GetCalendarFeed()
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 @@ private object GetCalendarFeed()
//{
// premiersOnly = bool.Parse(queryPremiersOnly.Value);
//}
if (queryTags.HasValue)
{
var tagInput = (string)queryTags.Value.ToString();
@ -98,10 +106,9 @@ private object GetCalendarFeed()
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");

View file

@ -20,7 +20,6 @@ public CalendarModule(IBroadcastSignalRMessage signalR,
IMapCoversToLocal coverMapper)
: base(signalR, "calendar")
{
_moviesService = moviesService;
_coverMapper = coverMapper;
@ -37,9 +36,20 @@ private List<MovieResource> GetCalendar()
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 @@ private List<MovieResource> GetCalendar()
protected MovieResource MapToResource(Movie movie)
{
if (movie == null) return null;
if (movie == null)
{
return null;
}
var resource = movie.ToResource();

View file

@ -2,8 +2,6 @@
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.ProgressMessaging;
using NzbDrone.SignalR;
using Radarr.Http;
using Radarr.Http.Extensions;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Commands
{

View file

@ -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 @@ public class CommandResource : RestResource
//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 @@ public DateTime? StateChangeTime
{
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 @@ public static class CommandResourceMapper
{
public static CommandResource ToResource(this CommandModel model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new CommandResource
{

View file

@ -7,7 +7,6 @@ public class DownloadClientConfigModule : NzbDroneConfigModule<DownloadClientCon
public DownloadClientConfigModule(IConfigService configService)
: base(configService)
{
}
protected override DownloadClientConfigResource ToResource(IConfigService model)

View file

@ -1,5 +1,5 @@
using Radarr.Http.REST;
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{

View file

@ -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 @@ public static HostConfigResource ToResource(this IConfigFileProvider model, ICon
LaunchBrowser = model.LaunchBrowser,
AuthenticationMethod = model.AuthenticationMethod,
AnalyticsEnabled = model.AnalyticsEnabled,
//Username
//Password
LogLevel = model.LogLevel,

View file

@ -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<IndexerConfigResource>
{
public IndexerConfigModule(IConfigService configService)
: base(configService)
{

View file

@ -1,6 +1,6 @@
using Radarr.Http.REST;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Parser;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{

View file

@ -1,6 +1,6 @@
using Radarr.Http.REST;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.MediaFiles;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{

View file

@ -2,9 +2,9 @@
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 @@ public NamingConfigModule(INamingConfigService namingConfigService,
GetResourceById = GetNamingConfig;
UpdateResource = UpdateNamingConfig;
Get("/samples", x => GetExamples(this.Bind<NamingConfigResource>()));
Get("/samples", x => GetExamples(this.Bind<NamingConfigResource>()));
SharedValidator.RuleFor(c => c.MultiEpisodeStyle).InclusiveBetween(0, 5);
SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat();
@ -87,11 +87,9 @@ private void ValidateFormatResult(NamingConfig nameSpec)
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<ValidationFailure>();
//validationFailures.AddIfNotNull(standardMovieValidationResult);
if (validationFailures.Any())
{
throw new ValidationException(validationFailures.DistinctBy(v => v.PropertyName).ToArray());

View file

@ -1,5 +1,5 @@
using Radarr.Http.REST;
using NzbDrone.Core.Organizer;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
@ -33,6 +33,7 @@ public static NamingConfigResource ToResource(this NamingConfig model)
MultiEpisodeStyle = model.MultiEpisodeStyle,
StandardMovieFormat = model.StandardMovieFormat,
MovieFolderFormat = model.MovieFolderFormat
//IncludeSeriesTitle
//IncludeEpisodeTitle
//IncludeQuality

View file

@ -1,11 +1,10 @@
using Radarr.Http.Validation;
using NzbDrone.Core.Configuration;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Config
{
public class NetImportConfigModule : NzbDroneConfigModule<NetImportConfigResource>
{
public NetImportConfigModule(IConfigService configService)
: base(configService)
{

View file

@ -1,5 +1,5 @@
using Radarr.Http.REST;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{

View file

@ -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<TResource> : RadarrRestModule<TResource> where TResource : RestResource, new()
public abstract class NzbDroneConfigModule<TResource> : RadarrRestModule<TResource>
where TResource : RestResource, new()
{
private readonly IConfigService _configService;
@ -15,8 +16,8 @@ protected NzbDroneConfigModule(IConfigService configService)
{
}
protected NzbDroneConfigModule(string resource, IConfigService configService) :
base("config/" + resource.Trim('/'))
protected NzbDroneConfigModule(string resource, IConfigService configService)
: base("config/" + resource.Trim('/'))
{
_configService = configService;

View file

@ -7,7 +7,6 @@ public class UiConfigModule : NzbDroneConfigModule<UiConfigResource>
public UiConfigModule(IConfigService configService)
: base(configService)
{
}
protected override UiConfigResource ToResource(IConfigService model)

View file

@ -1,5 +1,5 @@
using Radarr.Http.REST;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{

View file

@ -4,7 +4,7 @@
namespace NzbDrone.Api.DiskSpace
{
public class DiskSpaceModule :RadarrRestModule<DiskSpaceResource>
public class DiskSpaceModule : RadarrRestModule<DiskSpaceResource>
{
private readonly IDiskSpaceService _diskSpaceService;
@ -15,7 +15,6 @@ public DiskSpaceModule(IDiskSpaceService diskSpaceService)
GetResourceAll = GetFreeSpace;
}
public List<DiskSpaceResource> GetFreeSpace()
{
return _diskSpaceService.GetFreeSpace().ConvertAll(DiskSpaceResourceMapper.MapToResource);

View file

@ -14,7 +14,10 @@ public static class DiskSpaceResourceMapper
{
public static DiskSpaceResource MapToResource(this Core.DiskSpace.DiskSpace model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new DiskSpaceResource
{

View file

@ -29,7 +29,11 @@ protected override void MapToModel(DownloadClientDefinition definition, Download
protected override void Validate(DownloadClientDefinition definition, bool includeWarnings)
{
if (!definition.Enable) return;
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}

View file

@ -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
{

View file

@ -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 @@ public static class ExtraFileResourceMapper
{
public static ExtraFileResource ToResource(this MetadataFile model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new ExtraFileResource
{
@ -36,7 +39,10 @@ public static ExtraFileResource ToResource(this MetadataFile model)
public static ExtraFileResource ToResource(this SubtitleFile model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new ExtraFileResource
{
@ -51,7 +57,10 @@ public static ExtraFileResource ToResource(this SubtitleFile model)
public static ExtraFileResource ToResource(this OtherExtraFile model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new ExtraFileResource
{
@ -78,6 +87,5 @@ public static List<ExtraFileResource> ToResource(this IEnumerable<OtherExtraFile
{
return movies.Select(ToResource).ToList();
}
}
}

View file

@ -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 @@ public FileSystemModule(IFileSystemLookupService fileSystemLookupService,
_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 @@ private object GetMediaFiles()
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)

View file

@ -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 @@ public static class HealthResourceMapper
{
public static HealthResource ToResource(this HealthCheck model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new HealthResource
{

View file

@ -3,10 +3,10 @@
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 @@ public HistoryModule(IHistoryService historyService,
_failedDownloadService = failedDownloadService;
GetResourcePaged = GetHistory;
Post("/failed", x => MarkAsFailed());
Post("/failed", x => MarkAsFailed());
}
protected HistoryResource MapToResource(Core.History.History model)

View file

@ -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 @@ public static class HistoryResourceMapper
{
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 @@ public static HistoryResource ToResource(this Core.History.History model)
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
};
}
}

View file

@ -31,7 +31,11 @@ protected override void MapToModel(IndexerDefinition definition, IndexerResource
protected override void Validate(IndexerDefinition definition, bool includeWarnings)
{
if (!definition.Enable) return;
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}

View file

@ -2,15 +2,15 @@
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 @@ public ReleaseModule(IFetchAndParseRss rssFetcherAndParser,
_logger = logger;
GetResourceAll = GetReleases;
Post("/", x => DownloadRelease(this.Bind<ReleaseResource>()));
Post("/", x => DownloadRelease(this.Bind<ReleaseResource>()));
//PostValidator.RuleFor(s => s.DownloadAllowed).Equal(true);
PostValidator.RuleFor(s => s.Guid).NotEmpty();
@ -60,6 +60,7 @@ private object DownloadRelease(ReleaseResource release)
return new NotFoundResponse();
}
try
{
_downloadService.DownloadReport(remoteMovie);
@ -115,10 +116,9 @@ private List<ReleaseResource> GetRss()
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);
}
}
}

View file

@ -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 @@ public ReleasePushModule(IMakeDownloadDecision downloadDecisionMaker,
_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();

View file

@ -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 @@ public class ReleaseResource : RestResource
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 @@ public static ReleaseResource ToResource(this DownloadDecision model)
DownloadUrl = releaseInfo.DownloadUrl,
InfoUrl = releaseInfo.InfoUrl,
MappingResult = mappingResult,
//ReleaseWeight
//ReleaseWeight
SuspectedMovieId = movieId,
MagnetUrl = torrentInfo.MagnetUrl,
@ -136,7 +135,6 @@ public static ReleaseResource ToResource(this DownloadDecision model)
//Special = parsedMovieInfo.Special,
};
}
public static ReleaseInfo ToModel(this ReleaseResource resource)

View file

@ -26,7 +26,7 @@ public LogFileModuleBase(IDiskProvider diskProvider,
_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 @@ private object GetLogFileResponse(string filename)
var filePath = GetLogFilePath(filename);
if (!_diskProvider.FileExists(filePath))
{
return new NotFoundResponse();
}
var data = _diskProvider.ReadAllText(filePath);

View file

@ -17,7 +17,10 @@ public static class LogResourceMapper
{
public static LogResource ToResource(this Core.Instrumentation.Log model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new LogResource
{

View file

@ -25,7 +25,10 @@ public UpdateLogFileModule(IAppFolderInfo appFolderInfo,
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))

View file

@ -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 @@ public static class ManualImportResourceMapper
{
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 @@ public static ManualImportResource ToResource(this Core.MediaFiles.MovieImport.M
Size = model.Size,
Movie = model.Movie.ToResource(),
Quality = model.Quality,
//QualityWeight
DownloadId = model.DownloadId,
Rejections = model.Rejections

View file

@ -10,19 +10,19 @@ namespace NzbDrone.Api.MediaCovers
{
public class MediaCoverModule : NzbDroneApiModule
{
private const string MEDIA_COVER_ROUTE = @"/(?<movieId>\d+)/(?<filename>(.+)\.(jpg|png|gif))";
private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private const string MEDIA_COVER_ROUTE = @"/(?<seriesId>\d+)/(?<filename>(.+)\.(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 @@ private object GetMediaCover(int seriesId, string filename)
{
return new NotFoundResponse();
}
filePath = basefilePath;
}

View file

@ -25,7 +25,11 @@ protected override void MapToModel(MetadataDefinition definition, MetadataResour
protected override void Validate(MetadataDefinition definition, bool includeWarnings)
{
if (!definition.Enable) return;
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}

View file

@ -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 @@ private MovieFileResource GetMovieFile(int id)
return movie.ToResource();
}
private void SetQuality(MovieFileResource movieFileResource)
{
var movieFile = _mediaFileService.GetMovie(movieFileResource.Id);

View file

@ -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 @@ public class MovieFileResource : RestResource
{
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 @@ public static class MovieFileResourceMapper
{
public static MovieFileResource ToResource(this MovieFile model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
MovieResource movie = null;
@ -69,11 +70,13 @@ public static MovieFileResource ToResource(this MovieFile model)
public static MovieFile ToModel(this MovieFileResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new MovieFile
{
};
}

View file

@ -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;

View file

@ -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 @@ public class AlternativeTitleResource : RestResource
{
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 @@ public static class AlternativeTitleResourceMapper
{
public static AlternativeTitleResource ToResource(this AlternativeTitle model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new AlternativeTitleResource
{
@ -50,7 +51,10 @@ public static AlternativeTitleResource ToResource(this AlternativeTitle model)
public static AlternativeTitle ToModel(this AlternativeTitleResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new AlternativeTitle
{

View file

@ -6,13 +6,11 @@ public class AlternativeYearResource : RestResource
{
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; }

View file

@ -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 @@ public FetchMovieListModule(IFetchNetImport netImport, ISearchForNewMovie 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<Core.Movies.Movie> realResults = new List<Core.Movies.Movie>();
@ -41,7 +40,6 @@ private object Search()
return MapToResource(results);
}
private static IEnumerable<MovieResource> MapToResource(IEnumerable<Core.Movies.Movie> movies)
{
foreach (var currentSeries in movies)

View file

@ -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<UnmappedFolder>
{
public int Compare(UnmappedFolder a, UnmappedFolder b)
@ -37,10 +36,14 @@ public class MovieBulkImportModule : RadarrRestModule<MovieResource>
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 @@ public MovieBulkImportModule(ISearchForNewMovie searchProxy, IRootFolderService
_movieService = movieService;
_profileService = profileService;
_parsingService = parsingService;
Get("/", x => Search());
Get("/", x => Search());
}
private object Search()
{
if (Request.Query.Id == 0)
@ -84,7 +86,7 @@ private object Search()
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 @@ private object Search()
};
}
private static IEnumerable<MovieResource> MapToResource(IEnumerable<Core.Movies.Movie> movies)
{
foreach (var currentMovie in movies)

View file

@ -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 @@ public MovieDiscoverModule(IDiscoverNewMovies searchProxy, INetImportFactory net
{
_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 @@ private object GetLists()
{
var lists = _netImportFactory.Discoverable();
return lists.Select(definition => {
return lists.Select(definition =>
{
var resource = new NetImportResource();
resource.Id = definition.Definition.Id;

View file

@ -2,8 +2,8 @@
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 @@ public MovieEditorModule(IMovieService movieService)
: 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<List<MovieResource>>();
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 @@ private object DeleteSelected()
{
deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value);
}
if (addExclusionQuery.HasValue)
{
addExclusion = Convert.ToBoolean(addExclusionQuery.Value);
}
var ids = Request.Body.FromJson<List<int>>();
foreach (var id in ids)

View file

@ -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 @@ public MovieLookupModule(ISearchForNewMovie searchProxy, IProvideMovieInfo movie
{
_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();

View file

@ -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.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 @@ public class MovieModule : RadarrRestModuleWithSignalR<MovieResource, Movie>,
IHandle<MovieDeletedEvent>,
IHandle<MovieRenamedEvent>,
IHandle<MediaCoversUpdatedEvent>
{
private const string TITLE_SLUG_ROUTE = "/titleslug/(?<slug>[^/]+)";
protected readonly IMovieService _moviesService;
private readonly IMapCoversToLocal _coverMapper;
private const string TITLE_SLUG_ROUTE = "/titleslug/(?<slug>[^/]+)";
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 @@ private MovieResource GetMovie(int id)
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 @@ private void DeleteMovie(int id)
{
deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value);
}
if (addExclusionQuery.HasValue)
{
addExclusion = Convert.ToBoolean(addExclusionQuery.Value);
@ -151,7 +153,10 @@ public void Handle(MovieImportedEvent message)
public void Handle(MovieFileDeletedEvent message)
{
if (message.Reason == DeleteMediaFileReason.Upgrade) return;
if (message.Reason == DeleteMediaFileReason.Upgrade)
{
return;
}
BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId);
}

View file

@ -65,7 +65,6 @@ public void Handle(MovieGrabbedEvent message)
//add a grabbed field in MovieResource?
//resource.Grabbed = true;
BroadcastResourceChange(ModelAction.Updated, resource);
}

View file

@ -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 @@ public MovieResource()
public DateTime Added { get; set; }
public AddMovieOptions AddOptions { get; set; }
public Ratings Ratings { get; set; }
//public List<string> AlternativeTitles { get; set; }
public MovieFileResource MovieFile { get; set; }
@ -90,15 +91,15 @@ public static class MovieResourceMapper
{
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 @@ public static MovieResource ToResource(this Core.Movies.Movie model)
}*/
//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 @@ public static MovieResource ToResource(this Core.Movies.Movie model)
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 @@ public static MovieResource ToResource(this Core.Movies.Movie model)
FolderName = model.FolderName(),
//SizeOnDisk = size,
Runtime = model.Runtime,
LastInfoSync = model.LastInfoSync,
CleanTitle = model.CleanTitle,
@ -173,7 +175,10 @@ public static MovieResource ToResource(this Core.Movies.Movie model)
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 @@ public static Core.Movies.Movie ToModel(this MovieResource resource)
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 @@ public static Core.Movies.Movie ToModel(this MovieResource resource)
Tags = resource.Tags,
Added = resource.Added,
AddOptions = resource.AddOptions,
//AlternativeTitles = resource.AlternativeTitles,
Ratings = resource.Ratings,
YouTubeTrailerId = resource.YouTubeTrailerId,

View file

@ -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 @@ public RenameMovieModule(IRenameMovieFileService renameMovieFileService)
private List<RenameMovieResource> GetMovies()
{
if(!Request.Query.MovieId.HasValue)
if (!Request.Query.MovieId.HasValue)
{
throw new BadRequestException("movieId is missing");
}
@ -28,6 +28,5 @@ private List<RenameMovieResource> GetMovies()
return _renameMovieFileService.GetRenamePreviews(movieId).ToResource();
}
}
}

View file

@ -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 @@ public static class RenameMovieResourceMapper
{
public static RenameMovieResource ToResource(this Core.MediaFiles.RenameMovieFilePreview model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new RenameMovieResource
{

View file

@ -9,7 +9,8 @@ public class ImportExclusionsModule : RadarrRestModule<ImportExclusionsResource>
{
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 @@ public int AddExclusion(ImportExclusionsResource exclusionResource)
return _exclusionService.AddExclusion(model).Id;
}
public void RemoveExclusion (int id)
public void RemoveExclusion(int id)
{
_exclusionService.RemoveExclusion(new ImportExclusion { Id = id });
}

View file

@ -15,7 +15,10 @@ public static class ImportExclusionsResourceMapper
{
public static ImportExclusionsResource ToResource(this Core.NetImport.ImportExclusions.ImportExclusion model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new ImportExclusionsResource
{

View file

@ -2,10 +2,10 @@
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 @@ public ListImportModule(IMovieService movieService, ISearchForNewMovie movieSear
{
_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);
}
}
}

View file

@ -6,7 +6,8 @@ namespace NzbDrone.Api.NetImport
{
public class NetImportModule : ProviderModuleBase<NetImportResource, INetImport, NetImportDefinition>
{
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 @@ protected override void MapToModel(NetImportDefinition definition, NetImportReso
protected override void Validate(NetImportDefinition definition, bool includeWarnings)
{
if (!definition.Enable) return;
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}

View file

@ -41,7 +41,11 @@ protected override void MapToModel(NotificationDefinition definition, Notificati
protected override void Validate(NotificationDefinition definition, bool includeWarnings)
{
if (!definition.OnGrab && !definition.OnDownload) return;
if (!definition.OnGrab && !definition.OnDownload)
{
return;
}
base.Validate(definition, includeWarnings);
}
}

View file

@ -21,7 +21,6 @@ private ParseResource Parse()
var title = Request.Query.Title.Value as string;
var parsedMovieInfo = _parsingService.ParseMovieInfo(title, new List<object>());
if (parsedMovieInfo == null)
{
return null;

View file

@ -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
{

View file

@ -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
{

View file

@ -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 @@ public static class DelayProfileResourceMapper
{
public static DelayProfileResource ToResource(this DelayProfile model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new DelayProfileResource
{
@ -39,7 +42,10 @@ public static DelayProfileResource ToResource(this DelayProfile model)
public static DelayProfile ToModel(this DelayProfileResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new DelayProfile
{

View file

@ -27,12 +27,12 @@ private LanguageResource GetById(int id)
private List<LanguageResource> 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();
}

View file

@ -3,7 +3,7 @@
namespace NzbDrone.Api.Profiles
{
class LegacyProfileModule : NzbDroneApiModule
public class LegacyProfileModule : NzbDroneApiModule
{
public LegacyProfileModule()
: base("qualityprofile")

View file

@ -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 @@ public static class ProfileResourceMapper
{
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 @@ public static ProfileResource ToResource(this Profile model)
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 @@ public static ProfileResource ToResource(this Profile model)
public static ProfileQualityItemResource ToResource(this ProfileQualityItem model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new ProfileQualityItemResource
{
@ -113,7 +131,10 @@ public static ProfileFormatItemResource ToResource(this ProfileFormatItem model)
public static Profile ToModel(this ProfileResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new Profile
{
@ -131,7 +152,10 @@ public static Profile ToModel(this ProfileResource resource)
public static ProfileQualityItem ToModel(this ProfileQualityItemResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new ProfileQualityItem
{

View file

@ -31,7 +31,8 @@ private List<ProfileResource> GetAll()
var formatItems = _formatService.All().Select(v => new ProfileFormatItem
{
Format = v, Allowed = true
Format = v,
Allowed = true
}).ToList();
formatItems.Insert(0, new ProfileFormatItem

View file

@ -20,7 +20,6 @@ public class AllowedValidator<T> : PropertyValidator
public AllowedValidator()
: base("Must contain at least one allowed quality")
{
}
protected override bool IsValid(PropertyValidatorContext context)

View file

@ -3,10 +3,10 @@
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 @@ protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> pr
{
_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 @@ protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> pr
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 @@ private object Test(TProviderResource providerResource)
return "{}";
}
private object RequestAction(string action, TProviderResource providerResource)
{
var providerDefinition = GetDefinition(providerResource, true, false);

View file

@ -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
{

View file

@ -31,7 +31,7 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa
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 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa
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 @@ private object GetTemplates()
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 @@ private CustomFormatTestResource Test()
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(),

View file

@ -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
{

View file

@ -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 @@ public static class QualityTagMatchResultResourceMapper
{
public static FormatTagMatchResultResource ToResource(this FormatTagMatchResult model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new FormatTagMatchResultResource
{

View file

@ -7,7 +7,8 @@ namespace NzbDrone.Api.Qualities
{
public class FormatTagValidator : PropertyValidator
{
public FormatTagValidator() : base("{ValidationMessage}")
public FormatTagValidator()
: base("{ValidationMessage}")
{
}
@ -19,11 +20,14 @@ protected override bool IsValid(PropertyValidatorContext context)
return false;
}
var tags = (IEnumerable<string>) context.PropertyValue;
var tags = (IEnumerable<string>)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.";

View file

@ -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
{

View file

@ -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 @@ public static class QualityDefinitionResourceMapper
{
public static QualityDefinitionResource ToResource(this QualityDefinition model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new QualityDefinitionResource
{
@ -40,7 +43,10 @@ public static QualityDefinitionResource ToResource(this QualityDefinition model)
public static QualityDefinition ToModel(this QualityDefinitionResource resource)
{
if (resource == null) return null;
if (resource == null)
{
return null;
}
return new QualityDefinition
{

View file

@ -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 @@ public QueueActionModule(IQueueService queueService,
_pendingReleaseService = pendingReleaseService;
_downloadService = downloadService;
Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id));
Post("/import", x => Import());
Post("/grab", x => Grab());
Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id));
Post("/import", x => Import());
Post("/grab", x => Grab());
}
private object Remove(int id)

View file

@ -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 @@ public static class QueueResourceMapper
{
public static QueueResource ToResource(this Core.Queue.Queue model)
{
if (model == null) return null;
if (model == null)
{
return null;
}
return new QueueResource
{

Some files were not shown because too many files have changed in this diff Show more