ReSharper code cleanup

pull/7/merge
kay.one 14 years ago
parent 8cade435d1
commit e896af5cd0

@ -0,0 +1,70 @@
<Configuration>
<CodeStyleSettings>
<ExternalPath IsNull="False">
</ExternalPath>
<Sharing>SOLUTION</Sharing>
<CSharp>
<FormatSettings>
<MODIFIERS_ORDER IsNull="False">
<Item>public</Item>
<Item>protected</Item>
<Item>internal</Item>
<Item>private</Item>
<Item>new</Item>
<Item>abstract</Item>
<Item>virtual</Item>
<Item>override</Item>
<Item>sealed</Item>
<Item>static</Item>
<Item>readonly</Item>
<Item>extern</Item>
<Item>unsafe</Item>
<Item>volatile</Item>
</MODIFIERS_ORDER>
</FormatSettings>
<UsingsSettings />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
</Naming2>
</CSharp>
<VB>
<FormatSettings />
<ImportsSettings />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
</Naming2>
</VB>
<Web>
<Naming2 />
</Web>
<Xaml>
<Naming2 />
</Xaml>
<XML>
<FormatSettings />
</XML>
<GenerateMemberBody />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="PrivateStaticReadonly" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="TypesAndNamespaces" />
<PredefinedRule Inspect="True" Prefix="I" Suffix="" Style="AaBb" ElementKind="Interfaces" />
<PredefinedRule Inspect="True" Prefix="T" Suffix="" Style="AaBb" ElementKind="TypeParameters" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="MethodPropertyEvent" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="Locals" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="LocalConstants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="Parameters" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="PublicFields" />
<PredefinedRule Inspect="True" Prefix="_" Suffix="" Style="aaBb" ElementKind="PrivateInstanceFields" />
<PredefinedRule Inspect="True" Prefix="_" Suffix="" Style="aaBb" ElementKind="PrivateStaticFields" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="Constants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AA_BB" ElementKind="PrivateConstants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="StaticReadonly" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="EnumMember" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="Other" />
</Naming2>
</CodeStyleSettings>
</Configuration>

@ -14,9 +14,9 @@ namespace AutoMoq
{
public class AutoMoqer
{
internal Type ResolveType;
private IUnityContainer container;
private IDictionary<Type, object> registeredMocks;
internal Type ResolveType = null;
public AutoMoqer()
{
@ -30,7 +30,7 @@ namespace AutoMoq
public virtual T Resolve<T>()
{
ResolveType = typeof(T);
ResolveType = typeof (T);
var result = container.Resolve<T>();
ResolveType = null;
return result;
@ -67,47 +67,6 @@ namespace AutoMoq
SetMock(instance.GetType(), null);
}
#region private methods
private void SetupAutoMoqer(IUnityContainer container)
{
this.container = container;
registeredMocks = new Dictionary<Type, object>();
AddTheAutoMockingContainerExtensionToTheContainer(container);
container.RegisterInstance(this);
}
private static void AddTheAutoMockingContainerExtensionToTheContainer(IUnityContainer container)
{
container.AddNewExtension<AutoMockingContainerExtension>();
return;
}
private Mock<T> TheRegisteredMockForThisType<T>(Type type) where T : class
{
return (Mock<T>)registeredMocks.Where(x => x.Key == type).First().Value;
}
private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) where T : class
{
var mock = new Mock<T>(behavior);
container.RegisterInstance(mock.Object);
SetMock(type, mock);
}
private bool GetMockHasNotBeenCalledForThisType(Type type)
{
return registeredMocks.ContainsKey(type) == false;
}
private static Type GetTheMockType<T>() where T : class
{
return typeof(T);
}
#endregion
public ISetup<T> Setup<T>(Expression<Action<T>> expression) where T : class
{
return GetMock<T>().Setup(expression);
@ -147,5 +106,45 @@ namespace AutoMoq
}
}
#region private methods
private void SetupAutoMoqer(IUnityContainer container)
{
this.container = container;
registeredMocks = new Dictionary<Type, object>();
AddTheAutoMockingContainerExtensionToTheContainer(container);
container.RegisterInstance(this);
}
private static void AddTheAutoMockingContainerExtensionToTheContainer(IUnityContainer container)
{
container.AddNewExtension<AutoMockingContainerExtension>();
return;
}
private Mock<T> TheRegisteredMockForThisType<T>(Type type) where T : class
{
return (Mock<T>) registeredMocks.Where(x => x.Key == type).First().Value;
}
private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) where T : class
{
var mock = new Mock<T>(behavior);
container.RegisterInstance(mock.Object);
SetMock(type, mock);
}
private bool GetMockHasNotBeenCalledForThisType(Type type)
{
return registeredMocks.ContainsKey(type) == false;
}
private static Type GetTheMockType<T>() where T : class
{
return typeof (T);
}
#endregion
}
}

@ -1,22 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using AutoMoq;
using FizzWare.NBuilder;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using Ninject;
using Ninject.Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using SubSonic.Repository;
using TvdbLib.Data;
using SubSonic.Extensions;
namespace NzbDrone.Core.Test
{
@ -117,7 +102,7 @@ namespace NzbDrone.Core.Test
//Arrange
var mocker = new AutoMoqer();
var constant = new VirtualDependency() { PropValue = Guid.NewGuid().ToString() };
var constant = new VirtualDependency {PropValue = Guid.NewGuid().ToString()};
mocker.SetConstant(constant);
@ -127,7 +112,6 @@ namespace NzbDrone.Core.Test
//Assert
Assert.AreEqual(constant.PropValue, result);
}
}
public class ConcreteClass
@ -138,24 +122,27 @@ namespace NzbDrone.Core.Test
}
}
public class Dependency : IDependency { }
public class Dependency : IDependency
{
}
public interface IDependency { }
public interface IDependency
{
}
public class ClassWithDependencies
{
public IDependency Dependency { get; set; }
public ClassWithDependencies(IDependency dependency)
{
Dependency = dependency;
}
public IDependency Dependency { get; set; }
}
public class ClassWithVirtualDependencies
{
private readonly VirtualDependency _virtualDependency;
public IDependency Dependency { get; set; }
public ClassWithVirtualDependencies(IDependency dependency, VirtualDependency virtualDependency)
{
@ -163,6 +150,8 @@ namespace NzbDrone.Core.Test
Dependency = dependency;
}
public IDependency Dependency { get; set; }
public string CallVirtualChild()
{
return _virtualDependency.VirtualMethod();
@ -178,19 +167,20 @@ namespace NzbDrone.Core.Test
{
private readonly IDependency _dependency;
public string PropValue { get; set; }
public VirtualDependency() { }
public VirtualDependency()
{
}
public VirtualDependency(IDependency dependency)
{
_dependency = dependency;
}
public string PropValue { get; set; }
public virtual string VirtualMethod()
{
return "hello";
}
}
}
}

@ -10,9 +10,9 @@ namespace AutoMoq.Unity
{
internal class AutoMockingBuilderStrategy : BuilderStrategy
{
private readonly IUnityContainer container;
private readonly MockFactory mockFactory;
private readonly IEnumerable<Type> registeredTypes;
private readonly IUnityContainer container;
public AutoMockingBuilderStrategy(IEnumerable<Type> registeredTypes, IUnityContainer container)
{
@ -45,7 +45,7 @@ namespace AutoMoq.Unity
private static Type GetTheTypeFromTheBuilderContext(IBuilderContext context)
{
return ((NamedTypeBuildKey)context.OriginalBuildKey).Type;
return (context.OriginalBuildKey).Type;
}
private bool TypeIsNotRegistered(Type type)
@ -62,19 +62,19 @@ namespace AutoMoq.Unity
private Mock InvokeTheMockCreationMethod(MethodInfo createMethod)
{
return (Mock)createMethod.Invoke(mockFactory, new object[] { new List<object>().ToArray() });
return (Mock) createMethod.Invoke(mockFactory, new object[] {new List<object>().ToArray()});
}
private MethodInfo GenerateAnInterfaceMockCreationMethod(Type type)
{
var createMethodWithNoParameters = mockFactory.GetType().GetMethod("Create", EmptyArgumentList());
return createMethodWithNoParameters.MakeGenericMethod(new[] { type });
return createMethodWithNoParameters.MakeGenericMethod(new[] {type});
}
private static Type[] EmptyArgumentList()
{
return new[] { typeof(object[]) };
return new[] {typeof (object[])};
}
#endregion

@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using AutoMoq;
using Gallio.Framework;
using AutoMoq;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
@ -24,13 +18,13 @@ namespace NzbDrone.Core.Test
const string value = "MY_VALUE";
//Arrange
var config = new Config { Key = key, Value = value };
var config = new Config {Key = key, Value = value};
var mocker = new AutoMoqer();
mocker.GetMock<IRepository>()
.Setup(r => r.Single<Config>(key))
.Returns(config);
.Setup(r => r.Single<Config>(key))
.Returns(config);
//Act
mocker.Resolve<ConfigProvider>().SetValue(key, value);
@ -50,9 +44,9 @@ namespace NzbDrone.Core.Test
var mocker = new AutoMoqer();
mocker.GetMock<IRepository>()
.Setup(r => r.Single<Config>(It.IsAny<string>()))
.Returns<Config>(null)
.Verifiable();
.Setup(r => r.Single<Config>(It.IsAny<string>()))
.Returns<Config>(null)
.Verifiable();
//Act
mocker.Resolve<ConfigProvider>().SetValue(key, value);
@ -60,7 +54,8 @@ namespace NzbDrone.Core.Test
//Assert
mocker.GetMock<IRepository>().Verify();
mocker.GetMock<IRepository>().Verify(r => r.Update(It.IsAny<Config>()), Times.Never());
mocker.GetMock<IRepository>().Verify(r => r.Add(It.Is<Config>(c => c.Key == key && c.Value == value)), Times.Once());
mocker.GetMock<IRepository>().Verify(r => r.Add(It.Is<Config>(c => c.Key == key && c.Value == value)),
Times.Once());
}
}
}
}

@ -1,22 +1,15 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using AutoMoq;
using FizzWare.NBuilder;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using Ninject;
using Ninject.Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using SubSonic.Repository;
using TvdbLib.Data;
using SubSonic.Extensions;
namespace NzbDrone.Core.Test
{
@ -33,24 +26,23 @@ namespace NzbDrone.Core.Test
var fakeEpisodes = Builder<TvdbSeries>.CreateNew().With(
c => c.Episodes =
new List<TvdbEpisode>(Builder<TvdbEpisode>.CreateListOfSize(episodeCount).
WhereAll()
.Have(l => l.Language = new TvdbLanguage(0, "eng", "a"))
.Build())
).With(c => c.Id = seriesId).Build();
new List<TvdbEpisode>(Builder<TvdbEpisode>.CreateListOfSize(episodeCount).
WhereAll()
.Have(l => l.Language = new TvdbLanguage(0, "eng", "a"))
.Build())
).With(c => c.Id = seriesId).Build();
var mocker = new AutoMoqer();
mocker.SetConstant(MockLib.GetEmptyRepository());
mocker.GetMock<TvDbProvider>()
.Setup(c => c.GetSeries(seriesId, true))
.Returns(fakeEpisodes).Verifiable();
.Setup(c => c.GetSeries(seriesId, true))
.Returns(fakeEpisodes).Verifiable();
//mocker.GetMock<IRepository>().SetReturnsDefault();
//Act
var sw = Stopwatch.StartNew();
mocker.Resolve<EpisodeProvider>().RefreshEpisodeInfo(seriesId);
@ -72,14 +64,14 @@ namespace NzbDrone.Core.Test
var repo = new Mock<IRepository>();
var epInDb = new Episode
{
AirDate = DateTime.Today,
EpisodeId = 55555,
EpisodeNumber = 5,
Language = "en",
SeasonId = 4444,
SeasonNumber = 1
};
{
AirDate = DateTime.Today,
EpisodeId = 55555,
EpisodeNumber = 5,
Language = "en",
SeasonId = 4444,
SeasonNumber = 1
};
season.Setup(s => s.IsIgnored(12345, 1)).Returns(false);
series.Setup(s => s.QualityWanted(12345, QualityTypes.TV)).Returns(true);
@ -90,11 +82,10 @@ namespace NzbDrone.Core.Test
//repo.All<EpisodeFile>().Where(c => c.EpisodeId == episode.EpisodeId);
//Act
//Assert
}
}
}
}

@ -3,7 +3,6 @@ using System.IO;
using MbUnit.Framework;
using NLog;
using NLog.Config;
using System.Linq;
namespace NzbDrone.Core.Test
{
@ -13,27 +12,32 @@ namespace NzbDrone.Core.Test
[TearDown]
public void TearDown()
{
foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.db", SearchOption.AllDirectories))
foreach (
var file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.db", SearchOption.AllDirectories))
{
try
{
File.Delete(file);
}
catch
{ }
{
}
}
}
[FixtureTearDown]
public void FixtureTearDown()
{
foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*", SearchOption.AllDirectories))
foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*", SearchOption.AllDirectories)
)
{
try
{
File.Delete(file);
}
catch { }
catch
{
}
}
}
@ -42,7 +46,8 @@ namespace NzbDrone.Core.Test
{
try
{
LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(CentralDispatch.AppPath, "log.config"), false);
LogManager.Configuration =
new XmlLoggingConfiguration(Path.Combine(CentralDispatch.AppPath, "log.config"), false);
LogManager.ThrowExceptions = true;
}
catch (Exception e)
@ -50,7 +55,5 @@ namespace NzbDrone.Core.Test
Console.WriteLine("Unable to configure logging. " + e);
}
}
}
}

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository;
@ -20,7 +17,14 @@ namespace NzbDrone.Core.Test
public void AllItems()
{
//Setup
var indexer = new Indexer { Enabled = true, IndexerId = 0, IndexerName = "NzbMatrix", Order = 1, RssUrl = "http://www.nzbmatrix.com" };
var indexer = new Indexer
{
Enabled = true,
IndexerId = 0,
IndexerName = "NzbMatrix",
Order = 1,
RssUrl = "http://www.nzbmatrix.com"
};
var series = new Series
{
SeriesId = 5656,
@ -31,7 +35,7 @@ namespace NzbDrone.Core.Test
Title = "30 Rock",
Path = @"C:\Test\TV\30 Rock"
};
var season = new Season { SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true };
var season = new Season {SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true};
var episode = new Episode
{
AirDate = DateTime.Today.AddDays(-1),
@ -74,46 +78,53 @@ namespace NzbDrone.Core.Test
{
//Todo: This test fails... Moq Setup doesn't return the expected value
//Setup
var indexer = new Indexer { Enabled = true, IndexerName = "NzbMatrix", Order = 1, RssUrl = "http://www.nzbmatrix.com" };
var indexer = new Indexer
{
Enabled = true,
IndexerName = "NzbMatrix",
Order = 1,
RssUrl = "http://www.nzbmatrix.com"
};
var series = new Series
{
SeriesId = 5656,
CleanTitle = "rock",
Monitored = true,
Overview = "Series Overview",
QualityProfileId = 1,
Title = "30 Rock",
Path = @"C:\Test\TV\30 Rock"
};
var season = new Season { SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true };
{
SeriesId = 5656,
CleanTitle = "rock",
Monitored = true,
Overview = "Series Overview",
QualityProfileId = 1,
Title = "30 Rock",
Path = @"C:\Test\TV\30 Rock"
};
var season = new Season {SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true};
var episode = new Episode
{
AirDate = DateTime.Today.AddDays(-1),
EpisodeId = 1234,
EpisodeNumber = 5,
Language = "English",
Overview = "This is an Overview",
SeasonNumber = 1,
SeasonId = 4321,
Season = season,
SeriesId = 5656
};
{
AirDate = DateTime.Today.AddDays(-1),
EpisodeId = 1234,
EpisodeNumber = 5,
Language = "English",
Overview = "This is an Overview",
SeasonNumber = 1,
SeasonId = 4321,
Season = season,
SeriesId = 5656
};
var list = new List<History>();
list.Add(new History
{
HistoryId = new int(),
Date = DateTime.Now,
IsProper = false,
Quality = QualityTypes.TV,
IndexerId = indexer.IndexerId,
EpisodeId = episode.EpisodeId
});
{
HistoryId = new int(),
Date = DateTime.Now,
IsProper = false,
Quality = QualityTypes.TV,
IndexerId = indexer.IndexerId,
EpisodeId = episode.EpisodeId
});
var proper = false;
var repo = new Mock<IRepository>();
repo.Setup(r => r.Exists<History>(h => h.EpisodeId == episode.EpisodeId && h.IsProper == proper)).Returns(true);
repo.Setup(r => r.Exists<History>(h => h.EpisodeId == episode.EpisodeId && h.IsProper == proper)).Returns(
true);
var target = new HistoryProvider(repo.Object);
@ -131,44 +142,51 @@ namespace NzbDrone.Core.Test
//Todo: This test fails... Moq Setup doesn't return the expected value
//Setup
var indexer = new Indexer { Enabled = true, IndexerName = "NzbMatrix", Order = 1, RssUrl = "http://www.nzbmatrix.com" };
var indexer = new Indexer
{
Enabled = true,
IndexerName = "NzbMatrix",
Order = 1,
RssUrl = "http://www.nzbmatrix.com"
};
var series = new Series
{
SeriesId = 5656,
CleanTitle = "rock",
Monitored = true,
Overview = "Series Overview",
QualityProfileId = 1,
Title = "30 Rock",
Path = @"C:\Test\TV\30 Rock"
};
var season = new Season { SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true };
{
SeriesId = 5656,
CleanTitle = "rock",
Monitored = true,
Overview = "Series Overview",
QualityProfileId = 1,
Title = "30 Rock",
Path = @"C:\Test\TV\30 Rock"
};
var season = new Season {SeasonId = 4321, SeasonNumber = 1, SeriesId = 5656, Monitored = true};
var episode = new Episode
{
AirDate = DateTime.Today.AddDays(-1),
EpisodeId = 1234,
EpisodeNumber = 5,
Language = "English",
Overview = "This is an Overview",
SeasonNumber = 1,
SeasonId = 4321,
Season = season,
SeriesId = 5656
};
{
AirDate = DateTime.Today.AddDays(-1),
EpisodeId = 1234,
EpisodeNumber = 5,
Language = "English",
Overview = "This is an Overview",
SeasonNumber = 1,
SeasonId = 4321,
Season = season,
SeriesId = 5656
};
var list = new List<History>();
list.Add(new History
{
HistoryId = new int(),
Date = DateTime.Now,
IsProper = false,
Quality = QualityTypes.TV,
IndexerId = indexer.IndexerId,
EpisodeId = episode.EpisodeId
});
{
HistoryId = new int(),
Date = DateTime.Now,
IsProper = false,
Quality = QualityTypes.TV,
IndexerId = indexer.IndexerId,
EpisodeId = episode.EpisodeId
});
var repo = new Mock<IRepository>();
repo.Setup(r => r.Exists<History>(h => h.Episode == episode && h.IsProper == list[0].IsProper)).Returns(false);
repo.Setup(r => r.Exists<History>(h => h.Episode == episode && h.IsProper == list[0].IsProper)).Returns(
false);
var target = new HistoryProvider(repo.Object);

@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
@ -25,10 +21,14 @@ namespace NzbDrone.Core.Test
//Setup
var list = new List<Indexer>();
list.Add(new Indexer { IndexerName = "Test1", RssUrl = "http://www.test1.com/rss.php", Enabled = true, Order = 1 });
list.Add(new Indexer { IndexerName = "Test2", RssUrl = "http://www.test2.com/rss.php", Enabled = false, Order = 4 });
list.Add(new Indexer { IndexerName = "Test3", RssUrl = "http://www.test3.com/rss.php", Enabled = true, Order = 3 });
list.Add(new Indexer { IndexerName = "Test4", RssUrl = "http://www.test4.com/rss.php", Enabled = false, Order = 2 });
list.Add(new Indexer
{IndexerName = "Test1", RssUrl = "http://www.test1.com/rss.php", Enabled = true, Order = 1});
list.Add(new Indexer
{IndexerName = "Test2", RssUrl = "http://www.test2.com/rss.php", Enabled = false, Order = 4});
list.Add(new Indexer
{IndexerName = "Test3", RssUrl = "http://www.test3.com/rss.php", Enabled = true, Order = 3});
list.Add(new Indexer
{IndexerName = "Test4", RssUrl = "http://www.test4.com/rss.php", Enabled = false, Order = 2});
var repo = new Mock<IRepository>();
var config = new Mock<ConfigProvider>();
@ -53,10 +53,14 @@ namespace NzbDrone.Core.Test
//Setup
var list = new List<Indexer>();
list.Add(new Indexer { IndexerName = "Test1", RssUrl = "http://www.test1.com/rss.php", Enabled = true, Order = 1 });
list.Add(new Indexer { IndexerName = "Test2", RssUrl = "http://www.test2.com/rss.php", Enabled = false, Order = 4 });
list.Add(new Indexer { IndexerName = "Test3", RssUrl = "http://www.test3.com/rss.php", Enabled = true, Order = 3 });
list.Add(new Indexer { IndexerName = "Test4", RssUrl = "http://www.test4.com/rss.php", Enabled = false, Order = 2 });
list.Add(new Indexer
{IndexerName = "Test1", RssUrl = "http://www.test1.com/rss.php", Enabled = true, Order = 1});
list.Add(new Indexer
{IndexerName = "Test2", RssUrl = "http://www.test2.com/rss.php", Enabled = false, Order = 4});
list.Add(new Indexer
{IndexerName = "Test3", RssUrl = "http://www.test3.com/rss.php", Enabled = true, Order = 3});
list.Add(new Indexer
{IndexerName = "Test4", RssUrl = "http://www.test4.com/rss.php", Enabled = false, Order = 2});
var repo = new Mock<IRepository>();
var config = new Mock<ConfigProvider>();
@ -72,4 +76,4 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(result.Last().IndexerName, "Test3");
}
}
}
}

@ -1,16 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using AutoMoq;
using FizzWare.NBuilder;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using Ninject;
using Ninject.Moq;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
@ -23,7 +16,6 @@ namespace NzbDrone.Core.Test
// ReSharper disable InconsistentNaming
public class MediaFileProviderTests
{
[Test]
[Description("Verifies that a new file imported properly")]
public void import_new_file()
@ -45,15 +37,16 @@ namespace NzbDrone.Core.Test
var mocker = new AutoMoqer();
mocker.GetMock<IRepository>()
.Setup(r => r.Exists<EpisodeFile>(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(false).Verifiable();
.Setup(r => r.Exists(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(false).Verifiable();
mocker.GetMock<IRepository>()
.Setup(r => r.Add(It.IsAny<EpisodeFile>())).Returns(0).Verifiable();
.Setup(r => r.Add(It.IsAny<EpisodeFile>())).Returns(0).Verifiable();
mocker.GetMock<EpisodeProvider>()
.Setup(e => e.GetEpisode(fakeSeries.SeriesId, seasonNumber, episodeNumner)).Returns(fakeEpisode).Verifiable();
.Setup(e => e.GetEpisode(fakeSeries.SeriesId, seasonNumber, episodeNumner)).Returns(fakeEpisode).
Verifiable();
mocker.GetMock<DiskProvider>()
.Setup(e => e.GetSize(fileName)).Returns(12345).Verifiable();
.Setup(e => e.GetSize(fileName)).Returns(12345).Verifiable();
//Act
@ -62,7 +55,7 @@ namespace NzbDrone.Core.Test
//Assert
Assert.IsNotNull(result);
mocker.GetMock<IRepository>().VerifyAll();
mocker.GetMock<IRepository>().Verify(r => r.Add<EpisodeFile>(result), Times.Once());
mocker.GetMock<IRepository>().Verify(r => r.Add(result), Times.Once());
mocker.GetMock<EpisodeProvider>().VerifyAll();
mocker.GetMock<DiskProvider>().VerifyAll();
@ -96,7 +89,7 @@ namespace NzbDrone.Core.Test
var mocker = new AutoMoqer();
mocker.GetMock<IRepository>(MockBehavior.Strict)
.Setup(r => r.Exists<EpisodeFile>(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(true).Verifiable();
.Setup(r => r.Exists(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(true).Verifiable();
mocker.GetMock<EpisodeProvider>(MockBehavior.Strict);
mocker.GetMock<DiskProvider>(MockBehavior.Strict);
@ -109,7 +102,7 @@ namespace NzbDrone.Core.Test
mocker.GetMock<EpisodeProvider>().VerifyAll();
mocker.GetMock<DiskProvider>(MockBehavior.Strict).VerifyAll();
Assert.IsNull(result);
mocker.GetMock<IRepository>().Verify(r => r.Add<EpisodeFile>(result), Times.Never());
mocker.GetMock<IRepository>().Verify(r => r.Add(result), Times.Never());
}
[Test]
@ -130,10 +123,11 @@ namespace NzbDrone.Core.Test
//Mocks
var mocker = new AutoMoqer();
mocker.GetMock<IRepository>(MockBehavior.Strict)
.Setup(r => r.Exists<EpisodeFile>(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(false).Verifiable();
.Setup(r => r.Exists(It.IsAny<Expression<Func<EpisodeFile, Boolean>>>())).Returns(false).Verifiable();
mocker.GetMock<EpisodeProvider>(MockBehavior.Strict)
.Setup(e => e.GetEpisode(fakeSeries.SeriesId, seasonNumber, episodeNumner)).Returns<Episode>(null).Verifiable();
.Setup(e => e.GetEpisode(fakeSeries.SeriesId, seasonNumber, episodeNumner)).Returns<Episode>(null).
Verifiable();
mocker.GetMock<DiskProvider>(MockBehavior.Strict);
@ -144,12 +138,7 @@ namespace NzbDrone.Core.Test
//Assert
mocker.VerifyAllMocks();
Assert.IsNull(result);
mocker.GetMock<IRepository>().Verify(r => r.Add<EpisodeFile>(result), Times.Never());
mocker.GetMock<IRepository>().Verify(r => r.Add(result), Times.Never());
}
}
}
}

@ -1,40 +1,45 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using FizzWare.NBuilder;
using Moq;
using NLog;
using NzbDrone.Core.Instrumentation;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using SubSonic.DataProviders;
using SubSonic.Repository;
using TvdbLib;
namespace NzbDrone.Core.Test
{
/// <summary>
/// Provides the standard Mocks needed for a typical test
/// Provides the standard Mocks needed for a typical test
/// </summary>
static class MockLib
internal static class MockLib
{
public static string[] StandardSeries
{
get { return new string[] { "c:\\tv\\the simpsons", "c:\\tv\\family guy", "c:\\tv\\southpark", "c:\\tv\\24" }; }
get { return new[] {"c:\\tv\\the simpsons", "c:\\tv\\family guy", "c:\\tv\\southpark", "c:\\tv\\24"}; }
}
public static ConfigProvider StandardConfig
{
get
{
var mock = new Mock<ConfigProvider>();
mock.SetupGet(c => c.SeriesRoot).Returns("C:\\");
return mock.Object;
}
}
public static IRepository GetEmptyRepository()
{
return GetEmptyRepository(true);
}
public static IRepository GetEmptyRepository(bool enableLogging)
{
Console.WriteLine("Creating an empty SQLite database");
var provider = ProviderFactory.GetProvider("Data Source=" + Guid.NewGuid() + ".db;Version=3;New=True", "System.Data.SQLite");
var provider = ProviderFactory.GetProvider("Data Source=" + Guid.NewGuid() + ".db;Version=3;New=True",
"System.Data.SQLite");
if (enableLogging)
{
provider.Log = new NlogWriter();
@ -42,16 +47,6 @@ namespace NzbDrone.Core.Test
return new SimpleRepository(provider, SimpleRepositoryOptions.RunMigrations);
}
public static ConfigProvider StandardConfig
{
get
{
var mock = new Mock<ConfigProvider>();
mock.SetupGet(c => c.SeriesRoot).Returns("C:\\");
return mock.Object;
}
}
public static DiskProvider GetStandardDisk(int seasons, int episodes)
{
var mock = new Mock<DiskProvider>();
@ -77,4 +72,4 @@ namespace NzbDrone.Core.Test
return mock.Object;
}
}
}
}

@ -6,28 +6,31 @@ using Ninject.Syntax;
namespace Ninject.Moq
{
/// <summary>
/// Extensions for the fluent binding syntax API.
/// </summary>
public static class ExtensionsForBindingSyntax
{
/// <summary>
/// Indicates that the service should be bound to a mocked instance of the specified type.
/// </summary>
/// <typeparam name="T">The service that is being mocked.</typeparam>
/// <param name="builder">The builder that is building the binding.</param>
public static IBindingWhenInNamedWithOrOnSyntax<T> ToMock<T>(this IBindingToSyntax<T> builder)
{
var haveBinding = builder as IHaveBinding;
if (haveBinding == null)
throw new NotSupportedException(String.Format("The binding builder for {0} is of type {1}, which does not implement IHaveBinding and is therefore not extensible.", typeof(T), builder.GetType()));
/// <summary>
/// Extensions for the fluent binding syntax API.
/// </summary>
public static class ExtensionsForBindingSyntax
{
/// <summary>
/// Indicates that the service should be bound to a mocked instance of the specified type.
/// </summary>
/// <typeparam name = "T">The service that is being mocked.</typeparam>
/// <param name = "builder">The builder that is building the binding.</param>
public static IBindingWhenInNamedWithOrOnSyntax<T> ToMock<T>(this IBindingToSyntax<T> builder)
{
var haveBinding = builder as IHaveBinding;
IBinding binding = haveBinding.Binding;
if (haveBinding == null)
throw new NotSupportedException(
String.Format(
"The binding builder for {0} is of type {1}, which does not implement IHaveBinding and is therefore not extensible.",
typeof (T), builder.GetType()));
binding.ProviderCallback = ctx => new MockProvider(ctx.Kernel.Components.Get<IInjectorFactory>());
IBinding binding = haveBinding.Binding;
return builder as IBindingWhenInNamedWithOrOnSyntax<T>;
}
}
}
binding.ProviderCallback = ctx => new MockProvider(ctx.Kernel.Components.Get<IInjectorFactory>());
return builder as IBindingWhenInNamedWithOrOnSyntax<T>;
}
}
}

@ -6,70 +6,75 @@ using Ninject.Injection;
namespace Ninject.Moq
{
/// <summary>
/// Creates mocked instances via Moq.
/// </summary>
public class MockProvider : IProvider
{
private static readonly Dictionary<Type, ConstructorInjector> _injectors = new Dictionary<Type, ConstructorInjector>();
/// <summary>
/// Creates mocked instances via Moq.
/// </summary>
public class MockProvider : IProvider
{
private static readonly Dictionary<Type, ConstructorInjector> _injectors =
new Dictionary<Type, ConstructorInjector>();
/// <summary>
/// Gets the type (or prototype) of instances the provider creates.
/// </summary>
public Type Type
{
get { return typeof(Mock<>); }
}
/// <summary>
/// Initializes a new instance of the <see cref = "MockProvider" /> class.
/// </summary>
/// <param name = "injectorFactory">The injector factory component.</param>
public MockProvider(IInjectorFactory injectorFactory)
{
InjectorFactory = injectorFactory;
}
/// <summary>
/// Gets the injector factory component.
/// </summary>
public IInjectorFactory InjectorFactory { get; private set; }
/// <summary>
/// Gets the injector factory component.
/// </summary>
public IInjectorFactory InjectorFactory { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="MockProvider"/> class.
/// </summary>
/// <param name="injectorFactory">The injector factory component.</param>
public MockProvider(IInjectorFactory injectorFactory)
{
InjectorFactory = injectorFactory;
}
#region IProvider Members
/// <summary>
/// Creates an instance within the specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>The created instance.</returns>
public object Create(IContext context)
{
ConstructorInjector injector = GetInjector(context.Request.Service);
var mock = injector.Invoke() as Mock;
return mock.Object;
}
/// <summary>
/// Gets the type (or prototype) of instances the provider creates.
/// </summary>
public Type Type
{
get { return typeof (Mock<>); }
}
private ConstructorInjector GetInjector(Type service)
{
lock (_injectors)
{
Type mockType = typeof(Mock<>).MakeGenericType(service);
/// <summary>
/// Creates an instance within the specified context.
/// </summary>
/// <param name = "context">The context.</param>
/// <returns>The created instance.</returns>
public object Create(IContext context)
{
ConstructorInjector injector = GetInjector(context.Request.Service);
var mock = injector.Invoke() as Mock;
return mock.Object;
}
if (_injectors.ContainsKey(mockType))
return _injectors[mockType];
#endregion
ConstructorInjector injector = InjectorFactory.Create(mockType.GetConstructor(Type.EmptyTypes));
_injectors[mockType] = injector;
private ConstructorInjector GetInjector(Type service)
{
lock (_injectors)
{
Type mockType = typeof (Mock<>).MakeGenericType(service);
return injector;
}
}
if (_injectors.ContainsKey(mockType))
return _injectors[mockType];
/// <summary>
/// Gets a callback that creates an instance of the <see cref="MockProvider"/>.
/// </summary>
/// <returns>The created callback.</returns>
public static Func<IContext, IProvider> GetCreationCallback()
{
return ctx => new MockProvider(ctx.Kernel.Components.Get<IInjectorFactory>());
}
}
}
ConstructorInjector injector = InjectorFactory.Create(mockType.GetConstructor(Type.EmptyTypes));
_injectors[mockType] = injector;
return injector;
}
}
/// <summary>
/// Gets a callback that creates an instance of the <see cref = "MockProvider" />.
/// </summary>
/// <returns>The created callback.</returns>
public static Func<IContext, IProvider> GetCreationCallback()
{
return ctx => new MockProvider(ctx.Kernel.Components.Get<IInjectorFactory>());
}
}
}

@ -5,14 +5,14 @@ using Ninject.Planning.Bindings;
namespace Ninject.Moq
{
/// <summary>
/// A kernel that will create mocked instances (via Moq) for any service that is
/// requested for which no binding is registered.
/// A kernel that will create mocked instances (via Moq) for any service that is
/// requested for which no binding is registered.
/// </summary>
public class MockingKernel : StandardKernel
{
/// <summary>
/// Clears the kernel's cache, immediately deactivating all activated instances regardless of scope.
/// This does not remove any modules, extensions, or bindings.
/// Clears the kernel's cache, immediately deactivating all activated instances regardless of scope.
/// This does not remove any modules, extensions, or bindings.
/// </summary>
public void Reset()
{
@ -20,22 +20,22 @@ namespace Ninject.Moq
}
/// <summary>
/// Attempts to handle a missing binding for a service.
/// Attempts to handle a missing binding for a service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name = "service">The service.</param>
/// <returns><c>True</c> if the missing binding can be handled; otherwise <c>false</c>.</returns>
protected override bool HandleMissingBinding(Type service)
{
var binding = new Binding(service)
{
ProviderCallback = MockProvider.GetCreationCallback(),
ScopeCallback = ctx => null,
IsImplicit = true
};
{
ProviderCallback = MockProvider.GetCreationCallback(),
ScopeCallback = ctx => null,
IsImplicit = true
};
AddBinding(binding);
return true;
}
}
}
}

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using MbUnit.Framework;
using NzbDrone.Core.Repository.Quality;
namespace NzbDrone.Core.Test
@ -70,9 +65,9 @@ namespace NzbDrone.Core.Test
}
[Test]
[Row("WEEDS.S03E01-06.DUAL.BDRip.XviD.AC3.-HELLYWOOD", 3, new[] { 2, 3, 4, 5, 6 })]
[Row("Two.and.a.Half.Me.103.104.720p.HDTV.X264-DIMENSION", 1, new[] { 3, 4 })]
[Row("The.Kennedys.Part.1.and.Part.2.DSR.XviD-SYS", 1, new[] { 1, 2 })]
[Row("WEEDS.S03E01-06.DUAL.BDRip.XviD.AC3.-HELLYWOOD", 3, new[] {2, 3, 4, 5, 6})]
[Row("Two.and.a.Half.Me.103.104.720p.HDTV.X264-DIMENSION", 1, new[] {3, 4})]
[Row("The.Kennedys.Part.1.and.Part.2.DSR.XviD-SYS", 1, new[] {1, 2})]
public void episode_multipart_parse(string path, int season, int[] episodes)
{
var result = Parser.ParseEpisodeInfo(path);
@ -82,7 +77,6 @@ namespace NzbDrone.Core.Test
}
[Test]
[Row(@"c:\test\", @"c:\test")]
[Row(@"c:\\test\\", @"c:\test")]

@ -1,12 +1,10 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Runtime.InteropServices;
using MbUnit.Framework;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NzbDrone.Core.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
@ -19,9 +17,11 @@ using MbUnit.Framework;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("699aed1b-015e-4f0d-9c81-d5557b05d260")]
// Version information for an assembly consists of the following four values:
@ -34,5 +34,6 @@ using MbUnit.Framework;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,40 +1,34 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FizzWare.NBuilder;
using MbUnit.Framework;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using System.Linq;
using TvdbLib.Data;
namespace NzbDrone.Core.Test
{
[TestFixture]
// ReSharper disable InconsistentNaming
public class QualityProfileTest
{
/// <summary>
/// Test_s the storage.
/// </summary>
///
///
///<summary>
/// Test_s the storage.
///</summary>
[Test]
public void Test_Storage()
{
//Arrange
var repo = MockLib.GetEmptyRepository();
var testProfile = new QualityProfile
{
Name = Guid.NewGuid().ToString(),
Cutoff = QualityTypes.TV,
Allowed = new List<QualityTypes>() { QualityTypes.HDTV, QualityTypes.DVD },
Allowed = new List<QualityTypes> {QualityTypes.HDTV, QualityTypes.DVD},
};
//Act
var id = (int)repo.Add(testProfile);
var id = (int) repo.Add(testProfile);
var fetch = repo.Single<QualityProfile>(c => c.QualityProfileId == id);
//Assert
@ -51,19 +45,19 @@ namespace NzbDrone.Core.Test
var repo = MockLib.GetEmptyRepository();
var testProfile = new QualityProfile
{
Name = Guid.NewGuid().ToString(),
Cutoff = QualityTypes.TV,
Allowed = new List<QualityTypes>() { QualityTypes.HDTV, QualityTypes.DVD },
};
{
Name = Guid.NewGuid().ToString(),
Cutoff = QualityTypes.TV,
Allowed = new List<QualityTypes> {QualityTypes.HDTV, QualityTypes.DVD},
};
var profileId = (int)repo.Add(testProfile);
var profileId = (int) repo.Add(testProfile);
var series = Builder<Series>.CreateNew().Build();
series.QualityProfileId = profileId;
var seriesID = (int)repo.Add(series);
var seriesID = (int) repo.Add(series);
var result = repo.All<Series>();

@ -3,10 +3,10 @@ using System.Linq;
using FizzWare.NBuilder;
using MbUnit.Framework;
using NLog;
using NLog.Config;
using NzbDrone.Core.Instrumentation;
using NzbDrone.Core.Repository;
using LogLevel = NzbDrone.Core.Instrumentation.LogLevel;
using NLog.Config;
using LogLevel = NLog.LogLevel;
namespace NzbDrone.Core.Test
{
@ -38,7 +38,9 @@ namespace NzbDrone.Core.Test
}
[Test]
[Description("This test confirms that the tvdb id stored in the db is preserved rather than being replaced by an auto incrementing value")]
[Description(
"This test confirms that the tvdb id stored in the db is preserved rather than being replaced by an auto incrementing value"
)]
public void tvdbid_is_preserved([RandomNumbers(Minimum = 100, Maximum = 999, Count = 1)] int tvdbId)
{
//Arrange
@ -72,7 +74,7 @@ namespace NzbDrone.Core.Test
var sonicTarget = new SubsonicTarget(sonicRepo);
LogManager.Configuration.AddTarget("DbLogger", sonicTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, sonicTarget));
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, sonicTarget));
LogManager.Configuration.Reload();
Logger Logger = LogManager.GetCurrentClassLogger();
@ -89,7 +91,7 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(message, logItem.Message);
Assert.AreEqual(Logger.Name, logItem.Logger);
Assert.AreEqual(Logger.Name, logItem.Logger);
Assert.AreEqual(LogLevel.Info, logItem.Level);
Assert.AreEqual(Instrumentation.LogLevel.Info, logItem.Level);
}
[Test]
@ -102,7 +104,7 @@ namespace NzbDrone.Core.Test
var sonicTarget = new SubsonicTarget(sonicRepo);
LogManager.Configuration.AddTarget("DbLogger", sonicTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, sonicTarget));
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, sonicTarget));
LogManager.Configuration.Reload();
Logger Logger = LogManager.GetCurrentClassLogger();
@ -120,7 +122,7 @@ namespace NzbDrone.Core.Test
Assert.AreNotEqual(new DateTime(), logItem.Time);
Assert.AreEqual(message, logItem.Message);
Assert.AreEqual(Logger.Name, logItem.Logger);
Assert.AreEqual(LogLevel.Error, logItem.Level);
Assert.AreEqual(Instrumentation.LogLevel.Error, logItem.Level);
Assert.AreEqual(ex.GetType().ToString(), logItem.ExceptionType);
Assert.AreEqual(ex.ToString(), logItem.ExceptionString);
Assert.AreEqual(ex.Message, logItem.ExceptionMessage);
@ -136,7 +138,7 @@ namespace NzbDrone.Core.Test
var sonicTarget = new SubsonicTarget(sonicRepo);
LogManager.Configuration.AddTarget("DbLogger", sonicTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, sonicTarget));
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, sonicTarget));
LogManager.Configuration.Reload();
Logger Logger = LogManager.GetCurrentClassLogger();
@ -154,10 +156,10 @@ namespace NzbDrone.Core.Test
Assert.AreNotEqual(new DateTime(), logItem.Time);
Assert.AreEqual(ex.Message, logItem.Message);
Assert.AreEqual(Logger.Name, logItem.Logger);
Assert.AreEqual(LogLevel.Error, logItem.Level);
Assert.AreEqual(Instrumentation.LogLevel.Error, logItem.Level);
Assert.AreEqual(ex.GetType().ToString(), logItem.ExceptionType);
Assert.AreEqual(ex.ToString(), logItem.ExceptionString);
Assert.AreEqual(ex.Message, logItem.ExceptionMessage);
}
}
}
}

@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq;
using AutoMoq;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
@ -21,8 +15,8 @@ namespace NzbDrone.Core.Test
{
//Setup
var sonicRepo = MockLib.GetEmptyRepository();
sonicRepo.Add(new RootDir { Path = @"C:\TV" });
sonicRepo.Add(new RootDir { Path = @"C:\TV2" });
sonicRepo.Add(new RootDir {Path = @"C:\TV"});
sonicRepo.Add(new RootDir {Path = @"C:\TV2"});
var mocker = new AutoMoqer();
@ -48,7 +42,7 @@ namespace NzbDrone.Core.Test
//Act
var rootDirProvider = mocker.Resolve<RootDirProvider>();
rootDirProvider.Add(new RootDir{ Path = path });
rootDirProvider.Add(new RootDir {Path = path});
//Assert
@ -69,8 +63,8 @@ namespace NzbDrone.Core.Test
//Act
var rootDirProvider = mocker.Resolve<RootDirProvider>();
rootDirProvider.Add(new RootDir { Path = @"C:\TV" });
rootDirProvider.Update(new RootDir { Id = 1, Path = path });
rootDirProvider.Add(new RootDir {Path = @"C:\TV"});
rootDirProvider.Update(new RootDir {Id = 1, Path = path});
//Assert
var rootDirs = rootDirProvider.GetAll();
@ -90,7 +84,7 @@ namespace NzbDrone.Core.Test
//Act
var rootDirProvider = mocker.Resolve<RootDirProvider>();
rootDirProvider.Add(new RootDir { Path = @"C:\TV" });
rootDirProvider.Add(new RootDir {Path = @"C:\TV"});
rootDirProvider.Remove(1);
//Assert
@ -110,7 +104,7 @@ namespace NzbDrone.Core.Test
//Act
var rootDirProvider = mocker.Resolve<RootDirProvider>();
rootDirProvider.Add(new RootDir { Id = id, Path = path });
rootDirProvider.Add(new RootDir {Id = id, Path = path});
//Assert
var rootDir = rootDirProvider.GetRootDir(id);
@ -118,4 +112,4 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(path, rootDir.Path);
}
}
}
}

@ -1,31 +1,21 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using AutoMoq;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using Ninject;
using Ninject.Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Providers.Feed;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
namespace NzbDrone.Core.Test
{
[TestFixture]
public class RssProviderTest
// ReSharper disable InconsistentNaming
// ReSharper disable InconsistentNaming
{
[Test]
public void Download_feed_test()
{
var mocker = new AutoMoqer();
@ -38,19 +28,20 @@ namespace NzbDrone.Core.Test
mocker.Resolve<MockFeedProvider>().Fetch();
}
}
public class MockFeedProvider : FeedProviderBase
{
public MockFeedProvider(SeriesProvider seriesProvider, SeasonProvider seasonProvider, EpisodeProvider episodeProvider, ConfigProvider configProvider, HttpProvider httpProvider)
public MockFeedProvider(SeriesProvider seriesProvider, SeasonProvider seasonProvider,
EpisodeProvider episodeProvider, ConfigProvider configProvider,
HttpProvider httpProvider)
: base(seriesProvider, seasonProvider, episodeProvider, configProvider, httpProvider)
{
}
protected override string[] URL
{
get { return new[] { "www.google.com" }; }
get { return new[] {"www.google.com"}; }
}
protected override string Name
@ -63,4 +54,4 @@ namespace NzbDrone.Core.Test
return item.Links[0].Uri.ToString();
}
}
}
}

@ -1,15 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using AutoMoq;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using SubSonic.Repository;
namespace NzbDrone.Core.Test
{
@ -49,11 +43,15 @@ namespace NzbDrone.Core.Test
.Returns(category);
mocker.GetMock<HttpProvider>()
.Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=0&cat=tv&nzbname=This+is+an+Nzb&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns("ok");
.Setup(
s =>
s.DownloadString(
"http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=0&cat=tv&nzbname=This+is+an+Nzb&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns("ok");
//Act
bool result = mocker.Resolve<SabProvider>().AddByUrl("http://www.nzbclub.com/nzb_download.aspx?mid=1950232", "This is an Nzb");
bool result = mocker.Resolve<SabProvider>().AddByUrl(
"http://www.nzbclub.com/nzb_download.aspx?mid=1950232", "This is an Nzb");
//Assert
Assert.AreEqual(true, result);
@ -83,11 +81,15 @@ namespace NzbDrone.Core.Test
fakeConfig.Setup(c => c.GetValue("SabTvCategory", String.Empty, true)).Returns(category);
mocker.GetMock<HttpProvider>()
.Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=0&cat=tv&nzbname=This+is+an+Nzb&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns("error");
.Setup(
s =>
s.DownloadString(
"http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=0&cat=tv&nzbname=This+is+an+Nzb&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns("error");
//Act
bool result = mocker.Resolve<SabProvider>().AddByUrl("http://www.nzbclub.com/nzb_download.aspx?mid=1950232", "This is an Nzb");
bool result = mocker.Resolve<SabProvider>().AddByUrl(
"http://www.nzbclub.com/nzb_download.aspx?mid=1950232", "This is an Nzb");
//Assert
Assert.AreEqual(false, result);
@ -113,7 +115,10 @@ namespace NzbDrone.Core.Test
fakeConfig.Setup(c => c.GetValue("SabPassword", String.Empty, false)).Returns(password);
mocker.GetMock<HttpProvider>()
.Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Setup(
s =>
s.DownloadString(
"http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns(new StreamReader(@".\Files\Queue.xml").ReadToEnd());
//Act
@ -143,8 +148,11 @@ namespace NzbDrone.Core.Test
fakeConfig.Setup(c => c.GetValue("SabPassword", String.Empty, false)).Returns(password);
mocker.GetMock<HttpProvider>()
.Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns(new StreamReader(@".\Files\QueueEmpty.xml").ReadToEnd());
.Setup(
s =>
s.DownloadString(
"http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns(new StreamReader(@".\Files\QueueEmpty.xml").ReadToEnd());
//Act
bool result = mocker.Resolve<SabProvider>().IsInQueue(String.Empty);
@ -173,8 +181,11 @@ namespace NzbDrone.Core.Test
fakeConfig.Setup(c => c.GetValue("SabPassword", String.Empty, false)).Returns(password);
mocker.GetMock<HttpProvider>()
.Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns(new StreamReader(@".\Files\QueueError.xml").ReadToEnd());
.Setup(
s =>
s.DownloadString(
"http://192.168.5.55:2222/api?mode=queue&output=xml&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"))
.Returns(new StreamReader(@".\Files\QueueError.xml").ReadToEnd());
//Act
@ -184,4 +195,4 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(false, result);
}
}
}
}

@ -1,24 +1,18 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using AutoMoq;
using FizzWare.NBuilder;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using Ninject;
using Ninject.Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using SubSonic.Repository;
using TvdbLib.Data;
using System.Linq;
// ReSharper disable InconsistentNaming
namespace NzbDrone.Core.Test
{
[TestFixture]
@ -65,7 +59,6 @@ namespace NzbDrone.Core.Test
[Test]
public void Add_new_series()
{
var mocker = new AutoMoqer();
mocker.SetConstant(MockLib.GetEmptyRepository());
@ -85,16 +78,14 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(path, series.First().Path);
Assert.AreEqual(tvDbId, series.First().SeriesId);
Assert.AreEqual(qualityProfileId, series.First().QualityProfileId);
}
[Test]
[Row(new object[] { "That's Life - 2x03 -The Devil and Miss DeLucca", "That's Life" })]
[Row(new object[] { "Van.Duin.Op.Zn.Best.S02E05.DUTCH.WS.PDTV.XViD-DiFFERENT", "Van Duin Op Zn Best" })]
[Row(new object[] { "Dollhouse.S02E06.The.Left.Hand.720p.BluRay.x264-SiNNERS", "Dollhouse" })]
[Row(new object[] { "Heroes.S02.COMPLETE.German.PROPER.DVDRip.XviD-Prim3time", "Heroes" })]
[Row(new object[] {"That's Life - 2x03 -The Devil and Miss DeLucca", "That's Life"})]
[Row(new object[] {"Van.Duin.Op.Zn.Best.S02E05.DUTCH.WS.PDTV.XViD-DiFFERENT", "Van Duin Op Zn Best"})]
[Row(new object[] {"Dollhouse.S02E06.The.Left.Hand.720p.BluRay.x264-SiNNERS", "Dollhouse"})]
[Row(new object[] {"Heroes.S02.COMPLETE.German.PROPER.DVDRip.XviD-Prim3time", "Heroes"})]
[Ignore("should be updated to validate agains a remote episode instance rather than just the title string")]
public void Test_Parse_Success(string postTitle, string title)
{
@ -110,14 +101,14 @@ namespace NzbDrone.Core.Test
mocker.SetConstant(MockLib.GetEmptyRepository());
mocker.Resolve<IRepository>().Add(Builder<Series>.CreateNew()
.With(c => c.Monitored = true)
.With(c => c.SeriesId = 12)
.Build());
.With(c => c.Monitored = true)
.With(c => c.SeriesId = 12)
.Build());
mocker.Resolve<IRepository>().Add(Builder<Series>.CreateNew()
.With(c => c.Monitored = false)
.With(c => c.SeriesId = 11)
.Build());
.With(c => c.Monitored = false)
.With(c => c.SeriesId = 11)
.Build());
//Act, Assert
@ -128,7 +119,6 @@ namespace NzbDrone.Core.Test
}
[Test]
[Row(12, QualityTypes.TV, true)]
[Row(12, QualityTypes.Unknown, false)]
@ -139,14 +129,14 @@ namespace NzbDrone.Core.Test
public void QualityWanted(int seriesId, QualityTypes qualityTypes, Boolean result)
{
var quality = Builder<QualityProfile>.CreateNew()
.With(q => q.Allowed = new List<QualityTypes>() { QualityTypes.BDRip, QualityTypes.DVD, QualityTypes.TV })
.With(q => q.Cutoff = QualityTypes.DVD)
.Build();
.With(q => q.Allowed = new List<QualityTypes> {QualityTypes.BDRip, QualityTypes.DVD, QualityTypes.TV})
.With(q => q.Cutoff = QualityTypes.DVD)
.Build();
var series = Builder<Series>.CreateNew()
.With(c => c.SeriesId = 12)
.With(c => c.QualityProfileId = quality.QualityProfileId)
.Build();
.With(c => c.SeriesId = 12)
.With(c => c.QualityProfileId = quality.QualityProfileId)
.Build();
var mocker = new AutoMoqer();
var emptyRepository = MockLib.GetEmptyRepository();
@ -154,7 +144,7 @@ namespace NzbDrone.Core.Test
mocker.GetMock<QualityProvider>()
.Setup(c => c.Find(quality.QualityProfileId)).Returns(quality);
.Setup(c => c.Find(quality.QualityProfileId)).Returns(quality);
emptyRepository.Add(series);
@ -165,4 +155,4 @@ namespace NzbDrone.Core.Test
Assert.AreEqual(result, needed);
}
}
}
}

@ -1,15 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using AutoMoq;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using Moq;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using SubSonic.Repository;
namespace NzbDrone.Core.Test
{
@ -35,11 +29,11 @@ namespace NzbDrone.Core.Test
}
[Test]
[ExpectedException(typeof(ArgumentException))]
[ExpectedException(typeof (ArgumentException))]
public void empty_folder_path_throws()
{
var mocker = new AutoMoqer();
mocker.Resolve<SyncProvider>().GetUnmappedFolders("");
}
}
}
}

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using NzbDrone.Core.Providers;
namespace NzbDrone.Core.Test
@ -40,19 +36,19 @@ namespace NzbDrone.Core.Test
[Test]
[Row(new object[] { "CAPITAL", "capital", true })]
[Row(new object[] { "Something!!", "Something", true })]
[Row(new object[] { "Simpsons 2000", "Simpsons", true })]
[Row(new object[] { "Simp222sons", "Simpsons", true })]
[Row(new object[] { "Simpsons", "The Simpsons", true })]
[Row(new object[] { "Law and order", "Law & order", true })]
[Row(new object[] { "xxAndxx", "xxxx", false })]
[Row(new object[] { "Andxx", "xx", false })]
[Row(new object[] { "xxAnd", "xx", false })]
[Row(new object[] { "Thexx", "xx", false })]
[Row(new object[] { "Thexx", "xx", false })]
[Row(new object[] { "xxThexx", "xxxxx", false })]
[Row(new object[] { "Simpsons The", "Simpsons", true })]
[Row(new object[] {"CAPITAL", "capital", true})]
[Row(new object[] {"Something!!", "Something", true})]
[Row(new object[] {"Simpsons 2000", "Simpsons", true})]
[Row(new object[] {"Simp222sons", "Simpsons", true})]
[Row(new object[] {"Simpsons", "The Simpsons", true})]
[Row(new object[] {"Law and order", "Law & order", true})]
[Row(new object[] {"xxAndxx", "xxxx", false})]
[Row(new object[] {"Andxx", "xx", false})]
[Row(new object[] {"xxAnd", "xx", false})]
[Row(new object[] {"Thexx", "xx", false})]
[Row(new object[] {"Thexx", "xx", false})]
[Row(new object[] {"xxThexx", "xxxxx", false})]
[Row(new object[] {"Simpsons The", "Simpsons", true})]
public void Name_match_test(string a, string b, bool match)
{
bool result = TvDbProvider.IsTitleMatch(a, b);
@ -85,8 +81,5 @@ namespace NzbDrone.Core.Test
//assert
Assert.IsNull(result);
}
}
}
}

@ -2,22 +2,16 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Hosting;
using Ninject;
using NLog.Config;
using NLog.Targets;
using NLog;
using NzbDrone.Core.Instrumentation;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Providers.Fakes;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using SubSonic.DataProviders;
using SubSonic.Query;
using SubSonic.Repository;
using NLog;
using System.Linq;
namespace NzbDrone.Core
{
@ -28,6 +22,45 @@ namespace NzbDrone.Core
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static string _startupPath;
public static String AppPath
{
get
{
if (!String.IsNullOrWhiteSpace(HostingEnvironment.ApplicationPhysicalPath))
{
return HostingEnvironment.ApplicationPhysicalPath;
}
return Directory.GetCurrentDirectory();
}
}
public static string ExecutablePath
{
get
{
//var uri = new Uri(Assembly.EscapedCodeBase);
//return Path.GetDirectoryName(uri.LocalPath);
return Directory.GetCurrentDirectory();
}
}
public static string StartupPath
{
get { return _startupPath; }
}
public static StandardKernel NinjectKernel
{
get
{
if (_kernel == null)
{
BindKernel();
}
return _kernel;
}
}
public static void BindKernel()
{
lock (KernelLock)
@ -42,10 +75,12 @@ namespace NzbDrone.Core
var AppDataPath = new DirectoryInfo(Path.Combine(AppPath, "App_Data", "nzbdrone.db"));
if (!AppDataPath.Exists) AppDataPath.Create();
string connectionString = String.Format("Data Source={0};Version=3;", Path.Combine(AppDataPath.FullName, "nzbdrone.db"));
string connectionString = String.Format("Data Source={0};Version=3;",
Path.Combine(AppDataPath.FullName, "nzbdrone.db"));
var dbProvider = ProviderFactory.GetProvider(connectionString, "System.Data.SQLite");
string logConnectionString = String.Format("Data Source={0};Version=3;", Path.Combine(AppDataPath.FullName, "log.db"));
string logConnectionString = String.Format("Data Source={0};Version=3;",
Path.Combine(AppDataPath.FullName, "log.db"));
var logDbProvider = ProviderFactory.GetProvider(logConnectionString, "System.Data.SQLite");
@ -80,9 +115,11 @@ namespace NzbDrone.Core
_kernel.Bind<LogProvider>().ToSelf().InSingletonScope();
_kernel.Bind<MediaFileProvider>().ToSelf().InSingletonScope();
_kernel.Bind<TimerProvider>().ToSelf().InSingletonScope();
_kernel.Bind<IRepository>().ToMethod(c => new SimpleRepository(dbProvider, SimpleRepositoryOptions.RunMigrations)).InSingletonScope();
_kernel.Bind<IRepository>().ToMethod(
c => new SimpleRepository(dbProvider, SimpleRepositoryOptions.RunMigrations)).InSingletonScope();
_kernel.Bind<IRepository>().ToConstant(logRepository).WhenInjectedInto<SubsonicTarget>().InSingletonScope();
_kernel.Bind<IRepository>().ToConstant(logRepository).WhenInjectedInto<SubsonicTarget>().
InSingletonScope();
_kernel.Bind<IRepository>().ToConstant(logRepository).WhenInjectedInto<LogProvider>().InSingletonScope();
ForceMigration(_kernel.Get<IRepository>());
@ -97,46 +134,6 @@ namespace NzbDrone.Core
}
}
public static String AppPath
{
get
{
if (!String.IsNullOrWhiteSpace(HostingEnvironment.ApplicationPhysicalPath))
{
return HostingEnvironment.ApplicationPhysicalPath;
}
return Directory.GetCurrentDirectory();
}
}
public static string ExecutablePath
{
get
{
//var uri = new Uri(Assembly.EscapedCodeBase);
//return Path.GetDirectoryName(uri.LocalPath);
return Directory.GetCurrentDirectory();
}
}
public static string StartupPath
{
get { return _startupPath; }
}
public static StandardKernel NinjectKernel
{
get
{
if (_kernel == null)
{
BindKernel();
}
return _kernel;
}
}
private static void ForceMigration(IRepository repository)
{
repository.GetPaged<Series>(0, 1);
@ -148,23 +145,24 @@ namespace NzbDrone.Core
}
/// <summary>
/// This method forces IISExpress process to exit with the host application
/// This method forces IISExpress process to exit with the host application
/// </summary>
public static void DedicateToHost()
{
try
{
Logger.Debug("Attaching to parent process for automatic termination.");
var pc = new PerformanceCounter("Process", "Creating Process ID", Process.GetCurrentProcess().ProcessName);
var pid = (int)pc.NextValue();
var pc = new PerformanceCounter("Process", "Creating Process ID",
Process.GetCurrentProcess().ProcessName);
var pid = (int) pc.NextValue();
var hostProcess = Process.GetProcessById(pid);
hostProcess.EnableRaisingEvents = true;
hostProcess.Exited += (delegate
{
Logger.Info("Host has been terminated. Shutting down web server.");
ShutDown();
});
{
Logger.Info("Host has been terminated. Shutting down web server.");
ShutDown();
});
Logger.Debug("Successfully Attached to host. Process ID: {0}", pid);
}
@ -184,8 +182,10 @@ namespace NzbDrone.Core
{
//Setup the default providers in the Providers table
string nzbMatrixRss = "http://rss.nzbmatrix.com/rss.php?page=download&username={USERNAME}&apikey={APIKEY}&subcat=6,41&english=1";
string nzbMatrixApi = "http://rss.nzbmatrix.com/rss.php?page=download&username={USERNAME}&apikey={APIKEY}&subcat=6,41&english=1&age={AGE}&term={TERM}";
string nzbMatrixRss =
"http://rss.nzbmatrix.com/rss.php?page=download&username={USERNAME}&apikey={APIKEY}&subcat=6,41&english=1";
string nzbMatrixApi =
"http://rss.nzbmatrix.com/rss.php?page=download&username={USERNAME}&apikey={APIKEY}&subcat=6,41&english=1&age={AGE}&term={TERM}";
string nzbsOrgRss = "http://nzbs.org/rss.php?type=1&dl=1&num=100&i={UID}&h={HASH}";
string nzbsOrgApi = String.Empty;
string nzbsrusRss = "http://www.nzbsrus.com/rssfeed.php?cat=91,75&i={UID}&h={HASH}";
@ -210,13 +210,13 @@ namespace NzbDrone.Core
};
var nzbsrusIndexer = new Indexer
{
IndexerId = 3,
IndexerName = "Nzbsrus",
RssUrl = nzbsrusRss,
ApiUrl = nzbsrusApi,
Order = 3
};
{
IndexerId = 3,
IndexerName = "Nzbsrus",
RssUrl = nzbsrusRss,
ApiUrl = nzbsrusApi,
Order = 3
};
//NzbMatrix
Logger.Debug("Checking for NzbMatrix Indexer");
@ -273,18 +273,20 @@ namespace NzbDrone.Core
private static void SetupDefaultQualityProfiles(IRepository repository)
{
var sd = new QualityProfile
{
Name = "SD",
Allowed = new List<QualityTypes> { QualityTypes.TV, QualityTypes.DVD },
Cutoff = QualityTypes.TV
};
{
Name = "SD",
Allowed = new List<QualityTypes> {QualityTypes.TV, QualityTypes.DVD},
Cutoff = QualityTypes.TV
};
var hd = new QualityProfile
{
Name = "HD",
Allowed = new List<QualityTypes> { QualityTypes.HDTV, QualityTypes.WEBDL, QualityTypes.BDRip, QualityTypes.Bluray720 },
Cutoff = QualityTypes.HDTV
};
{
Name = "HD",
Allowed =
new List<QualityTypes>
{QualityTypes.HDTV, QualityTypes.WEBDL, QualityTypes.BDRip, QualityTypes.Bluray720},
Cutoff = QualityTypes.HDTV
};
//Add or Update SD
Logger.Debug(String.Format("Checking for default QualityProfile: {0}", sd.Name));

@ -7,25 +7,70 @@ namespace NzbDrone.Core.Helpers
public static class EpisodeSortingHelper
{
private static readonly List<EpisodeSortingType> SeparatorStyles = new List<EpisodeSortingType>
{
new EpisodeSortingType {Id = 0, Name = "Dash", Pattern = " - "},
new EpisodeSortingType {Id = 1, Name = "Space", Pattern = " "}
};
{
new EpisodeSortingType
{
Id = 0,
Name = "Dash",
Pattern = " - "
},
new EpisodeSortingType
{
Id = 1,
Name = "Space",
Pattern = " "
}
};
private static readonly List<EpisodeSortingType> NumberStyles = new List<EpisodeSortingType>
{
new EpisodeSortingType { Id = 0, Name = "1x05", Pattern = "%sx%0e"},
new EpisodeSortingType { Id = 1, Name = "01x05", Pattern = "%0sx%0e"},
new EpisodeSortingType { Id = 2, Name = "S01E05", Pattern = "S%0sE%0e"},
new EpisodeSortingType { Id = 3, Name = "s01e05", Pattern = "s%0se%0e"}
};
{
new EpisodeSortingType
{
Id = 0,
Name = "1x05",
Pattern = "%sx%0e"
},
new EpisodeSortingType
{
Id = 1,
Name = "01x05",
Pattern = "%0sx%0e"
},
new EpisodeSortingType
{
Id = 2,
Name = "S01E05",
Pattern = "S%0sE%0e"
},
new EpisodeSortingType
{
Id = 3,
Name = "s01e05",
Pattern = "s%0se%0e"
}
};
private static readonly List<EpisodeSortingType> MultiEpisodeStyles = new List<EpisodeSortingType>
{
new EpisodeSortingType { Id = 0, Name = "Extend", Pattern = "" },
new EpisodeSortingType { Id = 1, Name = "Duplicate", Pattern = "" },
new EpisodeSortingType { Id = 2, Name = "Repeat", Pattern = "" }
};
{
new EpisodeSortingType
{
Id = 0,
Name = "Extend",
Pattern = ""
},
new EpisodeSortingType
{
Id = 1,
Name = "Duplicate",
Pattern = ""
},
new EpisodeSortingType
{
Id = 2,
Name = "Repeat",
Pattern = ""
}
};
public static List<EpisodeSortingType> GetSeparatorStyles()
{
@ -72,4 +117,4 @@ namespace NzbDrone.Core.Helpers
return MultiEpisodeStyles.Single(s => s.Name == name);
}
}
}
}

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Core.Model;
namespace NzbDrone.Core.Helpers
@ -9,70 +8,302 @@ namespace NzbDrone.Core.Helpers
public static class SceneNameHelper
{
private static readonly List<SceneNameModel> SceneNameMappings = new List<SceneNameModel>
{
new SceneNameModel { SeriesId = 72546, Name = "CSI" },
new SceneNameModel { SeriesId = 73696, Name = "CSI New York" },
new SceneNameModel { SeriesId = 73696, Name = "CSI NY" },
new SceneNameModel { SeriesId = 110381, Name = "Archer" },
new SceneNameModel { SeriesId = 83897, Name = "Life After People The Series" },
new SceneNameModel { SeriesId = 83897, Name = "Life After People" },
new SceneNameModel { SeriesId = 80552, Name = "Kitchen Nightmares US" },
new SceneNameModel { SeriesId = 71256, Name = "The Daily Show" },
new SceneNameModel { SeriesId = 71256, Name = "The Daily Show with Jon Stewart" },
new SceneNameModel { SeriesId = 75692, Name = "Law and Order SVU" },
new SceneNameModel { SeriesId = 75692, Name = "Law and Order Special Victims Unit" },
new SceneNameModel { SeriesId = 71489, Name = "Law and Order Criminal Intent" },
new SceneNameModel { SeriesId = 71489, Name = "Law and Order CI" },
new SceneNameModel { SeriesId = 79590, Name = "Dancing With The Stars US" },
new SceneNameModel { SeriesId = 73387, Name = "Craig Ferguson" },
new SceneNameModel { SeriesId = 85355, Name = "Jimmy Fallon" },
new SceneNameModel { SeriesId = 75088, Name = "David Letterman" },
new SceneNameModel { SeriesId = 76706, Name = "Big Brother US" },
new SceneNameModel { SeriesId = 105521, Name = "The Colony" },
new SceneNameModel { SeriesId = 105521, Name = "The Colony US" },
new SceneNameModel { SeriesId = 76235, Name = "Americas Funniest Home Videos" },
new SceneNameModel { SeriesId = 76235, Name = "AFHV" },
new SceneNameModel { SeriesId = 139941, Name = "Childrens Hospital US" },
new SceneNameModel { SeriesId = 139941, Name = "Childrens Hospital" },
new SceneNameModel { SeriesId = 83123, Name = "Merlin" },
new SceneNameModel { SeriesId = 83123, Name = "Merlin 2008" },
new SceneNameModel { SeriesId = 76779, Name = "WWE Monday Night RAW" },
new SceneNameModel { SeriesId = 164951, Name = "Shit My Dad Says" },
new SceneNameModel { SeriesId = 83714, Name = "Genius with Dave Gorman" },
new SceneNameModel { SeriesId = 168161, Name = "Law and Order Los Angeles" },
new SceneNameModel { SeriesId = 168161, Name = "Law and Order LA" },
new SceneNameModel { SeriesId = 77526, Name = "Star Trek TOS" },
new SceneNameModel { SeriesId = 72073, Name = "Star Trek DS9" },
new SceneNameModel { SeriesId = 72194, Name = "Ellen Degeneres" },
new SceneNameModel { SeriesId = 72194, Name = "Ellen Degeneres" },
new SceneNameModel { SeriesId = 195831, Name = "Drinking Made Easy" },
new SceneNameModel { SeriesId = 195831, Name = "Zane Lampreys Drinking Made Easy" },
new SceneNameModel { SeriesId = 76133, Name = "Poirot" },
new SceneNameModel { SeriesId = 76133, Name = "Agatha Christies Poirot" },
new SceneNameModel { SeriesId = 70870, Name = "The Real World Road Rules Challenge" },
new SceneNameModel { SeriesId = 70870, Name = "The Challenge Cutthroat" },
new SceneNameModel { SeriesId = 77444, Name = "This Old House Program" },
new SceneNameModel { SeriesId = 73290, Name = "60 Minutes US" },
new SceneNameModel { SeriesId = 194751, Name = "Conan" },
new SceneNameModel { SeriesId = 194751, Name = "Conan 2010" },
new SceneNameModel { SeriesId = 164451, Name = "Carlos 2010" },
new SceneNameModel { SeriesId = 70726, Name = "Babalon 5" },
new SceneNameModel { SeriesId = 70726, Name = "Babalon5" },
new SceneNameModel { SeriesId = 83714, Name = "Genius" },
new SceneNameModel { SeriesId = 83714, Name = "Genius With Dave Gormand" },
new SceneNameModel { SeriesId = 212571, Name = "Come Fly With Me 2010" },
new SceneNameModel { SeriesId = 81563, Name = "Border Security" },
new SceneNameModel { SeriesId = 81563, Name = "Border Security Australias Frontline" },
new SceneNameModel { SeriesId = 172381, Name = "Silent Library US" },
new SceneNameModel { SeriesId = 131791, Name = "Sci-Fi Science" },
new SceneNameModel { SeriesId = 80646, Name = "Frontline" },
new SceneNameModel { SeriesId = 80646, Name = "Frontline US" },
new SceneNameModel { SeriesId = 189931, Name = "RBT AU" },
new SceneNameModel { SeriesId = 73255, Name = "House" },
new SceneNameModel { SeriesId = 73255, Name = "House MD" },
new SceneNameModel { SeriesId = 73244, Name = "The Office" },
new SceneNameModel { SeriesId = 73244, Name = "The Office US" },
};
{
new SceneNameModel
{SeriesId = 72546, Name = "CSI"},
new SceneNameModel
{
SeriesId = 73696,
Name = "CSI New York"
},
new SceneNameModel
{SeriesId = 73696, Name = "CSI NY"},
new SceneNameModel
{
SeriesId = 110381,
Name = "Archer"
},
new SceneNameModel
{
SeriesId = 83897,
Name =
"Life After People The Series"
},
new SceneNameModel
{
SeriesId = 83897,
Name = "Life After People"
},
new SceneNameModel
{
SeriesId = 80552,
Name = "Kitchen Nightmares US"
},
new SceneNameModel
{
SeriesId = 71256,
Name = "The Daily Show"
},
new SceneNameModel
{
SeriesId = 71256,
Name =
"The Daily Show with Jon Stewart"
},
new SceneNameModel
{
SeriesId = 75692,
Name = "Law and Order SVU"
},
new SceneNameModel
{
SeriesId = 75692,
Name =
"Law and Order Special Victims Unit"
},
new SceneNameModel
{
SeriesId = 71489,
Name =
"Law and Order Criminal Intent"
},
new SceneNameModel
{
SeriesId = 71489,
Name = "Law and Order CI"
},
new SceneNameModel
{
SeriesId = 79590,
Name = "Dancing With The Stars US"
},
new SceneNameModel
{
SeriesId = 73387,
Name = "Craig Ferguson"
},
new SceneNameModel
{
SeriesId = 85355,
Name = "Jimmy Fallon"
},
new SceneNameModel
{
SeriesId = 75088,
Name = "David Letterman"
},
new SceneNameModel
{
SeriesId = 76706,
Name = "Big Brother US"
},
new SceneNameModel
{
SeriesId = 105521,
Name = "The Colony"
},
new SceneNameModel
{
SeriesId = 105521,
Name = "The Colony US"
},
new SceneNameModel
{
SeriesId = 76235,
Name =
"Americas Funniest Home Videos"
},
new SceneNameModel
{SeriesId = 76235, Name = "AFHV"},
new SceneNameModel
{
SeriesId = 139941,
Name = "Childrens Hospital US"
},
new SceneNameModel
{
SeriesId = 139941,
Name = "Childrens Hospital"
},
new SceneNameModel
{SeriesId = 83123, Name = "Merlin"},
new SceneNameModel
{
SeriesId = 83123,
Name = "Merlin 2008"
},
new SceneNameModel
{
SeriesId = 76779,
Name = "WWE Monday Night RAW"
},
new SceneNameModel
{
SeriesId = 164951,
Name = "Shit My Dad Says"
},
new SceneNameModel
{
SeriesId = 83714,
Name = "Genius with Dave Gorman"
},
new SceneNameModel
{
SeriesId = 168161,
Name = "Law and Order Los Angeles"
},
new SceneNameModel
{
SeriesId = 168161,
Name = "Law and Order LA"
},
new SceneNameModel
{
SeriesId = 77526,
Name = "Star Trek TOS"
},
new SceneNameModel
{
SeriesId = 72073,
Name = "Star Trek DS9"
},
new SceneNameModel
{
SeriesId = 72194,
Name = "Ellen Degeneres"
},
new SceneNameModel
{
SeriesId = 72194,
Name = "Ellen Degeneres"
},
new SceneNameModel
{
SeriesId = 195831,
Name = "Drinking Made Easy"
},
new SceneNameModel
{
SeriesId = 195831,
Name =
"Zane Lampreys Drinking Made Easy"
},
new SceneNameModel
{SeriesId = 76133, Name = "Poirot"},
new SceneNameModel
{
SeriesId = 76133,
Name = "Agatha Christies Poirot"
},
new SceneNameModel
{
SeriesId = 70870,
Name =
"The Real World Road Rules Challenge"
},
new SceneNameModel
{
SeriesId = 70870,
Name = "The Challenge Cutthroat"
},
new SceneNameModel
{
SeriesId = 77444,
Name = "This Old House Program"
},
new SceneNameModel
{
SeriesId = 73290,
Name = "60 Minutes US"
},
new SceneNameModel
{SeriesId = 194751, Name = "Conan"},
new SceneNameModel
{
SeriesId = 194751,
Name = "Conan 2010"
},
new SceneNameModel
{
SeriesId = 164451,
Name = "Carlos 2010"
},
new SceneNameModel
{
SeriesId = 70726,
Name = "Babalon 5"
},
new SceneNameModel
{
SeriesId = 70726,
Name = "Babalon5"
},
new SceneNameModel
{SeriesId = 83714, Name = "Genius"},
new SceneNameModel
{
SeriesId = 83714,
Name = "Genius With Dave Gormand"
},
new SceneNameModel
{
SeriesId = 212571,
Name = "Come Fly With Me 2010"
},
new SceneNameModel
{
SeriesId = 81563,
Name = "Border Security"
},
new SceneNameModel
{
SeriesId = 81563,
Name =
"Border Security Australias Frontline"
},
new SceneNameModel
{
SeriesId = 172381,
Name = "Silent Library US"
},
new SceneNameModel
{
SeriesId = 131791,
Name = "Sci-Fi Science"
},
new SceneNameModel
{
SeriesId = 80646,
Name = "Frontline"
},
new SceneNameModel
{
SeriesId = 80646,
Name = "Frontline US"
},
new SceneNameModel
{
SeriesId = 189931,
Name = "RBT AU"
},
new SceneNameModel
{SeriesId = 73255, Name = "House"},
new SceneNameModel
{
SeriesId = 73255,
Name = "House MD"
},
new SceneNameModel
{
SeriesId = 73244,
Name = "The Office"
},
new SceneNameModel
{
SeriesId = 73244,
Name = "The Office US"
},
};
public static int FindByName(string cleanSeriesName)
{
@ -95,6 +326,5 @@ namespace NzbDrone.Core.Helpers
return results;
}
}
}
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace NzbDrone.Core.Helpers
{
@ -15,4 +11,4 @@ namespace NzbDrone.Core.Helpers
//return Dns.GetHostName();
}
}
}
}

@ -11,17 +11,18 @@ namespace NzbDrone.Core.Instrumentation
protected override void Write(LogEventInfo logEvent)
{
if (logEvent.Exception == null)
throw new InvalidOperationException(@"Missing Exception Object.. Please Use Logger.FatalException() or Logger.ErrorException() rather
throw new InvalidOperationException(
@"Missing Exception Object.. Please Use Logger.FatalException() or Logger.ErrorException() rather
than Logger.Fatal() and Logger.Error()");
if (!Debugger.IsAttached)
{
new Client
{
ApiKey = "43BBF60A-EB2A-4C1C-B09E-422ADF637265",
ApplicationName = "NZBDrone",
CurrentException = logEvent.Exception
}.Submit();
{
ApiKey = "43BBF60A-EB2A-4C1C-B09E-422ADF637265",
ApplicationName = "NZBDrone",
CurrentException = logEvent.Exception
}.Submit();
}
}
}

@ -38,4 +38,4 @@ namespace NzbDrone.Core.Instrumentation
get { return Level.ToString(); }
}
}
}
}

@ -1,8 +1,8 @@
using System.Diagnostics;
using System.IO;
using Ninject;
using NLog;
using NLog.Config;
using Ninject;
namespace NzbDrone.Core.Instrumentation
{
@ -15,7 +15,8 @@ namespace NzbDrone.Core.Instrumentation
LogManager.ThrowExceptions = true;
}
LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(CentralDispatch.AppPath, "log.config"), false);
LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(CentralDispatch.AppPath, "log.config"),
false);
LogManager.ConfigurationReloaded += ((s, e) => BindCustomLoggers());
BindCustomLoggers();
}
@ -35,9 +36,5 @@ namespace NzbDrone.Core.Instrumentation
LogManager.Configuration.Reload();
}
}
}
}

@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq;
using NLog;
using SubSonic.Repository;
namespace NzbDrone.Core.Instrumentation
{
public class LogProvider
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
@ -29,4 +25,4 @@ namespace NzbDrone.Core.Instrumentation
Logger.Info("Cleared Log History");
}
}
}
}

@ -8,6 +8,11 @@ namespace NzbDrone.Core.Instrumentation
{
private static readonly Logger Logger = LogManager.GetLogger("NzbDrone.SubSonic");
public override Encoding Encoding
{
get { return Encoding.Default; }
}
public override void Write(char[] buffer, int index, int count)
{
@ -23,10 +28,5 @@ namespace NzbDrone.Core.Instrumentation
{
Logger.Trace(value);
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
}

@ -1,11 +1,7 @@
using System;
using System.Diagnostics;
using Exceptioneer.WindowsFormsClient;
using NLog;
using NLog.Targets;
using SubSonic.Repository;
using Ninject;
using NzbDrone.Core.Repository;
namespace NzbDrone.Core.Instrumentation
{

@ -19,8 +19,8 @@ namespace NzbDrone.Core.Model
public override string ToString()
{
return string.Format("Series:{0} Season:{1} Episode:{2}", SeriesTitle, SeasonNumber, String.Join(",", Episodes));
return string.Format("Series:{0} Season:{1} Episode:{2}", SeriesTitle, SeasonNumber,
String.Join(",", Episodes));
}
}
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository;
namespace NzbDrone.Core.Model
{
@ -13,4 +9,4 @@ namespace NzbDrone.Core.Model
public EpisodeFile EpisodeFile { get; set; }
public bool NewDownload { get; set; }
}
}
}

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Core.Model
namespace NzbDrone.Core.Model
{
public class EpisodeSortingType
{
@ -11,4 +6,4 @@ namespace NzbDrone.Core.Model
public string Name { get; set; }
public string Pattern { get; set; }
}
}
}

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Core.Model
namespace NzbDrone.Core.Model
{
public enum EpisodeStatusType
{
@ -11,4 +6,4 @@ namespace NzbDrone.Core.Model
Grabbed = 1,
Downloaded = 2
}
}
}

@ -10,7 +10,7 @@ namespace NzbDrone.Core.Model.Notification
}
/// <summary>
/// Gets or sets the unique id.
/// Gets or sets the unique id.
/// </summary>
/// <value>The Id.</value>
public Guid Id { get; private set; }
@ -20,7 +20,7 @@ namespace NzbDrone.Core.Model.Notification
public BasicNotificationType Type { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not this message should be automatically dismissed after a period of time.
/// Gets or sets a value indicating whether or not this message should be automatically dismissed after a period of time.
/// </summary>
/// <value><c>true</c> if [auto dismiss]; otherwise, <c>false</c>.</value>
public bool AutoDismiss { get; set; }

@ -18,53 +18,52 @@ namespace NzbDrone.Core.Model.Notification
/// <summary>
/// Gets or sets the unique id.
/// Gets or sets the unique id.
/// </summary>
/// <value>The Id.</value>
public Guid Id { get; private set; }
/// <summary>
/// Gets or sets the title for this notification.
/// Gets or sets the title for this notification.
/// </summary>
/// <value>The title.</value>
public String Title { get; set; }
/// <summary>
/// Gets or sets the current status of this task. this field could be use to show the currently processing item in a long running task.
/// Gets or sets the current status of this task. this field could be use to show the currently processing item in a long running task.
/// </summary>
/// <value>The current status.</value>
public String CurrentStatus { get; set; }
/// <summary>
/// Gets or sets the completion status in percent.
/// Gets or sets the completion status in percent.
/// </summary>
/// <value>The percent complete.</value>
public int PercentComplete
{
get
{
return Convert.ToInt32(Convert.ToDouble(ProgressValue) / Convert.ToDouble(ProgressMax) * 100);
}
get { return Convert.ToInt32(Convert.ToDouble(ProgressValue)/Convert.ToDouble(ProgressMax)*100); }
}
/// <summary>
/// Gets or sets the total number of items that need to be completed
/// Gets or sets the total number of items that need to be completed
/// </summary>
/// <value>The progress max.</value>
public int ProgressMax { get; set; }
/// <summary>
/// Gets or sets the number of items successfully completed.
/// Gets or sets the number of items successfully completed.
/// </summary>
/// <value>The progress value.</value>
public int ProgressValue { get; set; }
/// <summary>
/// Gets or sets the status.
/// Gets or sets the status.
/// </summary>
/// <value>The status.</value>
public ProgressNotificationStatus Status { get; set; }
#region IDisposable Members
public void Dispose()
{
if (Status == ProgressNotificationStatus.InProgress)
@ -73,5 +72,7 @@ namespace NzbDrone.Core.Model.Notification
Status = ProgressNotificationStatus.Failed;
}
}
#endregion
}
}

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
namespace NzbDrone.Core.Model
{
@ -17,4 +12,4 @@ namespace NzbDrone.Core.Model
return Title.EndsWith("(Passworded)", StringComparison.InvariantCultureIgnoreCase);
}
}
}
}

@ -1,13 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Core.Model
namespace NzbDrone.Core.Model
{
public class SceneNameModel
{
public string Name { get; set; }
public int SeriesId { get; set; }
}
}
}

@ -14,6 +14,5 @@ namespace NzbDrone.Core.Model
{
return string.Format("Series:{0} Season:{1}", SeriesTitle, SeasonNumber);
}
}
}

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using NzbDrone.Core.Repository;
namespace NzbDrone.Core.Model
@ -12,4 +9,4 @@ namespace NzbDrone.Core.Model
public List<Episode> Today { get; set; }
public List<Episode> Week { get; set; }
}
}
}

@ -1,12 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository.Quality;
namespace NzbDrone.Core
@ -16,22 +13,31 @@ namespace NzbDrone.Core
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly Regex[] ReportTitleRegex = new[]
{
new Regex(@"(?<title>.+?)?\W?(?<year>\d+?)?\WS?(?<season>\d+)(?:\-|\.|[a-z])(?<episode>\d+)\W(?!\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"(?<title>.+?)?\W?(?<year>\d+?)?\WS?(?<season>\d+)(?<episode>\d{2})\W(?!\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled) //Supports 103/113 naming
};
{
new Regex(
@"(?<title>.+?)?\W?(?<year>\d+?)?\WS?(?<season>\d+)(?:\-|\.|[a-z])(?<episode>\d+)\W(?!\\)",
RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(
@"(?<title>.+?)?\W?(?<year>\d+?)?\WS?(?<season>\d+)(?<episode>\d{2})\W(?!\\)",
RegexOptions.IgnoreCase | RegexOptions.Compiled)
//Supports 103/113 naming
};
private static readonly Regex[] SeasonReportTitleRegex = new[]
{
new Regex(@"(?<title>.+?)?\W?(?<year>\d{4}?)?\W(?:S|Season)?\W?(?<season>\d+)(?!\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
};
{
new Regex(
@"(?<title>.+?)?\W?(?<year>\d{4}?)?\W(?:S|Season)?\W?(?<season>\d+)(?!\\)",
RegexOptions.IgnoreCase |
RegexOptions.Compiled),
};
private static readonly Regex NormalizeRegex = new Regex(@"((\s|^)the(\s|$))|((\s|^)and(\s|$))|[^a-z]", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex NormalizeRegex = new Regex(@"((\s|^)the(\s|$))|((\s|^)and(\s|$))|[^a-z]",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Parses a post title into list of episodes it contains
/// Parses a post title into list of episodes it contains
/// </summary>
/// <param name="title">Title of the report</param>
/// <param name = "title">Title of the report</param>
/// <returns>List of episodes contained to the post</returns>
internal static EpisodeParseResult ParseEpisodeInfo(string title)
{
@ -53,18 +59,17 @@ namespace NzbDrone.Core
}
var parsedEpisode = new EpisodeParseResult
{
Proper = title.ToLower().Contains("proper"),
SeriesTitle = seriesName,
SeasonNumber = Convert.ToInt32(match[0].Groups["season"].Value),
Year = year,
Episodes = new List<int>()
};
{
Proper = title.ToLower().Contains("proper"),
SeriesTitle = seriesName,
SeasonNumber = Convert.ToInt32(match[0].Groups["season"].Value),
Year = year,
Episodes = new List<int>()
};
foreach (Match matchGroup in match)
{
parsedEpisode.Episodes.Add(Convert.ToInt32(matchGroup.Groups["episode"].Value));
}
parsedEpisode.Quality = ParseQuality(title);
@ -79,9 +84,9 @@ namespace NzbDrone.Core
}
/// <summary>
/// Parses a post title into season it contains
/// Parses a post title into season it contains
/// </summary>
/// <param name="title">Title of the report</param>
/// <param name = "title">Title of the report</param>
/// <returns>Season information contained in the post</returns>
internal static SeasonParseResult ParseSeasonInfo(string title)
{
@ -105,11 +110,11 @@ namespace NzbDrone.Core
var seasonNumber = Convert.ToInt32(match[0].Groups["season"].Value);
var result = new SeasonParseResult
{
SeriesTitle = seriesName,
SeasonNumber = seasonNumber,
Year = year
};
{
SeriesTitle = seriesName,
SeasonNumber = seasonNumber,
Year = year
};
result.Quality = ParseQuality(title);
@ -123,9 +128,9 @@ namespace NzbDrone.Core
}
/// <summary>
/// Parses a post title to find the series that relates to it
/// Parses a post title to find the series that relates to it
/// </summary>
/// <param name="title">Title of the report</param>
/// <param name = "title">Title of the report</param>
/// <returns>Normalized Series Name</returns>
internal static string ParseSeriesName(string title)
{
@ -155,9 +160,9 @@ namespace NzbDrone.Core
}
/// <summary>
/// Parses proper status out of a report title
/// Parses proper status out of a report title
/// </summary>
/// <param name="title">Title of the report</param>
/// <param name = "title">Title of the report</param>
/// <returns></returns>
internal static bool ParseProper(string title)
{
@ -229,10 +234,10 @@ namespace NzbDrone.Core
}
/// <summary>
/// Normalizes the title. removing all non-word characters as well as common tokens
/// such as 'the' and 'and'
/// Normalizes the title. removing all non-word characters as well as common tokens
/// such as 'the' and 'and'
/// </summary>
/// <param name="title">title</param>
/// <param name = "title">title</param>
/// <returns></returns>
internal static string NormalizeTitle(string title)
{
@ -255,7 +260,5 @@ namespace NzbDrone.Core
return info.FullName.Trim('/', '\\', ' ');
}
}
}

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Core.Providers
{
@ -13,6 +10,7 @@ namespace NzbDrone.Core.Providers
{
throw new NotImplementedException();
}
public virtual bool StartSearch(int seriesId)
{
throw new NotImplementedException();

@ -238,10 +238,10 @@ namespace NzbDrone.Core.Providers.Core
if (dbValue == null)
{
_sonicRepo.Add(new Config
{
Key = key,
Value = value
});
{
Key = key,
Value = value
});
}
else
{

@ -5,8 +5,6 @@ namespace NzbDrone.Core.Providers.Core
{
public class DiskProvider
{
#region IDiskProvider Members
public virtual bool FolderExists(string path)
{
return Directory.Exists(path);
@ -48,7 +46,5 @@ namespace NzbDrone.Core.Providers.Core
{
File.Move(sourcePath, destinationPath);
}
#endregion
}
}

@ -47,7 +47,6 @@ namespace NzbDrone.Core.Providers.Core
{
var webClient = new WebClient();
webClient.DownloadFile(request, filename);
}
catch (Exception ex)
{
@ -55,8 +54,6 @@ namespace NzbDrone.Core.Providers.Core
Logger.TraceException(ex.Message, ex);
throw;
}
}
public virtual void DownloadFile(string request, string filename, string username, string password)

@ -1,7 +1,6 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Repository;
@ -13,17 +12,17 @@ namespace NzbDrone.Core.Providers
{
//TODO: Remove parsing of the series name, it should be done in series provider
private readonly IRepository _sonicRepo;
private readonly SeriesProvider _series;
private readonly SeasonProvider _seasons;
private readonly TvDbProvider _tvDb;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly HistoryProvider _history;
private readonly QualityProvider _quality;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly SeasonProvider _seasons;
private readonly SeriesProvider _series;
private readonly IRepository _sonicRepo;
private readonly TvDbProvider _tvDb;
public EpisodeProvider(IRepository sonicRepo, SeriesProvider seriesProvider,
SeasonProvider seasonProvider, TvDbProvider tvDbProvider,
HistoryProvider history, QualityProvider quality)
SeasonProvider seasonProvider, TvDbProvider tvDbProvider,
HistoryProvider history, QualityProvider quality)
{
_sonicRepo = sonicRepo;
_series = seriesProvider;
@ -35,7 +34,6 @@ namespace NzbDrone.Core.Providers
public EpisodeProvider()
{
}
public virtual Episode GetEpisode(long id)
@ -45,7 +43,9 @@ namespace NzbDrone.Core.Providers
public virtual Episode GetEpisode(int seriesId, int seasonNumber, int episodeNumber)
{
return _sonicRepo.Single<Episode>(c => c.SeriesId == seriesId && c.SeasonNumber == seasonNumber && c.EpisodeNumber == episodeNumber);
return
_sonicRepo.Single<Episode>(
c => c.SeriesId == seriesId && c.SeasonNumber == seasonNumber && c.EpisodeNumber == episodeNumber);
}
public virtual IList<Episode> GetEpisodeBySeries(long seriesId)
@ -68,9 +68,9 @@ namespace NzbDrone.Core.Providers
}
/// <summary>
/// Comprehensive check on whether or not this episode is needed.
/// Comprehensive check on whether or not this episode is needed.
/// </summary>
/// <param name="parsedReport">Episode that needs to be checked</param>
/// <param name = "parsedReport">Episode that needs to be checked</param>
/// <returns></returns>
public virtual bool IsNeeded(EpisodeParseResult parsedReport)
{
@ -112,11 +112,10 @@ namespace NzbDrone.Core.Providers
continue;
}
return true;//If we get to this point and the file has not yet been rejected then accept it
return true; //If we get to this point and the file has not yet been rejected then accept it
}
return false;
}
public virtual void RefreshEpisodeInfo(int seriesId)
@ -130,7 +129,7 @@ namespace NzbDrone.Core.Providers
var newList = new List<Episode>();
Logger.Debug("Updating season info for series:{0}", targetSeries.SeriesName);
targetSeries.Episodes.Select(e => new { e.SeasonId, e.SeasonNumber })
targetSeries.Episodes.Select(e => new {e.SeasonId, e.SeasonNumber})
.Distinct().ToList()
.ForEach(s => _seasons.EnsureSeason(seriesId, s.SeasonId, s.SeasonNumber));
@ -145,19 +144,20 @@ namespace NzbDrone.Core.Providers
if (episode.FirstAired < new DateTime(1753, 1, 1))
episode.FirstAired = new DateTime(1753, 1, 1);
Logger.Trace("Updating info for series:{0} - episode:{1}", targetSeries.SeriesName, episode.EpisodeNumber);
var newEpisode = new Episode()
{
AirDate = episode.FirstAired,
EpisodeId = episode.Id,
EpisodeNumber = episode.EpisodeNumber,
Language = episode.Language.Abbriviation,
Overview = episode.Overview,
SeasonId = episode.SeasonId,
SeasonNumber = episode.SeasonNumber,
SeriesId = seriesId,
Title = episode.EpisodeName
};
Logger.Trace("Updating info for series:{0} - episode:{1}", targetSeries.SeriesName,
episode.EpisodeNumber);
var newEpisode = new Episode
{
AirDate = episode.FirstAired,
EpisodeId = episode.Id,
EpisodeNumber = episode.EpisodeNumber,
Language = episode.Language.Abbriviation,
Overview = episode.Overview,
SeasonId = episode.SeasonId,
SeasonNumber = episode.SeasonNumber,
SeriesId = seriesId,
Title = episode.EpisodeName
};
if (_sonicRepo.Exists<Episode>(e => e.EpisodeId == newEpisode.EpisodeId))
{
@ -172,7 +172,8 @@ namespace NzbDrone.Core.Providers
}
catch (Exception e)
{
Logger.FatalException(String.Format("An error has occurred while updating episode info for series {0}", seriesId), e);
Logger.FatalException(
String.Format("An error has occurred while updating episode info for series {0}", seriesId), e);
failCount++;
}
}
@ -180,12 +181,14 @@ namespace NzbDrone.Core.Providers
_sonicRepo.AddMany(newList);
_sonicRepo.UpdateMany(updateList);
Logger.Debug("Finished episode refresh for series:{0}. Successful:{1} - Failed:{2} ", targetSeries.SeriesName, successCount, failCount);
Logger.Debug("Finished episode refresh for series:{0}. Successful:{1} - Failed:{2} ",
targetSeries.SeriesName, successCount, failCount);
}
public virtual void RefreshEpisodeInfo(Season season)
{
Logger.Info("Starting episode info refresh for season {0} of series:{1}", season.SeasonNumber, season.SeriesId);
Logger.Info("Starting episode info refresh for season {0} of series:{1}", season.SeasonNumber,
season.SeriesId);
int successCount = 0;
int failCount = 0;
var targetSeries = _tvDb.GetSeries(season.SeriesId, true);
@ -204,19 +207,20 @@ namespace NzbDrone.Core.Providers
if (episode.FirstAired < new DateTime(1753, 1, 1))
episode.FirstAired = new DateTime(1753, 1, 1);
Logger.Trace("Updating info for series:{0} - episode:{1}", targetSeries.SeriesName, episode.EpisodeNumber);
var newEpisode = new Episode()
{
AirDate = episode.FirstAired,
EpisodeId = episode.Id,
EpisodeNumber = episode.EpisodeNumber,
Language = episode.Language.Abbriviation,
Overview = episode.Overview,
SeasonId = episode.SeasonId,
SeasonNumber = episode.SeasonNumber,
SeriesId = season.SeriesId,
Title = episode.EpisodeName
};
Logger.Trace("Updating info for series:{0} - episode:{1}", targetSeries.SeriesName,
episode.EpisodeNumber);
var newEpisode = new Episode
{
AirDate = episode.FirstAired,
EpisodeId = episode.Id,
EpisodeNumber = episode.EpisodeNumber,
Language = episode.Language.Abbriviation,
Overview = episode.Overview,
SeasonId = episode.SeasonId,
SeasonNumber = episode.SeasonNumber,
SeriesId = season.SeriesId,
Title = episode.EpisodeName
};
if (_sonicRepo.Exists<Episode>(e => e.EpisodeId == newEpisode.EpisodeId))
{
@ -231,7 +235,9 @@ namespace NzbDrone.Core.Providers
}
catch (Exception e)
{
Logger.FatalException(String.Format("An error has occurred while updating episode info for season {0} of series {1}", season.SeasonNumber, season.SeriesId), e);
Logger.FatalException(
String.Format("An error has occurred while updating episode info for season {0} of series {1}",
season.SeasonNumber, season.SeriesId), e);
failCount++;
}
}
@ -239,7 +245,8 @@ namespace NzbDrone.Core.Providers
_sonicRepo.AddMany(newList);
_sonicRepo.UpdateMany(updateList);
Logger.Debug("Finished episode refresh for series:{0}. Successful:{1} - Failed:{2} ", targetSeries.SeriesName, successCount, failCount);
Logger.Debug("Finished episode refresh for series:{0}. Successful:{1} - Failed:{2} ",
targetSeries.SeriesName, successCount, failCount);
}
public virtual void DeleteEpisode(int episodeId)
@ -251,6 +258,5 @@ namespace NzbDrone.Core.Providers
{
_sonicRepo.Update(episode);
}
}
}

@ -1,29 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NzbDrone.Core.Helpers;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
namespace NzbDrone.Core.Providers
{
public class ExternalNotificationProvider
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _configProvider;
private readonly XbmcProvider _xbmcProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public ExternalNotificationProvider(ConfigProvider configProvider, XbmcProvider xbmcProvider)
{
_configProvider = configProvider;
_xbmcProvider = xbmcProvider;
}
#region ExternalNotificationProvider Members
public virtual void OnGrab(string message)
{
var header = "NzbDrone [TV] - Grabbed";
@ -100,6 +94,5 @@ namespace NzbDrone.Core.Providers
throw new NotImplementedException();
}
#endregion
}
}
}

@ -4,24 +4,19 @@ using NzbDrone.Core.Model.Notification;
namespace NzbDrone.Core.Providers.Fakes
{
class FakeNotificationProvider
internal class FakeNotificationProvider
{
private readonly Dictionary<Guid, BasicNotification> _basicNotifications = new Dictionary<Guid, BasicNotification>();
private readonly Dictionary<Guid, ProgressNotification> _progressNotification = new Dictionary<Guid, ProgressNotification>();
private readonly Dictionary<Guid, BasicNotification> _basicNotifications =
new Dictionary<Guid, BasicNotification>();
private readonly Object _lock = new object();
private readonly Dictionary<Guid, ProgressNotification> _progressNotification =
new Dictionary<Guid, ProgressNotification>();
ProgressNotification fakeNotification = new ProgressNotification("Updating Series");
ProgressNotification fakeNotification2 = new ProgressNotification("Updating Series2");
public void Register(ProgressNotification notification)
{
_progressNotification.Add(notification.Id, notification);
}
public void Register(BasicNotification notification)
{
_basicNotifications.Add(notification.Id, notification);
}
private readonly ProgressNotification fakeNotification = new ProgressNotification("Updating Series");
private readonly ProgressNotification fakeNotification2 = new ProgressNotification("Updating Series2");
public List<BasicNotification> BasicNotifications
{
@ -30,17 +25,26 @@ namespace NzbDrone.Core.Providers.Fakes
public List<ProgressNotification> GetProgressNotifications
{
get
{
fakeNotification.Status = ProgressNotificationStatus.InProgress;
fakeNotification.Status = ProgressNotificationStatus.InProgress;
fakeNotification2.CurrentStatus = DateTime.UtcNow.ToString();
fakeNotification.CurrentStatus = DateTime.Now.ToString();
return new List<ProgressNotification> { fakeNotification };
return new List<ProgressNotification> {fakeNotification};
}
}
public void Register(ProgressNotification notification)
{
_progressNotification.Add(notification.Id, notification);
}
public void Register(BasicNotification notification)
{
_basicNotifications.Add(notification.Id, notification);
}
public void Dismiss(Guid notificationId)
{
lock (_lock)

@ -1,5 +1,4 @@
using System.ServiceModel.Syndication;
using System.Xml;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers.Core;
@ -8,15 +7,16 @@ namespace NzbDrone.Core.Providers.Feed
{
public abstract class FeedProviderBase
{
protected readonly SeriesProvider _seriesProvider;
protected readonly SeasonProvider _seasonProvider;
protected readonly EpisodeProvider _episodeProvider;
protected static readonly Logger Logger = LogManager.GetCurrentClassLogger();
protected readonly ConfigProvider _configProvider;
protected readonly EpisodeProvider _episodeProvider;
private readonly HttpProvider _httpProvider;
protected static readonly Logger Logger = LogManager.GetCurrentClassLogger();
protected readonly SeasonProvider _seasonProvider;
protected readonly SeriesProvider _seriesProvider;
public FeedProviderBase(SeriesProvider seriesProvider, SeasonProvider seasonProvider,
EpisodeProvider episodeProvider, ConfigProvider configProvider, HttpProvider httpProvider)
EpisodeProvider episodeProvider, ConfigProvider configProvider,
HttpProvider httpProvider)
{
_seriesProvider = seriesProvider;
_seasonProvider = seasonProvider;
@ -27,28 +27,28 @@ namespace NzbDrone.Core.Providers.Feed
/// <summary>
/// Gets the source URL for the feed
/// Gets the source URL for the feed
/// </summary>
protected abstract string[] URL { get; }
/// <summary>
/// Gets the name for this feed
/// Gets the name for this feed
/// </summary>
protected abstract string Name { get; }
/// <summary>
/// Generates direct link to download an NZB
/// Generates direct link to download an NZB
/// </summary>
/// <param name="item">RSS Feed item to generate the link for</param>
/// <param name = "item">RSS Feed item to generate the link for</param>
/// <returns>Download link URL</returns>
protected abstract string NzbDownloadUrl(SyndicationItem item);
/// <summary>
/// Parses the RSS feed item and.
/// Parses the RSS feed item and.
/// </summary>
/// <param name="item">RSS feed item to parse</param>
/// <param name = "item">RSS feed item to parse</param>
/// <returns>Detailed episode info</returns>
protected EpisodeParseResult ParseFeed(SyndicationItem item)
{
@ -66,13 +66,11 @@ namespace NzbDrone.Core.Providers.Feed
Logger.Debug("Unable to map {0} to any of series in database", episodeParseResult.SeriesTitle);
return null;
}
/// <summary>
/// Fetches RSS feed and process each news item.
/// Fetches RSS feed and process each news item.
/// </summary>
public void Fetch()
{
@ -122,5 +120,4 @@ namespace NzbDrone.Core.Providers.Feed
}
}
}
}
}

@ -1,15 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.ServiceModel.Syndication;
using NzbDrone.Core.Providers.Core;
namespace NzbDrone.Core.Providers.Feed
{
class NzbsOrgFeedProvider : FeedProviderBase
internal class NzbsOrgFeedProvider : FeedProviderBase
{
public NzbsOrgFeedProvider(SeriesProvider seriesProvider, SeasonProvider seasonProvider, EpisodeProvider episodeProvider, ConfigProvider configProvider, HttpProvider httpProvider)
public NzbsOrgFeedProvider(SeriesProvider seriesProvider, SeasonProvider seasonProvider,
EpisodeProvider episodeProvider, ConfigProvider configProvider,
HttpProvider httpProvider)
: base(seriesProvider, seasonProvider, episodeProvider, configProvider, httpProvider)
{
}
@ -18,7 +16,11 @@ namespace NzbDrone.Core.Providers.Feed
{
get
{
return new[] { string.Format("http://nzbs.org/rss.php?type=1&i={0}&h={1}", _configProvider.NzbsOrgUId, _configProvider.NzbsOrgHash) };
return new[]
{
string.Format("http://nzbs.org/rss.php?type=1&i={0}&h={1}", _configProvider.NzbsOrgUId,
_configProvider.NzbsOrgHash)
};
}
}
@ -32,4 +34,4 @@ namespace NzbDrone.Core.Providers.Feed
return item.Id.Replace("action=view", "action=getnzb");
}
}
}
}

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
@ -11,9 +10,8 @@ namespace NzbDrone.Core.Providers
{
public class HistoryProvider
{
private readonly IRepository _sonicRepo;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IRepository _sonicRepo;
public HistoryProvider(IRepository sonicRepo)
{
@ -24,8 +22,6 @@ namespace NzbDrone.Core.Providers
{
}
#region HistoryProvider Members
public virtual List<History> AllItems()
{
return _sonicRepo.All<History>().ToList();
@ -54,13 +50,11 @@ namespace NzbDrone.Core.Providers
public virtual bool Exists(int episodeId, QualityTypes quality, bool proper)
{
//Looks for the existance of this episode in History
if (_sonicRepo.Exists<History>(h => h.EpisodeId == episodeId && (QualityTypes)h.Quality == quality && h.IsProper == proper))
if (_sonicRepo.Exists<History>(h => h.EpisodeId == episodeId && h.Quality == quality && h.IsProper == proper))
return true;
Logger.Debug("Episode not in History: {0}", episodeId);
return false;
}
#endregion
}
}
}

@ -1,21 +1,17 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers.Core;
using SubSonic.Repository;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
namespace NzbDrone.Core.Providers
{
public class IndexerProvider
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IRepository _sonicRepo;
private readonly ConfigProvider _configProvider;
private readonly IRepository _sonicRepo;
public IndexerProvider(IRepository sonicRepo, ConfigProvider configProvider)
{
@ -23,8 +19,6 @@ namespace NzbDrone.Core.Providers
_configProvider = configProvider;
}
#region IndexerProvider Members
public virtual List<Indexer> AllIndexers()
{
return _sonicRepo.All<Indexer>().OrderBy(i => i.Order).ToList();
@ -44,7 +38,5 @@ namespace NzbDrone.Core.Providers
{
return _sonicRepo.Single<Indexer>(indexerId);
}
#endregion
}
}
}

@ -2,10 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
@ -14,31 +11,28 @@ namespace NzbDrone.Core.Providers
{
public class MediaFileProvider
{
private readonly IRepository _repository;
private readonly ConfigProvider _configProvider;
private readonly DiskProvider _diskProvider;
private readonly EpisodeProvider _episodeProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly string[] MediaExtentions = new[] { "*.mkv", "*.avi", "*.wmv" };
private readonly DiskProvider _diskProvider;
private readonly EpisodeProvider _episodeProvider;
private readonly IRepository _repository;
public MediaFileProvider(IRepository repository, ConfigProvider configProvider, DiskProvider diskProvider, EpisodeProvider episodeProvider)
public MediaFileProvider(IRepository repository, DiskProvider diskProvider,
EpisodeProvider episodeProvider)
{
_repository = repository;
_configProvider = configProvider;
_diskProvider = diskProvider;
_episodeProvider = episodeProvider;
}
public MediaFileProvider()
{
}
/// <summary>
/// Scans the specified series folder for media files
/// Scans the specified series folder for media files
/// </summary>
/// <param name="series">The series to be scanned</param>
/// <param name = "series">The series to be scanned</param>
public List<EpisodeFile> Scan(Series series)
{
var mediaFileList = GetMediaFileList(series.Path);
@ -54,9 +48,9 @@ namespace NzbDrone.Core.Providers
}
/// <summary>
/// Scans the specified series folder for media files
/// Scans the specified series folder for media files
/// </summary>
/// <param name="series">The series to be scanned</param>
/// <param name = "series">The series to be scanned</param>
public List<EpisodeFile> Scan(Series series, string path)
{
var mediaFileList = GetMediaFileList(path);
@ -84,7 +78,8 @@ namespace NzbDrone.Core.Providers
foreach (var episodeNumber in episodesInFile.Episodes)
{
var episode = _episodeProvider.GetEpisode(series.SeriesId, episodesInFile.SeasonNumber, episodeNumber);
var episode = _episodeProvider.GetEpisode(series.SeriesId, episodesInFile.SeasonNumber,
episodeNumber);
if (episode != null)
{
@ -92,7 +87,8 @@ namespace NzbDrone.Core.Providers
}
else
Logger.Warn("Unable to find Series:{0} Season:{1} Episode:{2} in the database. File:{3}", series.Title, episodesInFile.SeasonNumber, episodeNumber, filePath);
Logger.Warn("Unable to find Series:{0} Season:{1} Episode:{2} in the database. File:{3}",
series.Title, episodesInFile.SeasonNumber, episodeNumber, filePath);
}
//Return null if no Episodes exist in the DB for the parsed episodes from file
@ -125,7 +121,8 @@ namespace NzbDrone.Core.Providers
_episodeProvider.UpdateEpisode(ep);
episodeList += String.Format(", {0}", ep.EpisodeId).Trim(' ', ',');
}
Logger.Trace("File {0}:{1} attached to episode(s): '{2}'", episodeFile.EpisodeFileId, filePath, episodeList);
Logger.Trace("File {0}:{1} attached to episode(s): '{2}'", episodeFile.EpisodeFileId, filePath,
episodeList);
return episodeFile;
}
@ -135,9 +132,9 @@ namespace NzbDrone.Core.Providers
}
/// <summary>
/// Removes files that no longer exist from the database
/// Removes files that no longer exist from the database
/// </summary>
/// <param name="files">list of files to verify</param>
/// <param name = "files">list of files to verify</param>
public void CleanUp(List<EpisodeFile> files)
{
foreach (var episodeFile in files)
@ -192,4 +189,4 @@ namespace NzbDrone.Core.Providers
return mediaFileList;
}
}
}
}

@ -1,25 +1,19 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Model.Notification;
namespace NzbDrone.Core.Providers
{
public class NotificationProvider
{
private readonly Dictionary<Guid, BasicNotification> _basicNotifications = new Dictionary<Guid, BasicNotification>();
private Dictionary<Guid, ProgressNotification> _progressNotification = new Dictionary<Guid, ProgressNotification>();
private readonly Object _lock = new object();
private readonly Dictionary<Guid, BasicNotification> _basicNotifications =
new Dictionary<Guid, BasicNotification>();
public virtual void Register(ProgressNotification notification)
{
_progressNotification.Add(notification.Id, notification);
}
private readonly Object _lock = new object();
public virtual void Register(BasicNotification notification)
{
_basicNotifications.Add(notification.Id, notification);
}
private readonly Dictionary<Guid, ProgressNotification> _progressNotification =
new Dictionary<Guid, ProgressNotification>();
public virtual List<BasicNotification> BasicNotifications
{
@ -30,10 +24,22 @@ namespace NzbDrone.Core.Providers
{
get
{
return new List<ProgressNotification>(_progressNotification.Values.Where(p => p.Status == ProgressNotificationStatus.InProgress));
return
new List<ProgressNotification>(
_progressNotification.Values.Where(p => p.Status == ProgressNotificationStatus.InProgress));
}
}
public virtual void Register(ProgressNotification notification)
{
_progressNotification.Add(notification.Id, notification);
}
public virtual void Register(BasicNotification notification)
{
_basicNotifications.Add(notification.Id, notification);
}
public virtual void Dismiss(Guid notificationId)
{
lock (_lock)

@ -1,30 +1,19 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using NzbDrone.Core.Helpers;
using NzbDrone.Core.Providers.Core;
namespace NzbDrone.Core.Providers
namespace NzbDrone.Core.Providers
{
public class PostProcessingProvider
{
private readonly SeriesProvider _seriesProvider;
private readonly MediaFileProvider _mediaFileProvider;
private readonly RenameProvider _renameProvider;
private readonly SeriesProvider _seriesProvider;
public PostProcessingProvider(SeriesProvider seriesProvider,
MediaFileProvider mediaFileProvider, RenameProvider renameProvider)
MediaFileProvider mediaFileProvider, RenameProvider renameProvider)
{
_seriesProvider = seriesProvider;
_mediaFileProvider = mediaFileProvider;
_mediaFileProvider = mediaFileProvider;
_renameProvider = renameProvider;
}
#region PostProcessingProvider Members
public virtual void ProcessEpisode(string dir, string nzbName)
{
var parsedSeries = Parser.ParseSeriesName(nzbName);
@ -42,7 +31,5 @@ namespace NzbDrone.Core.Providers
_renameProvider.RenameEpisodeFile(file.EpisodeFileId, true);
}
}
#endregion
}
}
}

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using NLog;
using NzbDrone.Core.Repository.Quality;
using SubSonic.Repository;
@ -11,12 +9,11 @@ namespace NzbDrone.Core.Providers
{
public class QualityProvider
{
private IRepository _sonicRepo;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IRepository _sonicRepo;
public QualityProvider()
{
}
public QualityProvider(IRepository sonicRepo)
@ -24,8 +21,6 @@ namespace NzbDrone.Core.Providers
_sonicRepo = sonicRepo;
}
#region IQualityProvider Members
public virtual void Add(QualityProfile profile)
{
_sonicRepo.Add(profile);
@ -58,7 +53,5 @@ namespace NzbDrone.Core.Providers
{
return _sonicRepo.Single<QualityProfile>(q => q.QualityProfileId == profileId);
}
#endregion
}
}
}

@ -2,35 +2,32 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using NLog;
using NzbDrone.Core.Helpers;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
namespace NzbDrone.Core.Providers
{
public class RenameProvider
{
private readonly SeriesProvider _seriesProvider;
private readonly SeasonProvider _seasonProvider;
private readonly EpisodeProvider _episodeProvider;
private readonly MediaFileProvider _mediaFileProvider;
private readonly DiskProvider _diskProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _configProvider;
private readonly DiskProvider _diskProvider;
private readonly EpisodeProvider _episodeProvider;
private readonly List<EpisodeRenameModel> _epsToRename = new List<EpisodeRenameModel>();
private readonly ExternalNotificationProvider _externalNotificationProvider;
private readonly MediaFileProvider _mediaFileProvider;
private readonly SeasonProvider _seasonProvider;
private readonly SeriesProvider _seriesProvider;
private Thread _renameThread;
private List<EpisodeRenameModel> _epsToRename = new List<EpisodeRenameModel>();
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public RenameProvider(SeriesProvider seriesProvider, SeasonProvider seasonProvider,
EpisodeProvider episodeProvider, MediaFileProvider mediaFileProvider,
DiskProvider diskProvider, ConfigProvider configProvider,
ExternalNotificationProvider extenalNotificationProvider)
EpisodeProvider episodeProvider, MediaFileProvider mediaFileProvider,
DiskProvider diskProvider, ConfigProvider configProvider,
ExternalNotificationProvider extenalNotificationProvider)
{
_seriesProvider = seriesProvider;
_seasonProvider = seasonProvider;
@ -41,7 +38,6 @@ namespace NzbDrone.Core.Providers
_externalNotificationProvider = extenalNotificationProvider;
}
#region RenameProvider Members
public virtual void RenameAll()
{
//Get a list of all episode files/episodes and rename them
@ -49,12 +45,14 @@ namespace NzbDrone.Core.Providers
foreach (var episodeFile in _mediaFileProvider.GetEpisodeFiles())
{
var series = _seriesProvider.GetSeries(episodeFile.SeriesId);
var erm = new EpisodeRenameModel();
erm.SeriesName = series.Title;
erm.Folder = series.Path;
var erm = new EpisodeRenameModel {SeriesName = series.Title, Folder = series.Path};
if (series.SeasonFolder)
erm.Folder += Path.DirectorySeparatorChar + EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber, _configProvider.GetValue("Sorting_SeasonFolderFormat", "Season %s", true));
erm.Folder += Path.DirectorySeparatorChar +
EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber,
_configProvider.GetValue(
"Sorting_SeasonFolderFormat", "Season %s",
true));
erm.EpisodeFile = episodeFile;
_epsToRename.Add(erm);
@ -70,13 +68,14 @@ namespace NzbDrone.Core.Providers
foreach (var episodeFile in _mediaFileProvider.GetEpisodeFiles().Where(s => s.SeriesId == seriesId))
{
var erm = new EpisodeRenameModel();
erm.SeriesName = series.Title;
erm.Folder = series.Path;
var erm = new EpisodeRenameModel {SeriesName = series.Title, Folder = series.Path};
if (series.SeasonFolder)
erm.Folder += Path.DirectorySeparatorChar + EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber, _configProvider.GetValue("Sorting_SeasonFolderFormat", "Season %s", true));
erm.Folder += Path.DirectorySeparatorChar +
EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber,
_configProvider.GetValue(
"Sorting_SeasonFolderFormat", "Season %s",
true));
erm.EpisodeFile = episodeFile;
_epsToRename.Add(erm);
@ -90,15 +89,17 @@ namespace NzbDrone.Core.Providers
var season = _seasonProvider.GetSeason(seasonId);
var series = _seriesProvider.GetSeries(season.SeriesId);
foreach (var episodeFile in _mediaFileProvider.GetEpisodeFiles().Where(s => s.Episodes[0].SeasonId == seasonId))
foreach (
var episodeFile in _mediaFileProvider.GetEpisodeFiles().Where(s => s.Episodes[0].SeasonId == seasonId))
{
var erm = new EpisodeRenameModel();
erm.SeriesName = series.Title;
erm.Folder = series.Path;
var erm = new EpisodeRenameModel {SeriesName = series.Title, Folder = series.Path};
if (series.SeasonFolder)
erm.Folder += Path.DirectorySeparatorChar + EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber, _configProvider.GetValue("Sorting_SeasonFolderFormat", "Season %s", true));
erm.Folder += Path.DirectorySeparatorChar +
EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber,
_configProvider.GetValue(
"Sorting_SeasonFolderFormat", "Season %s",
true));
erm.EpisodeFile = episodeFile;
_epsToRename.Add(erm);
@ -112,15 +113,16 @@ namespace NzbDrone.Core.Providers
var episode = _episodeProvider.GetEpisode(episodeId);
var series = _seriesProvider.GetSeries(episode.SeriesId);
var episodeFile = _mediaFileProvider.GetEpisodeFiles().Where(s => s.Episodes.Contains(episode)).FirstOrDefault();
var episodeFile =
_mediaFileProvider.GetEpisodeFiles().Where(s => s.Episodes.Contains(episode)).FirstOrDefault();
var erm = new EpisodeRenameModel();
erm.SeriesName = series.Title;
erm.Folder = series.Path;
var erm = new EpisodeRenameModel {SeriesName = series.Title, Folder = series.Path};
if (series.SeasonFolder)
erm.Folder += Path.DirectorySeparatorChar + EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber, _configProvider.GetValue("Sorting_SeasonFolderFormat", "Season %s", true));
erm.Folder += Path.DirectorySeparatorChar +
EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber,
_configProvider.GetValue(
"Sorting_SeasonFolderFormat", "Season %s", true));
erm.EpisodeFile = episodeFile;
_epsToRename.Add(erm);
@ -133,21 +135,19 @@ namespace NzbDrone.Core.Providers
var episodeFile = _mediaFileProvider.GetEpisodeFile(episodeFileId);
var series = _seriesProvider.GetSeries(episodeFile.Series.SeriesId);
var erm = new EpisodeRenameModel();
erm.SeriesName = series.Title;
erm.Folder = series.Path;
var erm = new EpisodeRenameModel {SeriesName = series.Title, Folder = series.Path};
if (series.SeasonFolder)
erm.Folder += Path.DirectorySeparatorChar + EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber, _configProvider.GetValue("Sorting_SeasonFolderFormat", "Season %s", true));
erm.Folder += Path.DirectorySeparatorChar +
EpisodeRenameHelper.GetSeasonFolder(episodeFile.Episodes[0].SeasonNumber,
_configProvider.GetValue(
"Sorting_SeasonFolderFormat", "Season %s", true));
erm.EpisodeFile = episodeFile;
_epsToRename.Add(erm);
StartRename();
}
#endregion
private void StartRename()
{
Logger.Debug("Episode Rename Starting");
@ -155,10 +155,10 @@ namespace NzbDrone.Core.Providers
{
Logger.Debug("Initializing background rename of episodes");
_renameThread = new Thread(RenameProcessor)
{
Name = "RenameEpisodes",
Priority = ThreadPriority.Lowest
};
{
Name = "RenameEpisodes",
Priority = ThreadPriority.Lowest
};
_renameThread.Start();
}
@ -203,7 +203,6 @@ namespace NzbDrone.Core.Providers
else
_externalNotificationProvider.OnRename(erm);
}
catch (Exception ex)
{
@ -212,4 +211,4 @@ namespace NzbDrone.Core.Providers
}
}
}
}
}

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
@ -27,17 +25,17 @@ namespace NzbDrone.Core.Providers
{
_sonioRepo.Add(rootDir);
}
public virtual void Remove(int rootDirId)
{
_sonioRepo.Delete<RootDir>(rootDirId);
}
public virtual void Update(RootDir rootDir)
{
_sonioRepo.Update(rootDir);
}
public virtual RootDir GetRootDir(int rootDirId)
{
return _sonioRepo.Single<RootDir>(rootDirId);
@ -45,4 +43,4 @@ namespace NzbDrone.Core.Providers
#endregion
}
}
}

@ -1,15 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Core.Providers
namespace NzbDrone.Core.Providers
{
public class RssSyncProvider
{
public virtual void Begin()
{
}
}
}
}

@ -9,19 +9,16 @@ namespace NzbDrone.Core.Providers
{
public class SabProvider
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _config;
private readonly HttpProvider _http;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public SabProvider(ConfigProvider config, HttpProvider http)
{
_config = config;
_http = http;
}
#region IDownloadProvider Members
public virtual bool AddByUrl(string url, string title)
{
const string mode = "addurl";
@ -31,7 +28,8 @@ namespace NzbDrone.Core.Providers
string name = url.Replace("&", "%26");
string nzbName = HttpUtility.UrlEncode(title);
string action = string.Format("mode={0}&name={1}&priority={2}&cat={3}&nzbname={4}", mode, name, priority, cat, nzbName);
string action = string.Format("mode={0}&name={1}&priority={2}&cat={3}&nzbname={4}", mode, name, priority,
cat, nzbName);
string request = GetSabRequest(action);
Logger.Debug("Adding report [{0}] to the queue.", nzbName);
@ -61,7 +59,10 @@ namespace NzbDrone.Core.Providers
return false;
//Get the Count of Items in Queue where 'filename' is Equal to goodName, if not zero, return true (isInQueue)))
if ((xDoc.Descendants("slot").Where(s => s.Element("filename").Value.Equals(title, StringComparison.InvariantCultureIgnoreCase))).Count() != 0)
if (
(xDoc.Descendants("slot").Where(
s => s.Element("filename").Value.Equals(title, StringComparison.InvariantCultureIgnoreCase))).Count() !=
0)
{
Logger.Debug("Episode in queue - '{0}'", title);
@ -81,7 +82,8 @@ namespace NzbDrone.Core.Providers
string priority = _config.GetValue("SabTvPriority", String.Empty, false);
string nzbName = HttpUtility.UrlEncode(title);
string action = string.Format("mode={0}&name={1}&priority={2}&cat={3}&nzbname={4}", mode, id, priority, cat, nzbName);
string action = string.Format("mode={0}&name={1}&priority={2}&cat={3}&nzbname={4}", mode, id, priority, cat,
nzbName);
string request = GetSabRequest(action);
Logger.Debug("Adding report [{0}] to the queue.", nzbName);
@ -95,16 +97,17 @@ namespace NzbDrone.Core.Providers
return false;
}
#endregion
private string GetSabRequest(string action)
{
string sabnzbdInfo = _config.GetValue("SabHost", String.Empty, false) + ":" + _config.GetValue("SabPort", String.Empty, false);
string sabnzbdInfo = _config.GetValue("SabHost", String.Empty, false) + ":" +
_config.GetValue("SabPort", String.Empty, false);
string username = _config.GetValue("SabUsername", String.Empty, false);
string password = _config.GetValue("SabPassword", String.Empty, false);
string apiKey = _config.GetValue("SabApiKey", String.Empty, false);
return string.Format(@"http://{0}/api?$Action&apikey={1}&ma_username={2}&ma_password={3}", sabnzbdInfo, apiKey, username, password).Replace("$Action", action);
return
string.Format(@"http://{0}/api?$Action&apikey={1}&ma_username={2}&ma_password={3}", sabnzbdInfo, apiKey,
username, password).Replace("$Action", action);
}
}
}

@ -1,29 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
using System.Linq;
namespace NzbDrone.Core.Providers
{
public class SeasonProvider
{
private readonly IRepository _sonicRepo;
private readonly SeriesProvider _seriesProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IRepository _sonicRepo;
public SeasonProvider(IRepository dataRepository, SeriesProvider seriesProvider)
public SeasonProvider(IRepository dataRepository)
{
_sonicRepo = dataRepository;
_seriesProvider = seriesProvider;
}
public SeasonProvider()
{
}
public virtual Season GetSeason(int seasonId)
@ -51,16 +46,17 @@ namespace NzbDrone.Core.Providers
if (_sonicRepo.Exists<Season>(s => s.SeasonId == seasonId))
return;
//TODO: Calculate Season Folder
Logger.Trace("Adding Season To DB. [SeriesID:{0} SeasonID:{1} SeasonNumber:{2}]", seriesId, seasonId, seasonNumber, "????");
var newSeason = new Season()
{
Monitored = true,
SeasonId = seasonId,
SeasonNumber = seasonNumber,
SeriesId = seriesId
};
_sonicRepo.Add<Season>(newSeason);
Logger.Trace("Adding Season To DB. [SeriesID:{0} SeasonID:{1} SeasonNumber:{2}]", seriesId, seasonId,
seasonNumber, "????");
var newSeason = new Season
{
Monitored = true,
SeasonId = seasonId,
SeasonNumber = seasonNumber,
SeriesId = seriesId
};
_sonicRepo.Add(newSeason);
}
public virtual int SaveSeason(Season season)

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Ninject;
using NLog;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
@ -19,14 +16,14 @@ namespace NzbDrone.Core.Providers
//Trims all white spaces and separators from the end of the title.
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _config;
private readonly QualityProvider _quality;
private readonly IRepository _sonioRepo;
private readonly TvDbProvider _tvDb;
private readonly QualityProvider _quality;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public SeriesProvider(ConfigProvider configProvider,
IRepository dataRepository, TvDbProvider tvDbProvider, QualityProvider quality)
IRepository dataRepository, TvDbProvider tvDbProvider, QualityProvider quality)
{
_config = configProvider;
_sonioRepo = dataRepository;
@ -38,8 +35,6 @@ namespace NzbDrone.Core.Providers
{
}
#region SeriesProvider Members
public virtual IQueryable<Series> GetAllSeries()
{
return _sonioRepo.All<Series>();
@ -51,9 +46,9 @@ namespace NzbDrone.Core.Providers
}
/// <summary>
/// Determines if a series is being actively watched.
/// Determines if a series is being actively watched.
/// </summary>
/// <param name="id">The TVDB ID of the series</param>
/// <param name = "id">The TVDB ID of the series</param>
/// <returns>Whether or not the show is monitored</returns>
public virtual bool IsMonitored(long id)
{
@ -149,7 +144,6 @@ namespace NzbDrone.Core.Providers
_sonioRepo.Delete<Series>(seriesId);
Logger.Info("Successfully deleted Series [{0}]", seriesId);
}
catch (Exception e)
{
@ -165,8 +159,5 @@ namespace NzbDrone.Core.Providers
return false;
}
#endregion
}
}

@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using NLog;
using NzbDrone.Core.Model;
using NzbDrone.Core.Model.Notification;
using NzbDrone.Core.Providers.Core;
@ -13,20 +11,19 @@ namespace NzbDrone.Core.Providers
{
public class SyncProvider
{
private readonly SeriesProvider _seriesProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly DiskProvider _diskProvider;
private readonly EpisodeProvider _episodeProvider;
private readonly MediaFileProvider _mediaFileProvider;
private readonly NotificationProvider _notificationProvider;
private readonly DiskProvider _diskProvider;
private readonly SeriesProvider _seriesProvider;
private ProgressNotification _seriesSyncNotification;
private Thread _seriesSyncThread;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public SyncProvider(SeriesProvider seriesProvider, EpisodeProvider episodeProvider,
MediaFileProvider mediaFileProvider, NotificationProvider notificationProvider,
DiskProvider diskProvider)
MediaFileProvider mediaFileProvider, NotificationProvider notificationProvider,
DiskProvider diskProvider)
{
_seriesProvider = seriesProvider;
_episodeProvider = episodeProvider;
@ -35,8 +32,6 @@ namespace NzbDrone.Core.Providers
_diskProvider = diskProvider;
}
#region ISyncProvider Members
public List<String> GetUnmappedFolders(string path)
{
Logger.Debug("Generating list of unmapped folders");
@ -64,8 +59,6 @@ namespace NzbDrone.Core.Providers
return results;
}
#endregion
public bool BeginUpdateNewSeries()
{
Logger.Debug("User has requested a scan of new series");
@ -73,10 +66,10 @@ namespace NzbDrone.Core.Providers
{
Logger.Debug("Initializing background scan thread");
_seriesSyncThread = new Thread(SyncNewSeries)
{
Name = "SyncNewSeries",
Priority = ThreadPriority.Lowest
};
{
Name = "SyncNewSeries",
Priority = ThreadPriority.Lowest
};
_seriesSyncThread.Start();
}
@ -120,8 +113,6 @@ namespace NzbDrone.Core.Providers
private void ScanSeries()
{
var syncList = _seriesProvider.GetAllSeries().Where(s => s.LastInfoSync == null).ToList();
if (syncList.Count == 0) return;
@ -131,13 +122,16 @@ namespace NzbDrone.Core.Providers
{
try
{
_seriesSyncNotification.CurrentStatus = String.Format("Searching For: {0}", new DirectoryInfo(currentSeries.Path).Name);
_seriesSyncNotification.CurrentStatus = String.Format("Searching For: {0}",
new DirectoryInfo(currentSeries.Path).Name);
var updatedSeries = _seriesProvider.UpdateSeriesInfo(currentSeries.SeriesId);
_seriesSyncNotification.CurrentStatus = String.Format("Downloading episode info For: {0}", updatedSeries.Title);
_seriesSyncNotification.CurrentStatus = String.Format("Downloading episode info For: {0}",
updatedSeries.Title);
_episodeProvider.RefreshEpisodeInfo(updatedSeries.SeriesId);
_seriesSyncNotification.CurrentStatus = String.Format("Scanning series folder {0}", updatedSeries.Path);
_seriesSyncNotification.CurrentStatus = String.Format("Scanning series folder {0}",
updatedSeries.Path);
_mediaFileProvider.Scan(_seriesProvider.GetSeries(updatedSeries.SeriesId));
//Todo: Launch Backlog search for this series _backlogProvider.StartSearch(mappedSeries.Id);
@ -154,4 +148,4 @@ namespace NzbDrone.Core.Providers
ScanSeries();
}
}
}
}

@ -1,27 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using NLog;
using NzbDrone.Core.Model.Notification;
namespace NzbDrone.Core.Providers
{
public class TimerProvider
{
private readonly RssSyncProvider _rssSyncProvider;
private readonly SeriesProvider _seriesProvider;
private readonly SeasonProvider _seasonProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly EpisodeProvider _episodeProvider;
private readonly MediaFileProvider _mediaFileProvider;
private Timer _rssSyncTimer;
private Timer _minuteTimer;
private readonly Timer _minuteTimer;
private readonly RssSyncProvider _rssSyncProvider;
private readonly Timer _rssSyncTimer;
private readonly SeasonProvider _seasonProvider;
private readonly SeriesProvider _seriesProvider;
private DateTime _rssSyncNextInterval;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public TimerProvider(RssSyncProvider rssSyncProvider, SeriesProvider seriesProvider, SeasonProvider seasonProvider, EpisodeProvider episodeProvider, MediaFileProvider mediaFileProvider)
public TimerProvider(RssSyncProvider rssSyncProvider, SeriesProvider seriesProvider,
SeasonProvider seasonProvider, EpisodeProvider episodeProvider,
MediaFileProvider mediaFileProvider)
{
_rssSyncProvider = rssSyncProvider;
_seriesProvider = seriesProvider;
@ -33,8 +31,6 @@ namespace NzbDrone.Core.Providers
_minuteTimer = new Timer(60000);
}
#region TimerProvider Members
public virtual void ResetRssSyncTimer()
{
double interval = _rssSyncTimer.Interval;
@ -43,13 +39,14 @@ namespace NzbDrone.Core.Providers
public virtual void StartRssSyncTimer()
{
if (_rssSyncTimer.Interval < 900000) //If Timer is less than 15 minutes, throw an error! This should also be handled when saving the config, though a user could by-pass it by editing the DB directly... TNO (Trust No One)
if (_rssSyncTimer.Interval < 900000)
//If Timer is less than 15 minutes, throw an error! This should also be handled when saving the config, though a user could by-pass it by editing the DB directly... TNO (Trust No One)
{
Logger.Error("RSS Sync Frequency is invalid, please set the interval first");
throw new InvalidOperationException("RSS Sync Frequency Invalid");
}
_rssSyncTimer.Elapsed += new ElapsedEventHandler(RunRssSync);
_rssSyncTimer.Elapsed += RunRssSync;
_rssSyncTimer.Start();
_rssSyncNextInterval = DateTime.Now.AddMilliseconds(_rssSyncTimer.Interval);
}
@ -61,7 +58,7 @@ namespace NzbDrone.Core.Providers
public virtual void SetRssSyncTimer(int minutes)
{
long ms = minutes * 60 * 1000;
long ms = minutes*60*1000;
_rssSyncTimer.Interval = ms;
}
@ -77,7 +74,7 @@ namespace NzbDrone.Core.Providers
public virtual void StartMinuteTimer()
{
_minuteTimer.Elapsed += new ElapsedEventHandler(MinuteTimer_Elapsed);
_minuteTimer.Elapsed += MinuteTimer_Elapsed;
_minuteTimer.Start();
}
@ -86,8 +83,6 @@ namespace NzbDrone.Core.Providers
_minuteTimer.Stop();
}
#endregion
private void RunRssSync(object obj, ElapsedEventArgs args)
{
_rssSyncNextInterval = DateTime.Now.AddMilliseconds(_rssSyncTimer.Interval);
@ -132,4 +127,4 @@ namespace NzbDrone.Core.Providers
throw new NotImplementedException();
}
}
}
}

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using NLog;
using TvdbLib;
@ -11,10 +10,12 @@ namespace NzbDrone.Core.Providers
{
public class TvDbProvider
{
private const string TVDB_APIKEY = "5D2D188E86E07F4F";
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly Regex CleanUpRegex = new Regex(@"((\s|^)the(\s|$))|((\s|^)and(\s|$))|[^a-z]", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private const string TVDB_APIKEY = "5D2D188E86E07F4F";
private static readonly Regex CleanUpRegex = new Regex(@"((\s|^)the(\s|$))|((\s|^)and(\s|$))|[^a-z]",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly TvdbHandler _handler;
public TvDbProvider()
@ -22,8 +23,6 @@ namespace NzbDrone.Core.Providers
_handler = new TvdbHandler(new XmlCacheProvider(CentralDispatch.AppPath + @"\cache\tvdb"), TVDB_APIKEY);
}
#region TvDbProvider Members
public virtual IList<TvdbSearchResult> SearchSeries(string title)
{
Logger.Debug("Searching TVDB for '{0}'", title);
@ -76,17 +75,15 @@ namespace NzbDrone.Core.Providers
}
/// <summary>
/// Determines whether a title in a search result is equal to the title searched for.
/// Determines whether a title in a search result is equal to the title searched for.
/// </summary>
/// <param name="directoryName">Name of the directory.</param>
/// <param name="tvdbTitle">The TVDB title.</param>
/// <param name = "directoryName">Name of the directory.</param>
/// <param name = "tvdbTitle">The TVDB title.</param>
/// <returns>
/// <c>true</c> if the titles are found to be same; otherwise, <c>false</c>.
/// <c>true</c> if the titles are found to be same; otherwise, <c>false</c>.
/// </returns>
public static bool IsTitleMatch(string directoryName, string tvdbTitle)
{
var result = false;
if (String.IsNullOrEmpty(directoryName))
@ -98,14 +95,13 @@ namespace NzbDrone.Core.Providers
{
result = true;
}
else if (String.Equals(CleanUpRegex.Replace(directoryName, ""), CleanUpRegex.Replace(tvdbTitle, ""), StringComparison.InvariantCultureIgnoreCase))
else if (String.Equals(CleanUpRegex.Replace(directoryName, ""), CleanUpRegex.Replace(tvdbTitle, ""),
StringComparison.InvariantCultureIgnoreCase))
result = true;
Logger.Debug("Match between '{0}' and '{1}' was {2}", tvdbTitle, directoryName, result);
return result;
}
#endregion
}
}

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Core.Model;
using NzbDrone.Core.Repository;
using SubSonic.Repository;
@ -10,18 +9,18 @@ namespace NzbDrone.Core.Providers
{
public class UpcomingEpisodesProvider
{
private IRepository _sonicRepo;
private readonly IRepository _sonicRepo;
public UpcomingEpisodesProvider(IRepository sonicRepo)
{
_sonicRepo = sonicRepo;
}
#region UpcomingEpisodesProvider Members
public virtual UpcomingEpisodesModel Upcoming()
{
var allEps = _sonicRepo.All<Episode>().Where(e => e.AirDate >= DateTime.Today.AddDays(-1) && e.AirDate < DateTime.Today.AddDays(8));
var allEps =
_sonicRepo.All<Episode>().Where(
e => e.AirDate >= DateTime.Today.AddDays(-1) && e.AirDate < DateTime.Today.AddDays(8));
var yesterday = allEps.Where(e => e.AirDate == DateTime.Today.AddDays(-1)).ToList();
var today = allEps.Where(e => e.AirDate == DateTime.Today).ToList();
@ -42,9 +41,9 @@ namespace NzbDrone.Core.Providers
public virtual List<Episode> Week()
{
return _sonicRepo.All<Episode>().Where(e => e.AirDate > DateTime.Today && e.AirDate < DateTime.Today.AddDays(8)).ToList();
return
_sonicRepo.All<Episode>().Where(e => e.AirDate > DateTime.Today && e.AirDate < DateTime.Today.AddDays(8))
.ToList();
}
#endregion
}
}
}

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using NLog;
using NzbDrone.Core.Helpers;
@ -12,23 +10,20 @@ namespace NzbDrone.Core.Providers
{
public class XbmcProvider
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _configProvider;
private readonly HttpProvider _httpProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public XbmcProvider(ConfigProvider configProvider, HttpProvider httpProvider)
{
_configProvider = configProvider;
_httpProvider = httpProvider;
}
#region XbmcProvider Members
public virtual void Notify(string header, string message)
{
//Get time in seconds and convert to ms
var time = Convert.ToInt32(_configProvider.GetValue("XbmcDisplayTime", "3", true)) * 1000;
var time = Convert.ToInt32(_configProvider.GetValue("XbmcDisplayTime", "3", true))*1000;
var command = String.Format("ExecBuiltIn(Notification({0},{1},{2}))", header, message, time);
if (Convert.ToBoolean(_configProvider.GetValue("XbmcNotificationImage", false, true)))
@ -55,7 +50,8 @@ namespace NzbDrone.Core.Providers
var xbmcSeriesPath = GetXbmcSeriesPath(host, seriesId);
//If the path is not found & the user wants to update the entire library, do it now.
if (String.IsNullOrEmpty(xbmcSeriesPath) && Convert.ToBoolean(_configProvider.GetValue("XbmcFullUpdate", false, true)))
if (String.IsNullOrEmpty(xbmcSeriesPath) &&
Convert.ToBoolean(_configProvider.GetValue("XbmcFullUpdate", false, true)))
{
//Update the entire library
Logger.Trace("Series [{0}] doesn't exist on XBMC host: {1}, Updating Entire Library", seriesId, host);
@ -78,8 +74,6 @@ namespace NzbDrone.Core.Providers
}
}
#endregion
private string SendCommand(string host, string command)
{
var username = _configProvider.GetValue("XbmcUsername", String.Empty, true);
@ -90,16 +84,20 @@ namespace NzbDrone.Core.Providers
{
return _httpProvider.DownloadString(url, username, password);
}
return _httpProvider.DownloadString(url);
}
private string GetXbmcSeriesPath(string host, int seriesId)
{
var query = String.Format("select path.strPath from path, tvshow, tvshowlinkpath where tvshow.c12 = {0} and tvshowlinkpath.idShow = tvshow.idShow and tvshowlinkpath.idPath = path.idPath", seriesId);
var query =
String.Format(
"select path.strPath from path, tvshow, tvshowlinkpath where tvshow.c12 = {0} and tvshowlinkpath.idShow = tvshow.idShow and tvshowlinkpath.idPath = path.idPath",
seriesId);
var command = String.Format("QueryVideoDatabase({0})", query);
var setResponseCommand = "SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)";
var setResponseCommand =
"SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)";
var resetResponseCommand = "SetResponseFormat()";
SendCommand(host, setResponseCommand);
@ -123,4 +121,4 @@ namespace NzbDrone.Core.Providers
return field.Value;
}
}
}
}

@ -9,6 +9,7 @@ namespace NzbDrone.Core.Repository
{
[SubSonicPrimaryKey(false)]
public virtual int EpisodeId { get; set; }
public virtual int SeriesId { get; set; }
public virtual int EpisodeFileId { get; set; }
public virtual int SeasonId { get; set; }
@ -16,8 +17,10 @@ namespace NzbDrone.Core.Repository
public int EpisodeNumber { get; set; }
public string Title { get; set; }
public DateTime AirDate { get; set; }
[SubSonicLongString]
public string Overview { get; set; }
public string Language { get; set; }
public EpisodeStatusType Status { get; set; }
@ -37,4 +40,4 @@ namespace NzbDrone.Core.Repository
[SubSonicToManyRelation]
public virtual List<History> Histories { get; private set; }
}
}
}

@ -9,6 +9,7 @@ namespace NzbDrone.Core.Repository
{
[SubSonicPrimaryKey]
public virtual int EpisodeFileId { get; set; }
public virtual int SeriesId { get; set; }
public string Path { get; set; }
public QualityTypes Quality { get; set; }
@ -22,4 +23,4 @@ namespace NzbDrone.Core.Repository
[SubSonicToOneRelation(ThisClassContainsJoinKey = true)]
public virtual Series Series { get; private set; }
}
}
}

@ -8,6 +8,7 @@ namespace NzbDrone.Core.Repository
{
[SubSonicPrimaryKey]
public virtual int HistoryId { get; set; }
public virtual int EpisodeId { get; set; }
public virtual int IndexerId { get; set; }
public string NzbTitle { get; set; }
@ -21,4 +22,4 @@ namespace NzbDrone.Core.Repository
[SubSonicToOneRelation(ThisClassContainsJoinKey = true)]
public virtual Indexer Indexer { get; private set; }
}
}
}

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using SubSonic.SqlGeneration.Schema;
namespace NzbDrone.Core.Repository
@ -19,10 +15,11 @@ namespace NzbDrone.Core.Repository
[SubSonicNullStringAttribute]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ApiUrl { get; set; }
public bool Enabled { get; set; }
public int Order { get; set; }
[SubSonicToManyRelation]
public virtual List<History> Histories { get; private set; }
}
}
}

@ -15,6 +15,7 @@ namespace NzbDrone.Core.Repository.Quality
[DisplayName("Name")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }
public bool UserProfile { get; set; } //Allows us to tell the difference between default and user profiles
[SubSonicIgnore]
@ -37,10 +38,10 @@ namespace NzbDrone.Core.Repository.Quality
{
string result = String.Empty;
if (Allowed == null) return result;
foreach (var q in Allowed)
{
result += (int)q + "|";
result += (int) q + "|";
}
return result.Trim('|');
}
@ -50,7 +51,7 @@ namespace NzbDrone.Core.Repository.Quality
Allowed = new List<QualityTypes>(qualities.Length);
foreach (var quality in qualities)
{
Allowed.Add((QualityTypes)Convert.ToInt32(quality));
Allowed.Add((QualityTypes) Convert.ToInt32(quality));
}
}
}
@ -58,4 +59,4 @@ namespace NzbDrone.Core.Repository.Quality
[SubSonicToManyRelation]
public virtual List<string> Series { get; private set; }
}
}
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SubSonic.SqlGeneration.Schema;
using SubSonic.SqlGeneration.Schema;
namespace NzbDrone.Core.Repository
{
@ -13,4 +9,4 @@ namespace NzbDrone.Core.Repository
public string Path { get; set; }
}
}
}

@ -8,10 +8,11 @@ namespace NzbDrone.Core.Repository
{
[SubSonicPrimaryKey(false)]
public virtual int SeasonId { get; set; }
public virtual int SeriesId { get; set; }
public virtual int SeasonNumber { get; set; }
public bool Monitored { get; set; }
public DayOfWeek? LastInfoSync { get; set; }
public DayOfWeek? LastDiskSync { get; set; }

@ -1,21 +1,18 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace NzbDrone.PostProcessor
{
class Program
internal class Program
{
private static string _host = "localhost";
private static int _port = 8989;
private static string _apiKey = String.Empty;
static void Main(string[] args)
private static void Main(string[] args)
{
try
{
@ -35,7 +32,8 @@ namespace NzbDrone.PostProcessor
var hostString = _host + ":" + _port;
var url = String.Format("http://{0}/?apiKey={1}&dir={2}&nzbName={3}&category={4}", hostString, _apiKey, dir, nzbName, category);
var url = String.Format("http://{0}/?apiKey={1}&dir={2}&nzbName={3}&category={4}", hostString, _apiKey,
dir, nzbName, category);
var webClient = new WebClient();
webClient.DownloadString(url);
@ -46,7 +44,7 @@ namespace NzbDrone.PostProcessor
}
}
static bool LoadConfig()
private static bool LoadConfig()
{
var configFile = "PostProcessor.xml";
if (!File.Exists(configFile))
@ -65,8 +63,10 @@ namespace NzbDrone.PostProcessor
}
var hostNode = config.Descendants("Host").FirstOrDefault();
var portNode = config.Descendants("Port").FirstOrDefault(); ;
var apiKeyNode = config.Descendants("ApiKey").FirstOrDefault(); ;
var portNode = config.Descendants("Port").FirstOrDefault();
;
var apiKeyNode = config.Descendants("ApiKey").FirstOrDefault();
;
if (hostNode == null || portNode == null || apiKeyNode == null)
{
@ -81,4 +81,4 @@ namespace NzbDrone.PostProcessor
return true;
}
}
}
}

@ -1,10 +1,10 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NzbDrone.PostProcessor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6521fcb0-15dc-4324-b08a-f18f87d78859")]
// Version information for an assembly consists of the following four values:
@ -32,5 +34,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
@ -12,16 +10,17 @@ namespace NzbDrone.Web.Controllers
{
public class AddSeriesController : Controller
{
private readonly SyncProvider _syncProvider;
private readonly RootDirProvider _rootFolderProvider;
private readonly ConfigProvider _configProvider;
private readonly QualityProvider _qualityProvider;
private readonly TvDbProvider _tvDbProvider;
private readonly RootDirProvider _rootFolderProvider;
private readonly SeriesProvider _seriesProvider;
private readonly SyncProvider _syncProvider;
private readonly TvDbProvider _tvDbProvider;
public AddSeriesController(SyncProvider syncProvider, RootDirProvider rootFolderProvider, ConfigProvider configProvider,
QualityProvider qualityProvider, TvDbProvider tvDbProvider, SeriesProvider seriesProvider)
public AddSeriesController(SyncProvider syncProvider, RootDirProvider rootFolderProvider,
ConfigProvider configProvider,
QualityProvider qualityProvider, TvDbProvider tvDbProvider,
SeriesProvider seriesProvider)
{
_syncProvider = syncProvider;
_rootFolderProvider = rootFolderProvider;
@ -48,12 +47,12 @@ namespace NzbDrone.Web.Controllers
var defaultQuality = Convert.ToInt32(_configProvider.DefaultQualityProfile);
var model = new AddNewSeriesModel
{
DirectorySeparatorChar = Path.DirectorySeparatorChar.ToString(),
RootDirectories = _rootFolderProvider.GetAll(),
QualityProfileId = defaultQuality,
QualitySelectList = selectList
};
{
DirectorySeparatorChar = Path.DirectorySeparatorChar.ToString(),
RootDirectories = _rootFolderProvider.GetAll(),
QualityProfileId = defaultQuality,
QualitySelectList = selectList
};
return View(model);
}
@ -78,7 +77,6 @@ namespace NzbDrone.Web.Controllers
public ActionResult RenderPartial(string path)
{
var suggestions = GetSuggestionList(new DirectoryInfo(path).Name);
ViewData["guid"] = Guid.NewGuid();
@ -92,10 +90,10 @@ namespace NzbDrone.Web.Controllers
qualityProfiles,
"QualityProfileId",
"Name",
defaultQuality); ;
defaultQuality);
;
return PartialView("AddSeriesItem", suggestions);
}
public JsonResult AddSeries(string path, int seriesId, int qualityProfileId)
@ -104,9 +102,11 @@ namespace NzbDrone.Web.Controllers
//Create new folder for series
//Add the new series to the Database
_seriesProvider.AddSeries(path.Replace('|', Path.DirectorySeparatorChar).Replace('^', Path.VolumeSeparatorChar), seriesId, qualityProfileId);
_seriesProvider.AddSeries(
path.Replace('|', Path.DirectorySeparatorChar).Replace('^', Path.VolumeSeparatorChar), seriesId,
qualityProfileId);
ScanNewSeries();
return new JsonResult() { Data = "ok" };
return new JsonResult {Data = "ok"};
}
[HttpPost]
@ -115,10 +115,10 @@ namespace NzbDrone.Web.Controllers
var suggestions = GetSuggestionList(text);
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = suggestions
};
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = suggestions
};
}
public SelectList GetSuggestionList(string searchString)
@ -133,6 +133,5 @@ namespace NzbDrone.Web.Controllers
return new SelectList(dataVal, "Id", "SeriesName", selectId);
}
}
}
}

@ -1,11 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Web.Mvc;
using NLog;
using NzbDrone.Core;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
@ -13,10 +7,9 @@ namespace NzbDrone.Web.Controllers
{
public class ApiController : Controller
{
private readonly PostProcessingProvider _postProcessingProvider;
private readonly ConfigProvider _configProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _configProvider;
private readonly PostProcessingProvider _postProcessingProvider;
public ApiController(PostProcessingProvider postProcessingProvider, ConfigProvider configProvider)
{
@ -41,4 +34,4 @@ namespace NzbDrone.Web.Controllers
return Content("Category doesn't match what was configured for SAB TV Category...");
}
}
}
}

@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Repository.Quality;
using NzbDrone.Web.Models;
using Telerik.Web.Mvc;
@ -12,7 +8,7 @@ namespace NzbDrone.Web.Controllers
{
public class HistoryController : Controller
{
private HistoryProvider _historyProvider;
private readonly HistoryProvider _historyProvider;
public HistoryController(HistoryProvider historyProvider)
{
@ -59,4 +55,4 @@ namespace NzbDrone.Web.Controllers
return View(new GridModel(history));
}
}
}
}

@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc;
using NzbDrone.Core.Instrumentation;
using SubSonic.Repository;
using Telerik.Web.Mvc;
namespace NzbDrone.Web.Controllers
@ -28,7 +23,6 @@ namespace NzbDrone.Web.Controllers
{
_logProvider.DeleteAll();
return RedirectToAction("Index");
}
[GridAction]
@ -37,4 +31,4 @@ namespace NzbDrone.Web.Controllers
return View(new GridModel(_logProvider.GetAllLogs()));
}
}
}
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc;
using NzbDrone.Core.Providers;
namespace NzbDrone.Web.Controllers
@ -29,6 +25,5 @@ namespace NzbDrone.Web.Controllers
return Json(message, JsonRequestBehavior.AllowGet);
}
}
}
}

@ -1,43 +1,36 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Providers.Core;
using NzbDrone.Core.Repository;
using NzbDrone.Core.Repository.Quality;
using NzbDrone.Web.Models;
using Telerik.Web.Mvc;
using TvdbLib.Data;
using EpisodeModel = NzbDrone.Web.Models.EpisodeModel;
namespace NzbDrone.Web.Controllers
{
[HandleError]
public class SeriesController : Controller
{
private readonly SeriesProvider _seriesProvider;
private readonly EpisodeProvider _episodeProvider;
private readonly SyncProvider _syncProvider;
private readonly RssSyncProvider _rssSyncProvider;
private readonly QualityProvider _qualityProvider;
private readonly MediaFileProvider _mediaFileProvider;
private readonly QualityProvider _qualityProvider;
private readonly RenameProvider _renameProvider;
private readonly RootDirProvider _rootDirProvider;
private readonly RssSyncProvider _rssSyncProvider;
private readonly SeriesProvider _seriesProvider;
private readonly SyncProvider _syncProvider;
private readonly TvDbProvider _tvDbProvider;
//
// GET: /Series/
public SeriesController(SyncProvider syncProvider, SeriesProvider seriesProvider,
EpisodeProvider episodeProvider, RssSyncProvider rssSyncProvider,
QualityProvider qualityProvider, MediaFileProvider mediaFileProvider,
RenameProvider renameProvider, RootDirProvider rootDirProvider,
TvDbProvider tvDbProvider)
EpisodeProvider episodeProvider, RssSyncProvider rssSyncProvider,
QualityProvider qualityProvider, MediaFileProvider mediaFileProvider,
RenameProvider renameProvider, RootDirProvider rootDirProvider,
TvDbProvider tvDbProvider)
{
_seriesProvider = seriesProvider;
_episodeProvider = episodeProvider;
@ -57,9 +50,6 @@ namespace NzbDrone.Web.Controllers
}
public ActionResult RssSync()
{
_rssSyncProvider.Begin();
@ -68,33 +58,41 @@ namespace NzbDrone.Web.Controllers
public ActionResult UnMapped(string path)
{
return View(_syncProvider.GetUnmappedFolders(path).Select(c => new MappingModel() { Id = 1, Path = c }).ToList());
return View(_syncProvider.GetUnmappedFolders(path).Select(c => new MappingModel {Id = 1, Path = c}).ToList());
}
public ActionResult LoadEpisodes(int seriesId)
{
_episodeProvider.RefreshEpisodeInfo(seriesId);
return RedirectToAction("Details", new
{
seriesId = seriesId
});
{
seriesId
});
}
[GridAction]
public ActionResult _AjaxSeasonGrid(int seasonId)
{
var episodes = _episodeProvider.GetEpisodeBySeason(seasonId).Select(c => new EpisodeModel()
{
EpisodeId = c.EpisodeId,
EpisodeNumber = c.EpisodeNumber,
SeasonNumber = c.SeasonNumber,
Title = c.Title,
Overview = c.Overview,
AirDate = c.AirDate,
Path = GetEpisodePath(c.EpisodeFile),
Quality = c.EpisodeFile == null ? String.Empty : c.EpisodeFile.Quality.ToString()
});
var episodes = _episodeProvider.GetEpisodeBySeason(seasonId).Select(c => new EpisodeModel
{
EpisodeId = c.EpisodeId,
EpisodeNumber =
c.EpisodeNumber,
SeasonNumber =
c.SeasonNumber,
Title = c.Title,
Overview = c.Overview,
AirDate = c.AirDate,
Path =
GetEpisodePath(
c.EpisodeFile),
Quality =
c.EpisodeFile == null
? String.Empty
: c.EpisodeFile.
Quality.
ToString()
});
return View(new GridModel(episodes));
}
@ -103,10 +101,10 @@ namespace NzbDrone.Web.Controllers
{
IEnumerable<Episode> data = GetData(command);
return View(new GridModel
{
Data = data,
Total = data.Count()
});
{
Data = data,
Total = data.Count()
});
}
[GridAction]
@ -123,16 +121,16 @@ namespace NzbDrone.Web.Controllers
//We still want to show this series as unmapped, but we don't know what it will be when mapped
//Todo: Provide the user with a way to manually map a folder to a TvDb series (or make them rename the folder...)
if (tvDbSeries == null)
tvDbSeries = new TvdbSeries { Id = 0, SeriesName = String.Empty };
tvDbSeries = new TvdbSeries {Id = 0, SeriesName = String.Empty};
unmappedList.Add(new AddExistingSeriesModel
{
IsWanted = true,
Path = unmappedFolder,
PathEncoded = Url.Encode(unmappedFolder),
TvDbId = tvDbSeries.Id,
TvDbName = tvDbSeries.SeriesName
});
{
IsWanted = true,
Path = unmappedFolder,
PathEncoded = Url.Encode(unmappedFolder),
TvDbId = tvDbSeries.Id,
TvDbName = tvDbSeries.SeriesName
});
}
}
@ -163,7 +161,6 @@ namespace NzbDrone.Web.Controllers
private IEnumerable<Episode> GetData(GridCommand command)
{
return null;
/*
IQueryable<Episode> data = .Orders;
@ -266,7 +263,7 @@ namespace NzbDrone.Web.Controllers
var series = _seriesProvider.GetSeries(seriesId);
_mediaFileProvider.Scan(series);
return RedirectToAction("Details", new { seriesId });
return RedirectToAction("Details", new {seriesId});
}
public ActionResult RenameAll()
@ -278,7 +275,7 @@ namespace NzbDrone.Web.Controllers
public ActionResult RenameSeries(int seriesId)
{
_renameProvider.RenameSeries(seriesId);
return RedirectToAction("Details", new { seriesId });
return RedirectToAction("Details", new {seriesId});
}
public ActionResult RenameSeason(int seasonId)
@ -305,4 +302,4 @@ namespace NzbDrone.Web.Controllers
return file.Path.Replace(file.Series.Path, "").Trim(Path.DirectorySeparatorChar);
}
}
}
}

@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using NLog;
using NzbDrone.Core;
using NzbDrone.Core.Helpers;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
@ -19,17 +16,16 @@ namespace NzbDrone.Web.Controllers
[HandleError]
public class SettingsController : Controller
{
private ConfigProvider _configProvider;
private IndexerProvider _indexerProvider;
private QualityProvider _qualityProvider;
private RootDirProvider _rootDirProvider;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private const string SETTINGS_SAVED = "Settings Saved.";
private const string SETTINGS_FAILED = "Error Saving Settings, please fix any errors";
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ConfigProvider _configProvider;
private readonly IndexerProvider _indexerProvider;
private readonly QualityProvider _qualityProvider;
private readonly RootDirProvider _rootDirProvider;
public SettingsController(ConfigProvider configProvider, IndexerProvider indexerProvider,
QualityProvider qualityProvider, RootDirProvider rootDirProvider)
QualityProvider qualityProvider, RootDirProvider rootDirProvider)
{
_configProvider = configProvider;
_indexerProvider = indexerProvider;
@ -63,8 +59,10 @@ namespace NzbDrone.Web.Controllers
ViewData["viewName"] = "Indexers";
return View("Index", new IndexerSettingsModel
{
NzbMatrixUsername = _configProvider.GetValue("NzbMatrixUsername", String.Empty, true),
NzbMatrixApiKey = _configProvider.GetValue("NzbMatrixApiKey", String.Empty, true),
NzbMatrixUsername =
_configProvider.GetValue("NzbMatrixUsername", String.Empty, true),
NzbMatrixApiKey =
_configProvider.GetValue("NzbMatrixApiKey", String.Empty, true),
NzbsOrgUId = _configProvider.GetValue("NzbsOrgUId", String.Empty, true),
NzbsOrgHash = _configProvider.GetValue("NzbsOrgHash", String.Empty, true),
NzbsrusUId = _configProvider.GetValue("NzbsrusUId", String.Empty, true),
@ -80,7 +78,8 @@ namespace NzbDrone.Web.Controllers
var model = new DownloadSettingsModel
{
SyncFrequency = Convert.ToInt32(_configProvider.GetValue("SyncFrequency", "15", true)),
DownloadPropers = Convert.ToBoolean(_configProvider.GetValue("DownloadPropers", "false", true)),
DownloadPropers =
Convert.ToBoolean(_configProvider.GetValue("DownloadPropers", "false", true)),
Retention = Convert.ToInt32(_configProvider.GetValue("Retention", "500", true)),
SabHost = _configProvider.GetValue("SabHost", "localhost", true),
SabPort = Convert.ToInt32(_configProvider.GetValue("SabPort", "8080", true)),
@ -88,7 +87,10 @@ namespace NzbDrone.Web.Controllers
SabUsername = _configProvider.GetValue("SabUsername", String.Empty, true),
SabPassword = _configProvider.GetValue("SabPassword", String.Empty, true),
SabTvCategory = _configProvider.GetValue("SabTvCategory", String.Empty, true),
SabTvPriority = (SabnzbdPriorityType)Enum.Parse(typeof(SabnzbdPriorityType), _configProvider.GetValue("SabTvPriority", "Normal", true)),
SabTvPriority =
(SabnzbdPriorityType)
Enum.Parse(typeof (SabnzbdPriorityType),
_configProvider.GetValue("SabTvPriority", "Normal", true)),
UseBlackHole = Convert.ToBoolean(_configProvider.GetValue("UseBlackHole", true, true)),
BlackholeDirectory = _configProvider.GetValue("BlackholeDirectory", String.Empty, true)
};
@ -102,7 +104,7 @@ namespace NzbDrone.Web.Controllers
var qualityTypes = new List<QualityTypes>();
foreach (QualityTypes qual in Enum.GetValues(typeof(QualityTypes)))
foreach (QualityTypes qual in Enum.GetValues(typeof (QualityTypes)))
{
qualityTypes.Add(qual);
}
@ -112,17 +114,18 @@ namespace NzbDrone.Web.Controllers
var userProfiles = _qualityProvider.GetAllProfiles().Where(q => q.UserProfile).ToList();
var profiles = _qualityProvider.GetAllProfiles().ToList();
var defaultQualityQualityProfileId = Convert.ToInt32(_configProvider.GetValue("DefaultQualityProfile", profiles[0].QualityProfileId, true));
var defaultQualityQualityProfileId =
Convert.ToInt32(_configProvider.GetValue("DefaultQualityProfile", profiles[0].QualityProfileId, true));
var selectList = new SelectList(profiles, "QualityProfileId", "Name");
var model = new QualityModel
{
Profiles = profiles,
UserProfiles = userProfiles,
DefaultQualityProfileId = defaultQualityQualityProfileId,
SelectList = selectList
};
{
Profiles = profiles,
UserProfiles = userProfiles,
DefaultQualityProfileId = defaultQualityQualityProfileId,
SelectList = selectList
};
return View("Index", model);
}
@ -132,22 +135,31 @@ namespace NzbDrone.Web.Controllers
ViewData["viewName"] = "Notifications";
var model = new NotificationSettingsModel
{
XbmcEnabled = Convert.ToBoolean(_configProvider.GetValue("XbmcEnabled", false, true)),
XbmcNotifyOnGrab = Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnGrab", false, true)),
XbmcNotifyOnDownload = Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnDownload", false, true)),
XbmcNotifyOnRename = Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnRename", false, true)),
XbmcNotificationImage = Convert.ToBoolean(_configProvider.GetValue("XbmcNotificationImage", false, true)),
XbmcDisplayTime = Convert.ToInt32(_configProvider.GetValue("XbmcDisplayTime", 3, true)),
XbmcUpdateOnDownload = Convert.ToBoolean(_configProvider.GetValue("XbmcUpdateOnDownload ", false, true)),
XbmcUpdateOnRename = Convert.ToBoolean(_configProvider.GetValue("XbmcUpdateOnRename", false, true)),
XbmcFullUpdate = Convert.ToBoolean(_configProvider.GetValue("XbmcFullUpdate", false, true)),
XbmcCleanOnDownload = Convert.ToBoolean(_configProvider.GetValue("XbmcCleanOnDownload", false, true)),
XbmcCleanOnRename = Convert.ToBoolean(_configProvider.GetValue("XbmcCleanOnRename", false, true)),
XbmcHosts = _configProvider.GetValue("XbmcHosts", "localhost:80", true),
XbmcUsername = _configProvider.GetValue("XbmcUsername", String.Empty, true),
XbmcPassword = _configProvider.GetValue("XbmcPassword", String.Empty, true)
};
{
XbmcEnabled = Convert.ToBoolean(_configProvider.GetValue("XbmcEnabled", false, true)),
XbmcNotifyOnGrab =
Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnGrab", false, true)),
XbmcNotifyOnDownload =
Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnDownload", false, true)),
XbmcNotifyOnRename =
Convert.ToBoolean(_configProvider.GetValue("XbmcNotifyOnRename", false, true)),
XbmcNotificationImage =
Convert.ToBoolean(_configProvider.GetValue("XbmcNotificationImage", false, true)),
XbmcDisplayTime = Convert.ToInt32(_configProvider.GetValue("XbmcDisplayTime", 3, true)),
XbmcUpdateOnDownload =
Convert.ToBoolean(_configProvider.GetValue("XbmcUpdateOnDownload ", false, true)),
XbmcUpdateOnRename =
Convert.ToBoolean(_configProvider.GetValue("XbmcUpdateOnRename", false, true)),
XbmcFullUpdate =
Convert.ToBoolean(_configProvider.GetValue("XbmcFullUpdate", false, true)),
XbmcCleanOnDownload =
Convert.ToBoolean(_configProvider.GetValue("XbmcCleanOnDownload", false, true)),
XbmcCleanOnRename =
Convert.ToBoolean(_configProvider.GetValue("XbmcCleanOnRename", false, true)),
XbmcHosts = _configProvider.GetValue("XbmcHosts", "localhost:80", true),
XbmcUsername = _configProvider.GetValue("XbmcUsername", String.Empty, true),
XbmcPassword = _configProvider.GetValue("XbmcPassword", String.Empty, true)
};
return View("Index", model);
}
@ -180,14 +192,14 @@ namespace NzbDrone.Web.Controllers
{
var qualityTypes = new List<QualityTypes>();
foreach (QualityTypes qual in Enum.GetValues(typeof(QualityTypes)))
foreach (QualityTypes qual in Enum.GetValues(typeof (QualityTypes)))
{
qualityTypes.Add(qual);
}
ViewData["Qualities"] = qualityTypes;
return View("UserProfileSection", new QualityProfile { Name = "New Profile", UserProfile = true });
return View("UserProfileSection", new QualityProfile {Name = "New Profile", UserProfile = true});
}
public ViewResult AddRootDir()
@ -203,10 +215,11 @@ namespace NzbDrone.Web.Controllers
public QualityModel GetUpdatedProfileList()
{
var profiles = _qualityProvider.GetAllProfiles().ToList();
var defaultQualityQualityProfileId = Convert.ToInt32(_configProvider.GetValue("DefaultQualityProfile", profiles[0].QualityProfileId, true));
var defaultQualityQualityProfileId =
Convert.ToInt32(_configProvider.GetValue("DefaultQualityProfile", profiles[0].QualityProfileId, true));
var selectList = new SelectList(profiles, "QualityProfileId", "Name");
return new QualityModel { DefaultQualityProfileId = defaultQualityQualityProfileId, SelectList = selectList };
return new QualityModel {DefaultQualityProfileId = defaultQualityQualityProfileId, SelectList = selectList};
}
[HttpPost]
@ -315,7 +328,7 @@ namespace NzbDrone.Web.Controllers
profile.Allowed = new List<QualityTypes>();
foreach (var quality in profile.AllowedString.Split(','))
{
var qType = (QualityTypes)Enum.Parse(typeof(QualityTypes), quality);
var qType = (QualityTypes) Enum.Parse(typeof (QualityTypes), quality);
profile.Allowed.Add(qType);
}
@ -385,4 +398,4 @@ namespace NzbDrone.Web.Controllers
return Content(SETTINGS_FAILED);
}
}
}
}

@ -1,15 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc;
using NzbDrone.Core.Providers;
namespace NzbDrone.Web.Controllers
{
public class SharedController : Controller
{
private TimerProvider _timerProvider;
private readonly TimerProvider _timerProvider;
public SharedController(TimerProvider timerProvider)
{
@ -29,4 +25,4 @@ namespace NzbDrone.Web.Controllers
return PartialView();
}
}
}
}

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using NzbDrone.Core.Providers;
using NzbDrone.Web.Models;
@ -11,7 +8,7 @@ namespace NzbDrone.Web.Controllers
{
public class UpcomingController : Controller
{
private UpcomingEpisodesProvider _upcomingEpisodesProvider;
private readonly UpcomingEpisodesProvider _upcomingEpisodesProvider;
public UpcomingController(UpcomingEpisodesProvider upcomingEpisodesProvider)
{
@ -30,16 +27,16 @@ namespace NzbDrone.Web.Controllers
public ActionResult _AjaxBindingYesterday()
{
var upcoming = _upcomingEpisodesProvider.Yesterday().Select(e => new UpcomingEpisodeModel
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
return View(new GridModel(upcoming));
}
@ -47,15 +44,15 @@ namespace NzbDrone.Web.Controllers
public ActionResult _AjaxBindingToday()
{
var upcoming = _upcomingEpisodesProvider.Today().Select(e => new UpcomingEpisodeModel
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
return View(new GridModel(upcoming));
}
@ -64,17 +61,17 @@ namespace NzbDrone.Web.Controllers
public ActionResult _AjaxBindingWeek()
{
var upcoming = _upcomingEpisodesProvider.Week().Select(e => new UpcomingEpisodeModel
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
{
SeriesId = e.Series.SeriesId,
SeriesName = e.Series.Title,
SeasonNumber = e.SeasonNumber,
EpisodeNumber = e.EpisodeNumber,
Title = e.Title,
Overview = e.Overview,
AirDate = e.AirDate
});
return View(new GridModel(upcoming));
}
}
}
}

@ -1,6 +1,5 @@
using System;
using System.Data.SQLite;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Web;
@ -11,7 +10,6 @@ using Ninject.Web.Mvc;
using NLog;
using NzbDrone.Core;
using NzbDrone.Core.Instrumentation;
using SubSonic.Repository;
namespace NzbDrone.Web
{
@ -21,17 +19,16 @@ namespace NzbDrone.Web
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" });
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.IgnoreRoute("{*robotstxt}", new {robotstxt = @"(.*/)?robots.txt(/.*)?"});
routes.IgnoreRoute("{*favicon}", new {favicon = @"(.*/)?favicon.ico(/.*)?"});
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Series", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller = "Series", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
}
protected override void OnApplicationStarted()
@ -85,15 +82,11 @@ namespace NzbDrone.Web
Logger.Warn("Restarting application");
HttpRuntime.UnloadAppDomain();
}
}
protected void Application_BeginRequest()
{
Thread.CurrentThread.Name = "UI";
}
}
}

@ -1,7 +1,7 @@
using System;
using System.Web.Mvc;
using System.Web;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace NzbDrone.Web.Helpers
{
@ -15,7 +15,9 @@ namespace NzbDrone.Web.Helpers
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, itemIndex));
html.ViewContext.Writer.WriteLine(
string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />",
collectionName, itemIndex));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
@ -30,8 +32,9 @@ namespace NzbDrone.Web.Helpers
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null) {
var queue = (Queue<string>) httpContext.Items[key];
if (queue == null)
{
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
@ -41,10 +44,12 @@ namespace NzbDrone.Web.Helpers
return queue;
}
#region Nested type: HtmlFieldPrefixScope
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
private readonly TemplateInfo templateInfo;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
@ -54,10 +59,16 @@ namespace NzbDrone.Web.Helpers
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
#region IDisposable Members
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
#endregion
}
#endregion
}
}

@ -1,14 +1,14 @@
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Helpers
{
public static class IsCurrentActionHelper
{
private static bool IsCurrentController(HtmlHelper helper, string actionName, string controllerName)
{
var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
var currentControllerName = (string) helper.ViewContext.RouteData.Values["controller"];
if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase))
return true;
@ -16,7 +16,8 @@ namespace Helpers
return false;
}
public static string CurrentActionLink(this HtmlHelper helper, string text, string actionName, string controllerName)
public static string CurrentActionLink(this HtmlHelper helper, string text, string actionName,
string controllerName)
{
string result;
@ -30,7 +31,6 @@ namespace Helpers
}
return result + helper.ActionLink(text, actionName, controllerName).ToHtmlString() + @"</li>";
}
}
}
}

@ -1,18 +1,16 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace NzbDrone.Web.Models
{
#region Models
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
[PropertiesMustMatch("NewPassword", "ConfirmPassword",
ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
[Required]
@ -47,7 +45,8 @@ namespace NzbDrone.Web.Models
public bool RememberMe { get; set; }
}
[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
[PropertiesMustMatch("Password", "ConfirmPassword",
ErrorMessage = "The password and confirmation password do not match.")]
public class RegisterModel
{
[Required]
@ -70,9 +69,11 @@ namespace NzbDrone.Web.Models
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
}
#endregion
#region Services
// The FormsAuthentication type is sealed and contains static members, so it is difficult to
// unit test code that calls its members. The interface and helper class below demonstrate
// how to create an abstract wrapper around such a type in order to make the AccountController
@ -101,26 +102,29 @@ namespace NzbDrone.Web.Models
_provider = provider ?? Membership.Provider;
}
#region IMembershipService Members
public int MinPasswordLength
{
get
{
return _provider.MinRequiredPasswordLength;
}
get { return _provider.MinRequiredPasswordLength; }
}
public bool ValidateUser(string userName, string password)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password))
throw new ArgumentException("Value cannot be null or empty.", "password");
return _provider.ValidateUser(userName, password);
}
public MembershipCreateStatus CreateUser(string userName, string password, string email)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password))
throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
MembershipCreateStatus status;
@ -130,9 +134,12 @@ namespace NzbDrone.Web.Models
public bool ChangePassword(string userName, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(oldPassword))
throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword))
throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
@ -150,6 +157,8 @@ namespace NzbDrone.Web.Models
return false;
}
}
#endregion
}
public interface IFormsAuthenticationService
@ -160,9 +169,12 @@ namespace NzbDrone.Web.Models
public class FormsAuthenticationService : IFormsAuthenticationService
{
#region IFormsAuthenticationService Members
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
@ -171,10 +183,14 @@ namespace NzbDrone.Web.Models
{
FormsAuthentication.SignOut();
}
#endregion
}
#endregion
#region Validation
public static class AccountValidation
{
public static string ErrorCodeToString(MembershipCreateStatus createStatus)
@ -205,13 +221,16 @@ namespace NzbDrone.Web.Models
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
return
"The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
return
"The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
return
"An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
}
@ -234,16 +253,13 @@ namespace NzbDrone.Web.Models
public override object TypeId
{
get
{
return _typeId;
}
get { return _typeId; }
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
@ -251,7 +267,7 @@ namespace NzbDrone.Web.Models
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
return Equals(originalValue, confirmValue);
}
}
@ -269,7 +285,7 @@ namespace NzbDrone.Web.Models
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
name, _minCharacters);
name, _minCharacters);
}
public override bool IsValid(object value)
@ -278,6 +294,6 @@ namespace NzbDrone.Web.Models
return (valueAsString != null && valueAsString.Length >= _minCharacters);
}
}
#endregion
}
#endregion
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.Mvc;
namespace NzbDrone.Web.Models

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NzbDrone.Web.Models
namespace NzbDrone.Web.Models
{
public class AddExistingSeriesModel
{

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NzbDrone.Core.Repository;

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NzbDrone.Core.Model;
@ -11,110 +8,63 @@ namespace NzbDrone.Web.Models
{
public class DownloadSettingsModel
{
public SelectList PrioritySelectList =
new SelectList(new[] {"Default", "Paused", "Low", "Normal", "High", "Top"});
[Required]
[Range(15, 120, ErrorMessage = "Must be between 15 and 120 minutes")]
[DataType(DataType.Text)]
[DisplayName("Sync Frequency")]
public int SyncFrequency
{
get;
set;
}
public int SyncFrequency { get; set; }
[DisplayName("Download Propers")]
public bool DownloadPropers
{
get;
set;
}
public bool DownloadPropers { get; set; }
[Required (ErrorMessage = "Please enter a valid number")]
[Required(ErrorMessage = "Please enter a valid number")]
[DataType(DataType.Text)]
[DisplayName("Retention")]
public int Retention
{
get;
set;
}
public int Retention { get; set; }
[Required (ErrorMessage = "Please enter a valid host")]
[Required(ErrorMessage = "Please enter a valid host")]
[DataType(DataType.Text)]
[DisplayName("SABnzbd Host")]
public String SabHost
{
get;
set;
}
public String SabHost { get; set; }
[Required(ErrorMessage = "Please enter a valid port")]
[DataType(DataType.Text)]
[DisplayName("SABnzbd Port")]
public int SabPort
{
get;
set;
}
public int SabPort { get; set; }
[DataType(DataType.Text)]
[DisplayName("SABnzbd API Key")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public String SabApiKey
{
get;
set;
}
public String SabApiKey { get; set; }
[DataType(DataType.Text)]
[DisplayName("SABnzbd Username")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public String SabUsername
{
get;
set;
}
public String SabUsername { get; set; }
[DataType(DataType.Text)]
[DisplayName("SABnzbd Password")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public String SabPassword
{
get;
set;
}
public String SabPassword { get; set; }
[DataType(DataType.Text)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("SABnzbd TV Category")]
public String SabTvCategory
{
get;
set;
}
public String SabTvCategory { get; set; }
[Required(ErrorMessage = "Please select a valid priority")]
[DisplayName("SABnzbd Priority")]
public SabnzbdPriorityType SabTvPriority
{
get;
set;
}
public SabnzbdPriorityType SabTvPriority { get; set; }
[DisplayName("Use Blackhole")]
public bool UseBlackHole
{
get;
set;
}
public bool UseBlackHole { get; set; }
[DataType(DataType.Text)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("Blackhole Directory")]
public String BlackholeDirectory
{
get;
set;
}
public SelectList PrioritySelectList = new SelectList(new string[] { "Default", "Paused", "Low", "Normal", "High", "Top" });
public String BlackholeDirectory { get; set; }
}
}

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NzbDrone.Core.Repository.Quality;
namespace NzbDrone.Web.Models
{

@ -1,11 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NzbDrone.Core.Model;
namespace NzbDrone.Web.Models
{

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

Loading…
Cancel
Save