1
0
mirror of https://github.com/Radarr/Radarr.git synced 2024-11-19 17:32:38 +01:00

New: Remove Legacy API

This commit is contained in:
Qstick 2021-05-23 12:44:19 -04:00
parent ee8dfe1ea9
commit b7f3791966
116 changed files with 2 additions and 6229 deletions

View File

@ -916,7 +916,7 @@ stages:
projectVersion: '$(radarrVersion)'
extraProperties: |
sonar.exclusions=**/obj/**,**/*.dll,**/NzbDrone.Core.Test/Files/**/*,./frontend/**,**/ExternalModules/**,./src/Libraries/**
sonar.coverage.exclusions=**/Radarr.Api.V3/**/*,**/NzbDrone.Api/**/*,**/MonoTorrent/**/*,**/Marr.Data/**/*
sonar.coverage.exclusions=**/Radarr.Api.V3/**/*
sonar.cs.opencover.reportsPaths=$(Build.SourcesDirectory)/CoverageResults/**/coverage.opencover.xml
sonar.cs.nunit.reportsPaths=$(Build.SourcesDirectory)/TestResult.xml
- bash: |

View File

@ -1,30 +0,0 @@
using NzbDrone.Core.Blacklisting;
using NzbDrone.Core.Datastore;
using Radarr.Http;
namespace NzbDrone.Api.Blacklist
{
public class BlacklistModule : RadarrRestModule<BlacklistResource>
{
private readonly IBlacklistService _blacklistService;
public BlacklistModule(IBlacklistService blacklistService)
{
_blacklistService = blacklistService;
GetResourcePaged = GetBlacklist;
DeleteResource = DeleteBlacklist;
}
private PagingResource<BlacklistResource> GetBlacklist(PagingResource<BlacklistResource> pagingResource)
{
var pagingSpec = pagingResource.MapToPagingSpec<BlacklistResource, Core.Blacklisting.Blacklist>("id", SortDirection.Ascending);
return ApplyToPage(_blacklistService.Paged, pagingSpec, BlacklistResourceMapper.MapToResource);
}
private void DeleteBlacklist(int id)
{
_blacklistService.Delete(id);
}
}
}

View File

@ -1,47 +0,0 @@
using System;
using System.Collections.Generic;
using NzbDrone.Api.Movies;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Blacklist
{
public class BlacklistResource : RestResource
{
public int SeriesId { get; set; }
public List<int> EpisodeIds { get; set; }
public int MovieId { get; set; }
public string SourceTitle { get; set; }
public QualityModel Quality { get; set; }
public DateTime Date { get; set; }
public DownloadProtocol Protocol { get; set; }
public string Indexer { get; set; }
public string Message { get; set; }
public MovieResource Movie { get; set; }
}
public static class BlacklistResourceMapper
{
public static BlacklistResource MapToResource(this Core.Blacklisting.Blacklist model)
{
if (model == null)
{
return null;
}
return new BlacklistResource
{
Id = model.Id,
MovieId = model.MovieId,
SourceTitle = model.SourceTitle,
Quality = model.Quality,
Date = model.Date,
Protocol = model.Protocol,
Indexer = model.Indexer,
Message = model.Message,
Movie = model.Movie.ToResource()
};
}
}
}

View File

@ -1,71 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy;
using NzbDrone.Api.Movies;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.Movies;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.Calendar
{
public class CalendarModule : RadarrRestModuleWithSignalR<MovieResource, Movie>
{
protected readonly IMovieService _moviesService;
private readonly IMapCoversToLocal _coverMapper;
public CalendarModule(IBroadcastSignalRMessage signalR,
IMovieService moviesService,
IMapCoversToLocal coverMapper)
: base(signalR, "calendar")
{
_moviesService = moviesService;
_coverMapper = coverMapper;
GetResourceAll = GetCalendar;
}
private List<MovieResource> GetCalendar()
{
var start = DateTime.Today;
var end = DateTime.Today.AddDays(2);
var includeUnmonitored = false;
var queryStart = Request.Query.Start;
var queryEnd = Request.Query.End;
var queryIncludeUnmonitored = Request.Query.Unmonitored;
if (queryStart.HasValue)
{
start = DateTime.Parse(queryStart.Value);
}
if (queryEnd.HasValue)
{
end = DateTime.Parse(queryEnd.Value);
}
if (queryIncludeUnmonitored.HasValue)
{
includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value);
}
var resources = _moviesService.GetMoviesBetweenDates(start, end, includeUnmonitored).Select(MapToResource);
return resources.OrderBy(e => e.InCinemas).ToList();
}
protected MovieResource MapToResource(Movie movie)
{
if (movie == null)
{
return null;
}
var resource = movie.ToResource();
return resource;
}
}
}

View File

@ -1,38 +0,0 @@
using System.Text;
using Nancy;
using Nancy.Responses;
namespace NzbDrone.Api.Calendar
{
public class LegacyCalendarFeedModule : NzbDroneFeedModule
{
public LegacyCalendarFeedModule()
: base("calendar")
{
Get("/NzbDrone.ics", options => GetCalendarFeed());
Get("/Sonarr.ics", options => GetCalendarFeed());
Get("/Radarr.ics", options => GetCalendarFeed());
}
private object GetCalendarFeed()
{
string queryString = ConvertQueryParams(Request.Query);
var url = string.Format("/feed/v3/calendar/Radarr.ics?{0}", queryString);
return Response.AsRedirect(url, RedirectResponse.RedirectType.Permanent);
}
private string ConvertQueryParams(DynamicDictionary query)
{
var sb = new StringBuilder();
foreach (var key in query)
{
var value = query[key];
sb.AppendFormat("&{0}={1}", key, value);
}
return sb.ToString().Trim('&');
}
}
}

View File

@ -1,76 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NLog;
using NzbDrone.Common;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.ProgressMessaging;
using NzbDrone.SignalR;
using Radarr.Http;
using Radarr.Http.Extensions;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Commands
{
public class CommandModule : RadarrRestModuleWithSignalR<CommandResource, CommandModel>, IHandle<CommandUpdatedEvent>
{
private readonly IManageCommandQueue _commandQueueManager;
private readonly IServiceFactory _serviceFactory;
private readonly Logger _logger;
public CommandModule(IManageCommandQueue commandQueueManager,
IBroadcastSignalRMessage signalRBroadcaster,
IServiceFactory serviceFactory,
Logger logger)
: base(signalRBroadcaster)
{
_commandQueueManager = commandQueueManager;
_serviceFactory = serviceFactory;
_logger = logger;
GetResourceById = GetCommand;
CreateResource = StartCommand;
GetResourceAll = GetStartedCommands;
PostValidator.RuleFor(c => c.Name).NotBlank();
}
private CommandResource GetCommand(int id)
{
return _commandQueueManager.Get(id).ToResource();
}
private int StartCommand(CommandResource commandResource)
{
var commandType = _serviceFactory.GetImplementations(typeof(Command))
.SingleOrDefault(c => c.Name.Replace("Command", "").Equals(commandResource.Name, StringComparison.InvariantCultureIgnoreCase));
if (commandType == null)
{
_logger.Error("Found no matching command for {0}", commandResource.Name);
return 0;
}
dynamic command = Request.Body.FromJson(commandType);
command.Trigger = CommandTrigger.Manual;
var trackedCommand = _commandQueueManager.Push(command, CommandPriority.Normal, CommandTrigger.Manual);
return trackedCommand.Id;
}
private List<CommandResource> GetStartedCommands()
{
return _commandQueueManager.GetStarted().ToResource();
}
public void Handle(CommandUpdatedEvent message)
{
if (message.Command.Body.SendUpdatesToClient)
{
BroadcastResourceChange(ModelAction.Updated, message.Command.ToResource());
}
}
}
}

View File

@ -1,143 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using NzbDrone.Common.Http;
using NzbDrone.Core.Messaging.Commands;
using Radarr.Http.REST;
namespace NzbDrone.Api.Commands
{
public class CommandResource : RestResource
{
public string Name { get; set; }
public string Message { get; set; }
public object Body { get; set; }
public CommandPriority Priority { get; set; }
public CommandStatus Status { get; set; }
public DateTime Queued { get; set; }
public DateTime? Started { get; set; }
public DateTime? Ended { get; set; }
public TimeSpan? Duration { get; set; }
public string Exception { get; set; }
public CommandTrigger Trigger { get; set; }
public string ClientUserAgent { get; set; }
[JsonIgnore]
public string CompletionMessage { get; set; }
//Legacy
public CommandStatus State
{
get { return Status; }
set { }
}
public bool Manual
{
get { return Trigger == CommandTrigger.Manual; }
set { }
}
public DateTime StartedOn
{
get { return Queued; }
set { }
}
public DateTime? StateChangeTime
{
get
{
if (Started.HasValue)
{
return Started.Value;
}
return Ended;
}
set
{
}
}
public bool SendUpdatesToClient
{
get
{
if (Body != null)
{
return (Body as Command).SendUpdatesToClient;
}
return false;
}
set
{
}
}
public bool UpdateScheduledTask
{
get
{
if (Body != null)
{
return (Body as Command).UpdateScheduledTask;
}
return false;
}
set
{
}
}
public DateTime? LastExecutionTime { get; set; }
}
public static class CommandResourceMapper
{
public static CommandResource ToResource(this CommandModel model)
{
if (model == null)
{
return null;
}
return new CommandResource
{
Id = model.Id,
Name = model.Name,
Message = model.Message,
Body = model.Body,
Priority = model.Priority,
Status = model.Status,
Queued = model.QueuedAt,
Started = model.StartedAt,
Ended = model.EndedAt,
Duration = model.Duration,
Exception = model.Exception,
Trigger = model.Trigger,
ClientUserAgent = UserAgentParser.SimplifyUserAgent(model.Body.ClientUserAgent),
CompletionMessage = model.Body.CompletionMessage,
LastExecutionTime = model.Body.LastExecutionTime
};
}
public static List<CommandResource> ToResource(this IEnumerable<CommandModel> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,17 +0,0 @@
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Config
{
public class DownloadClientConfigModule : NzbDroneConfigModule<DownloadClientConfigResource>
{
public DownloadClientConfigModule(IConfigService configService)
: base(configService)
{
}
protected override DownloadClientConfigResource ToResource(IConfigService model)
{
return DownloadClientConfigResourceMapper.ToResource(model);
}
}
}

View File

@ -1,35 +0,0 @@
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class DownloadClientConfigResource : RestResource
{
public string DownloadClientWorkingFolders { get; set; }
public bool EnableCompletedDownloadHandling { get; set; }
public bool RemoveCompletedDownloads { get; set; }
public int CheckForFinishedDownloadInterval { get; set; }
public bool AutoRedownloadFailed { get; set; }
public bool RemoveFailedDownloads { get; set; }
}
public static class DownloadClientConfigResourceMapper
{
public static DownloadClientConfigResource ToResource(IConfigService model)
{
return new DownloadClientConfigResource
{
DownloadClientWorkingFolders = model.DownloadClientWorkingFolders,
EnableCompletedDownloadHandling = model.EnableCompletedDownloadHandling,
RemoveCompletedDownloads = model.RemoveCompletedDownloads,
CheckForFinishedDownloadInterval = model.CheckForFinishedDownloadInterval,
AutoRedownloadFailed = model.AutoRedownloadFailed,
RemoveFailedDownloads = model.RemoveFailedDownloads
};
}
}
}

View File

@ -1,90 +0,0 @@
using System.IO;
using System.Linq;
using System.Reflection;
using FluentValidation;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Authentication;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Update;
using NzbDrone.Core.Validation;
using NzbDrone.Core.Validation.Paths;
using Radarr.Http;
namespace NzbDrone.Api.Config
{
public class HostConfigModule : RadarrRestModule<HostConfigResource>
{
private readonly IConfigFileProvider _configFileProvider;
private readonly IConfigService _configService;
private readonly IUserService _userService;
public HostConfigModule(IConfigFileProvider configFileProvider, IConfigService configService, IUserService userService)
: base("/config/host")
{
_configFileProvider = configFileProvider;
_configService = configService;
_userService = userService;
GetResourceSingle = GetHostConfig;
GetResourceById = GetHostConfig;
UpdateResource = SaveHostConfig;
SharedValidator.RuleFor(c => c.BindAddress)
.ValidIp4Address()
.NotListenAllIp4Address()
.When(c => c.BindAddress != "*");
SharedValidator.RuleFor(c => c.Port).ValidPort();
SharedValidator.RuleFor(c => c.UrlBase).ValidUrlBase();
SharedValidator.RuleFor(c => c.Username).NotEmpty().When(c => c.AuthenticationMethod != AuthenticationType.None);
SharedValidator.RuleFor(c => c.Password).NotEmpty().When(c => c.AuthenticationMethod != AuthenticationType.None);
SharedValidator.RuleFor(c => c.SslPort).ValidPort().When(c => c.EnableSsl);
SharedValidator.RuleFor(c => c.SslCertPath).NotEmpty().When(c => c.EnableSsl);
SharedValidator.RuleFor(c => c.Branch).NotEmpty().WithMessage("Branch name is required, 'master' is the default");
SharedValidator.RuleFor(c => c.UpdateScriptPath).IsValidPath().When(c => c.UpdateMechanism == UpdateMechanism.Script);
SharedValidator.RuleFor(c => c.BackupFolder).IsValidPath().When(c => Path.IsPathRooted(c.BackupFolder));
SharedValidator.RuleFor(c => c.BackupInterval).InclusiveBetween(1, 7);
SharedValidator.RuleFor(c => c.BackupRetention).InclusiveBetween(1, 90);
}
private HostConfigResource GetHostConfig()
{
var resource = _configFileProvider.ToResource(_configService);
resource.Id = 1;
var user = _userService.FindUser();
if (user != null)
{
resource.Username = user.Username;
resource.Password = user.Password;
}
return resource;
}
private HostConfigResource GetHostConfig(int id)
{
return GetHostConfig();
}
private void SaveHostConfig(HostConfigResource resource)
{
var dictionary = resource.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(resource, null));
_configFileProvider.SaveConfigDictionary(dictionary);
_configService.SaveConfigDictionary(dictionary);
if (resource.Username.IsNotNullOrWhiteSpace() && resource.Password.IsNotNullOrWhiteSpace())
{
_userService.Upsert(resource.Username, resource.Password);
}
}
}
}

View File

@ -1,84 +0,0 @@
using NzbDrone.Common.Http.Proxy;
using NzbDrone.Core.Authentication;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Update;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class HostConfigResource : RestResource
{
public string BindAddress { get; set; }
public int Port { get; set; }
public int SslPort { get; set; }
public bool EnableSsl { get; set; }
public bool LaunchBrowser { get; set; }
public AuthenticationType AuthenticationMethod { get; set; }
public bool AnalyticsEnabled { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string LogLevel { get; set; }
public string ConsoleLogLevel { get; set; }
public string Branch { get; set; }
public string ApiKey { get; set; }
public string SslCertPath { get; set; }
public string SslCertPassword { get; set; }
public string UrlBase { get; set; }
public bool UpdateAutomatically { get; set; }
public UpdateMechanism UpdateMechanism { get; set; }
public string UpdateScriptPath { get; set; }
public bool ProxyEnabled { get; set; }
public ProxyType ProxyType { get; set; }
public string ProxyHostname { get; set; }
public int ProxyPort { get; set; }
public string ProxyUsername { get; set; }
public string ProxyPassword { get; set; }
public string ProxyBypassFilter { get; set; }
public bool ProxyBypassLocalAddresses { get; set; }
public string BackupFolder { get; set; }
public int BackupInterval { get; set; }
public int BackupRetention { get; set; }
}
public static class HostConfigResourceMapper
{
public static HostConfigResource ToResource(this IConfigFileProvider model, IConfigService configService)
{
// TODO: Clean this mess up. don't mix data from multiple classes, use sub-resources instead?
return new HostConfigResource
{
BindAddress = model.BindAddress,
Port = model.Port,
SslPort = model.SslPort,
EnableSsl = model.EnableSsl,
LaunchBrowser = model.LaunchBrowser,
AuthenticationMethod = model.AuthenticationMethod,
AnalyticsEnabled = model.AnalyticsEnabled,
//Username
//Password
LogLevel = model.LogLevel,
ConsoleLogLevel = model.ConsoleLogLevel,
Branch = model.Branch,
ApiKey = model.ApiKey,
SslCertPath = model.SslCertPath,
SslCertPassword = model.SslCertPassword,
UrlBase = model.UrlBase,
UpdateAutomatically = model.UpdateAutomatically,
UpdateMechanism = model.UpdateMechanism,
UpdateScriptPath = model.UpdateScriptPath,
ProxyEnabled = configService.ProxyEnabled,
ProxyType = configService.ProxyType,
ProxyHostname = configService.ProxyHostname,
ProxyPort = configService.ProxyPort,
ProxyUsername = configService.ProxyUsername,
ProxyPassword = configService.ProxyPassword,
ProxyBypassFilter = configService.ProxyBypassFilter,
ProxyBypassLocalAddresses = configService.ProxyBypassLocalAddresses,
BackupFolder = configService.BackupFolder,
BackupInterval = configService.BackupInterval,
BackupRetention = configService.BackupRetention
};
}
}
}

View File

@ -1,30 +0,0 @@
using FluentValidation;
using NzbDrone.Core.Configuration;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Config
{
public class IndexerConfigModule : NzbDroneConfigModule<IndexerConfigResource>
{
public IndexerConfigModule(IConfigService configService)
: base(configService)
{
SharedValidator.RuleFor(c => c.MinimumAge)
.GreaterThanOrEqualTo(0);
SharedValidator.RuleFor(c => c.MaximumSize)
.GreaterThanOrEqualTo(0);
SharedValidator.RuleFor(c => c.Retention)
.GreaterThanOrEqualTo(0);
SharedValidator.RuleFor(c => c.RssSyncInterval)
.IsValidRssSyncInterval();
}
protected override IndexerConfigResource ToResource(IConfigService model)
{
return IndexerConfigResourceMapper.ToResource(model);
}
}
}

View File

@ -1,35 +0,0 @@
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class IndexerConfigResource : RestResource
{
public int MinimumAge { get; set; }
public int MaximumSize { get; set; }
public int Retention { get; set; }
public int RssSyncInterval { get; set; }
public bool PreferIndexerFlags { get; set; }
public int AvailabilityDelay { get; set; }
public bool AllowHardcodedSubs { get; set; }
public string WhitelistedHardcodedSubs { get; set; }
}
public static class IndexerConfigResourceMapper
{
public static IndexerConfigResource ToResource(IConfigService model)
{
return new IndexerConfigResource
{
MinimumAge = model.MinimumAge,
MaximumSize = model.MaximumSize,
Retention = model.Retention,
RssSyncInterval = model.RssSyncInterval,
PreferIndexerFlags = model.PreferIndexerFlags,
AvailabilityDelay = model.AvailabilityDelay,
AllowHardcodedSubs = model.AllowHardcodedSubs,
WhitelistedHardcodedSubs = model.WhitelistedHardcodedSubs,
};
}
}
}

View File

@ -1,39 +0,0 @@
using FluentValidation;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Validation;
using NzbDrone.Core.Validation.Paths;
namespace NzbDrone.Api.Config
{
public class MediaManagementConfigModule : NzbDroneConfigModule<MediaManagementConfigResource>
{
public MediaManagementConfigModule(IConfigService configService,
PathExistsValidator pathExistsValidator,
FolderChmodValidator folderChmodValidator,
FolderWritableValidator folderWritableValidator,
MoviePathValidator moviePathValidator,
StartupFolderValidator startupFolderValidator,
SystemFolderValidator systemFolderValidator,
RootFolderAncestorValidator rootFolderAncestorValidator,
RootFolderValidator rootFolderValidator)
: base(configService)
{
SharedValidator.RuleFor(c => c.ChmodFolder).SetValidator(folderChmodValidator).When(c => !string.IsNullOrEmpty(c.ChmodFolder) && PlatformInfo.IsMono);
SharedValidator.RuleFor(c => c.RecycleBin).IsValidPath()
.SetValidator(folderWritableValidator)
.SetValidator(rootFolderValidator)
.SetValidator(pathExistsValidator)
.SetValidator(moviePathValidator)
.SetValidator(rootFolderAncestorValidator)
.SetValidator(startupFolderValidator)
.SetValidator(systemFolderValidator)
.When(c => !string.IsNullOrWhiteSpace(c.RecycleBin));
}
protected override MediaManagementConfigResource ToResource(IConfigService model)
{
return MediaManagementConfigResourceMapper.ToResource(model);
}
}
}

View File

@ -1,54 +0,0 @@
using NzbDrone.Core.Configuration;
using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class MediaManagementConfigResource : RestResource
{
public bool AutoUnmonitorPreviouslyDownloadedEpisodes { get; set; }
public string RecycleBin { get; set; }
public ProperDownloadTypes DownloadPropersAndRepacks { get; set; }
public bool CreateEmptySeriesFolders { get; set; }
public FileDateType FileDate { get; set; }
public bool AutoRenameFolders { get; set; }
public bool PathsDefaultStatic { get; set; }
public bool SetPermissionsLinux { get; set; }
public string ChmodFolder { get; set; }
public string ChownGroup { get; set; }
public bool SkipFreeSpaceCheckWhenImporting { get; set; }
public bool CopyUsingHardlinks { get; set; }
public bool ImportExtraFiles { get; set; }
public string ExtraFileExtensions { get; set; }
public bool EnableMediaInfo { get; set; }
}
public static class MediaManagementConfigResourceMapper
{
public static MediaManagementConfigResource ToResource(IConfigService model)
{
return new MediaManagementConfigResource
{
AutoUnmonitorPreviouslyDownloadedEpisodes = model.AutoUnmonitorPreviouslyDownloadedMovies,
RecycleBin = model.RecycleBin,
DownloadPropersAndRepacks = model.DownloadPropersAndRepacks,
CreateEmptySeriesFolders = model.CreateEmptyMovieFolders,
FileDate = model.FileDate,
AutoRenameFolders = model.AutoRenameFolders,
SetPermissionsLinux = model.SetPermissionsLinux,
ChmodFolder = model.ChmodFolder,
ChownGroup = model.ChownGroup,
SkipFreeSpaceCheckWhenImporting = model.SkipFreeSpaceCheckWhenImporting,
CopyUsingHardlinks = model.CopyUsingHardlinks,
ImportExtraFiles = model.ImportExtraFiles,
ExtraFileExtensions = model.ExtraFileExtensions,
EnableMediaInfo = model.EnableMediaInfo
};
}
}
}

View File

@ -1,99 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using FluentValidation.Results;
using Nancy.ModelBinding;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Organizer;
using Radarr.Http;
namespace NzbDrone.Api.Config
{
public class NamingConfigModule : RadarrRestModule<NamingConfigResource>
{
private readonly INamingConfigService _namingConfigService;
private readonly IFilenameSampleService _filenameSampleService;
private readonly IFilenameValidationService _filenameValidationService;
private readonly IBuildFileNames _filenameBuilder;
public NamingConfigModule(INamingConfigService namingConfigService,
IFilenameSampleService filenameSampleService,
IFilenameValidationService filenameValidationService,
IBuildFileNames filenameBuilder)
: base("config/naming")
{
_namingConfigService = namingConfigService;
_filenameSampleService = filenameSampleService;
_filenameValidationService = filenameValidationService;
_filenameBuilder = filenameBuilder;
GetResourceSingle = GetNamingConfig;
GetResourceById = GetNamingConfig;
UpdateResource = UpdateNamingConfig;
Get("/samples", x => GetExamples(this.Bind<NamingConfigResource>()));
SharedValidator.RuleFor(c => c.MultiEpisodeStyle).InclusiveBetween(0, 5);
SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat();
SharedValidator.RuleFor(c => c.MovieFolderFormat).ValidMovieFolderFormat();
}
private void UpdateNamingConfig(NamingConfigResource resource)
{
var nameSpec = resource.ToModel();
ValidateFormatResult(nameSpec);
_namingConfigService.Save(nameSpec);
}
private NamingConfigResource GetNamingConfig()
{
var nameSpec = _namingConfigService.GetConfig();
var resource = nameSpec.ToResource();
if (resource.StandardMovieFormat.IsNotNullOrWhiteSpace())
{
var basicConfig = _filenameBuilder.GetBasicNamingConfig(nameSpec);
basicConfig.AddToResource(resource);
}
return resource;
}
private NamingConfigResource GetNamingConfig(int id)
{
return GetNamingConfig();
}
private object GetExamples(NamingConfigResource config)
{
var nameSpec = config.ToModel();
var sampleResource = new NamingSampleResource();
var movieSampleResult = _filenameSampleService.GetMovieSample(nameSpec);
sampleResource.MovieExample = nameSpec.StandardMovieFormat.IsNullOrWhiteSpace()
? "Invalid Format"
: movieSampleResult.FileName;
sampleResource.MovieFolderExample = nameSpec.MovieFolderFormat.IsNullOrWhiteSpace()
? "Invalid format"
: _filenameSampleService.GetMovieFolderSample(nameSpec);
return sampleResource;
}
private void ValidateFormatResult(NamingConfig nameSpec)
{
var movieSampleResult = _filenameSampleService.GetMovieSample(nameSpec);
//var standardMovieValidationResult = _filenameValidationService.ValidateMovieFilename(movieSampleResult); For now, let's hope the user is not stupid enough :/
var validationFailures = new List<ValidationFailure>();
//validationFailures.AddIfNotNull(standardMovieValidationResult);
if (validationFailures.Any())
{
throw new ValidationException(validationFailures.DistinctBy(v => v.PropertyName).ToArray());
}
}
}
}

View File

@ -1,70 +0,0 @@
using NzbDrone.Core.Organizer;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class NamingConfigResource : RestResource
{
public bool RenameEpisodes { get; set; }
public bool ReplaceIllegalCharacters { get; set; }
public ColonReplacementFormat ColonReplacementFormat { get; set; }
public string StandardMovieFormat { get; set; }
public string MovieFolderFormat { get; set; }
public int MultiEpisodeStyle { get; set; }
public bool IncludeSeriesTitle { get; set; }
public bool IncludeEpisodeTitle { get; set; }
public bool IncludeQuality { get; set; }
public bool ReplaceSpaces { get; set; }
public string Separator { get; set; }
public string NumberStyle { get; set; }
}
public static class NamingConfigResourceMapper
{
public static NamingConfigResource ToResource(this NamingConfig model)
{
return new NamingConfigResource
{
Id = model.Id,
RenameEpisodes = model.RenameMovies,
ReplaceIllegalCharacters = model.ReplaceIllegalCharacters,
ColonReplacementFormat = model.ColonReplacementFormat,
MultiEpisodeStyle = model.MultiEpisodeStyle,
StandardMovieFormat = model.StandardMovieFormat,
MovieFolderFormat = model.MovieFolderFormat
//IncludeSeriesTitle
//IncludeEpisodeTitle
//IncludeQuality
//ReplaceSpaces
//Separator
//NumberStyle
};
}
public static void AddToResource(this BasicNamingConfig basicNamingConfig, NamingConfigResource resource)
{
resource.IncludeSeriesTitle = basicNamingConfig.IncludeSeriesTitle;
resource.IncludeEpisodeTitle = basicNamingConfig.IncludeEpisodeTitle;
resource.IncludeQuality = basicNamingConfig.IncludeQuality;
resource.ReplaceSpaces = basicNamingConfig.ReplaceSpaces;
resource.Separator = basicNamingConfig.Separator;
resource.NumberStyle = basicNamingConfig.NumberStyle;
}
public static NamingConfig ToModel(this NamingConfigResource resource)
{
return new NamingConfig
{
Id = resource.Id,
RenameMovies = resource.RenameEpisodes,
ReplaceIllegalCharacters = resource.ReplaceIllegalCharacters,
ColonReplacementFormat = resource.ColonReplacementFormat,
StandardMovieFormat = resource.StandardMovieFormat,
MovieFolderFormat = resource.MovieFolderFormat
};
}
}
}

View File

@ -1,16 +0,0 @@
namespace NzbDrone.Api.Config
{
public class NamingSampleResource
{
public string SingleEpisodeExample { get; set; }
public string MultiEpisodeExample { get; set; }
public string DailyEpisodeExample { get; set; }
public string AnimeEpisodeExample { get; set; }
public string AnimeMultiEpisodeExample { get; set; }
public string SeriesFolderExample { get; set; }
public string SeasonFolderExample { get; set; }
public string MovieExample { get; set; }
public string MovieFolderExample { get; set; }
}
}

View File

@ -1,20 +0,0 @@
using NzbDrone.Core.Configuration;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Config
{
public class NetImportConfigModule : NzbDroneConfigModule<NetImportConfigResource>
{
public NetImportConfigModule(IConfigService configService)
: base(configService)
{
SharedValidator.RuleFor(c => c.ImportListSyncInterval)
.IsValidImportListSyncInterval();
}
protected override NetImportConfigResource ToResource(IConfigService model)
{
return NetImportConfigResourceMapper.ToResource(model);
}
}
}

View File

@ -1,25 +0,0 @@
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class NetImportConfigResource : RestResource
{
public int ImportListSyncInterval { get; set; }
public string ListSyncLevel { get; set; }
public string ImportExclusions { get; set; }
}
public static class NetImportConfigResourceMapper
{
public static NetImportConfigResource ToResource(IConfigService model)
{
return new NetImportConfigResource
{
ImportListSyncInterval = model.ImportListSyncInterval,
ListSyncLevel = model.ListSyncLevel,
ImportExclusions = model.ImportExclusions,
};
}
}
}

View File

@ -1,53 +0,0 @@
using System.Linq;
using System.Reflection;
using NzbDrone.Core.Configuration;
using Radarr.Http;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public abstract class NzbDroneConfigModule<TResource> : RadarrRestModule<TResource>
where TResource : RestResource, new()
{
private readonly IConfigService _configService;
protected NzbDroneConfigModule(IConfigService configService)
: this(new TResource().ResourceName.Replace("config", ""), configService)
{
}
protected NzbDroneConfigModule(string resource, IConfigService configService)
: base("config/" + resource.Trim('/'))
{
_configService = configService;
GetResourceSingle = GetConfig;
GetResourceById = GetConfig;
UpdateResource = SaveConfig;
}
private TResource GetConfig()
{
var resource = ToResource(_configService);
resource.Id = 1;
return resource;
}
protected abstract TResource ToResource(IConfigService model);
private TResource GetConfig(int id)
{
return GetConfig();
}
private void SaveConfig(TResource resource)
{
var dictionary = resource.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(resource, null));
_configService.SaveConfigDictionary(dictionary);
}
}
}

View File

@ -1,17 +0,0 @@
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Config
{
public class UiConfigModule : NzbDroneConfigModule<UiConfigResource>
{
public UiConfigModule(IConfigService configService)
: base(configService)
{
}
protected override UiConfigResource ToResource(IConfigService model)
{
return UiConfigResourceMapper.ToResource(model);
}
}
}

View File

@ -1,39 +0,0 @@
using NzbDrone.Core.Configuration;
using Radarr.Http.REST;
namespace NzbDrone.Api.Config
{
public class UiConfigResource : RestResource
{
//Calendar
public int FirstDayOfWeek { get; set; }
public string CalendarWeekColumnHeader { get; set; }
//Dates
public string ShortDateFormat { get; set; }
public string LongDateFormat { get; set; }
public string TimeFormat { get; set; }
public bool ShowRelativeDates { get; set; }
public bool EnableColorImpairedMode { get; set; }
}
public static class UiConfigResourceMapper
{
public static UiConfigResource ToResource(IConfigService model)
{
return new UiConfigResource
{
FirstDayOfWeek = model.FirstDayOfWeek,
CalendarWeekColumnHeader = model.CalendarWeekColumnHeader,
ShortDateFormat = model.ShortDateFormat,
LongDateFormat = model.LongDateFormat,
TimeFormat = model.TimeFormat,
ShowRelativeDates = model.ShowRelativeDates,
EnableColorImpairedMode = model.EnableColorImpairedMode,
};
}
}
}

View File

@ -1,67 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NzbDrone.Core.CustomFormats;
using Radarr.Http;
namespace NzbDrone.Api.CustomFormats
{
public class CustomFormatModule : RadarrRestModule<CustomFormatResource>
{
private readonly ICustomFormatService _formatService;
public CustomFormatModule(ICustomFormatService formatService)
{
_formatService = formatService;
SharedValidator.RuleFor(c => c.Name).NotEmpty();
SharedValidator.RuleFor(c => c.Name)
.Must((v, c) => !_formatService.All().Any(f => f.Name == c && f.Id != v.Id)).WithMessage("Must be unique.");
SharedValidator.RuleFor(c => c.Specifications).NotEmpty();
GetResourceAll = GetAll;
GetResourceById = GetById;
UpdateResource = Update;
CreateResource = Create;
DeleteResource = DeleteFormat;
Get("schema", x => GetTemplates());
}
private int Create(CustomFormatResource customFormatResource)
{
var model = customFormatResource.ToModel();
return _formatService.Insert(model).Id;
}
private void Update(CustomFormatResource resource)
{
var model = resource.ToModel();
_formatService.Update(model);
}
private CustomFormatResource GetById(int id)
{
return _formatService.GetById(id).ToResource();
}
private List<CustomFormatResource> GetAll()
{
return _formatService.All().ToResource();
}
private void DeleteFormat(int id)
{
_formatService.Delete(id);
}
private object GetTemplates()
{
return null;
}
}
}

View File

@ -1,42 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.CustomFormats;
using Radarr.Http.REST;
namespace NzbDrone.Api.CustomFormats
{
public class CustomFormatResource : RestResource
{
public string Name { get; set; }
public List<ICustomFormatSpecification> Specifications { get; set; }
public string Simplicity { get; set; }
}
public static class CustomFormatResourceMapper
{
public static CustomFormatResource ToResource(this CustomFormat model)
{
return new CustomFormatResource
{
Id = model.Id,
Name = model.Name,
Specifications = model.Specifications.ToList(),
};
}
public static List<CustomFormatResource> ToResource(this IEnumerable<CustomFormat> models)
{
return models.Select(m => m.ToResource()).ToList();
}
public static CustomFormat ToModel(this CustomFormatResource resource)
{
return new CustomFormat
{
Id = resource.Id,
Name = resource.Name,
Specifications = resource.Specifications.ToList(),
};
}
}
}

View File

@ -1,23 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.DiskSpace;
using Radarr.Http;
namespace NzbDrone.Api.DiskSpace
{
public class DiskSpaceModule : RadarrRestModule<DiskSpaceResource>
{
private readonly IDiskSpaceService _diskSpaceService;
public DiskSpaceModule(IDiskSpaceService diskSpaceService)
: base("diskspace")
{
_diskSpaceService = diskSpaceService;
GetResourceAll = GetFreeSpace;
}
public List<DiskSpaceResource> GetFreeSpace()
{
return _diskSpaceService.GetFreeSpace().ConvertAll(DiskSpaceResourceMapper.MapToResource);
}
}
}

View File

@ -1,31 +0,0 @@
using Radarr.Http.REST;
namespace NzbDrone.Api.DiskSpace
{
public class DiskSpaceResource : RestResource
{
public string Path { get; set; }
public string Label { get; set; }
public long FreeSpace { get; set; }
public long TotalSpace { get; set; }
}
public static class DiskSpaceResourceMapper
{
public static DiskSpaceResource MapToResource(this Core.DiskSpace.DiskSpace model)
{
if (model == null)
{
return null;
}
return new DiskSpaceResource
{
Path = model.Path,
Label = model.Label,
FreeSpace = model.FreeSpace,
TotalSpace = model.TotalSpace
};
}
}
}

View File

@ -1,40 +0,0 @@
using NzbDrone.Core.Download;
namespace NzbDrone.Api.DownloadClient
{
public class DownloadClientModule : ProviderModuleBase<DownloadClientResource, IDownloadClient, DownloadClientDefinition>
{
public DownloadClientModule(IDownloadClientFactory downloadClientFactory)
: base(downloadClientFactory, "downloadclient")
{
}
protected override void MapToResource(DownloadClientResource resource, DownloadClientDefinition definition)
{
base.MapToResource(resource, definition);
resource.Enable = definition.Enable;
resource.Protocol = definition.Protocol;
resource.Priority = definition.Priority;
}
protected override void MapToModel(DownloadClientDefinition definition, DownloadClientResource resource)
{
base.MapToModel(definition, resource);
definition.Enable = resource.Enable;
definition.Protocol = resource.Protocol;
definition.Priority = resource.Priority;
}
protected override void Validate(DownloadClientDefinition definition, bool includeWarnings)
{
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}
}

View File

@ -1,11 +0,0 @@
using NzbDrone.Core.Indexers;
namespace NzbDrone.Api.DownloadClient
{
public class DownloadClientResource : ProviderResource<DownloadClientResource>
{
public bool Enable { get; set; }
public DownloadProtocol Protocol { get; set; }
public int Priority { get; set; }
}
}

View File

@ -1,46 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.Extras.Files;
using NzbDrone.Core.Extras.Metadata.Files;
using NzbDrone.Core.Extras.Others;
using NzbDrone.Core.Extras.Subtitles;
using Radarr.Http;
using Radarr.Http.REST;
namespace NzbDrone.Api.ExtraFiles
{
public class ExtraFileModule : RadarrRestModule<ExtraFileResource>
{
private readonly IExtraFileService<SubtitleFile> _subtitleFileService;
private readonly IExtraFileService<MetadataFile> _metadataFileService;
private readonly IExtraFileService<OtherExtraFile> _otherFileService;
public ExtraFileModule(IExtraFileService<SubtitleFile> subtitleFileService, IExtraFileService<MetadataFile> metadataFileService, IExtraFileService<OtherExtraFile> otherExtraFileService)
: base("/extrafile")
{
_subtitleFileService = subtitleFileService;
_metadataFileService = metadataFileService;
_otherFileService = otherExtraFileService;
GetResourceAll = GetFiles;
}
private List<ExtraFileResource> GetFiles()
{
if (!Request.Query.MovieId.HasValue)
{
throw new BadRequestException("MovieId is missing");
}
var extraFiles = new List<ExtraFileResource>();
List<SubtitleFile> subtitleFiles = _subtitleFileService.GetFilesByMovie(Request.Query.MovieId);
List<MetadataFile> metadataFiles = _metadataFileService.GetFilesByMovie(Request.Query.MovieId);
List<OtherExtraFile> otherExtraFiles = _otherFileService.GetFilesByMovie(Request.Query.MovieId);
extraFiles.AddRange(subtitleFiles.ToResource());
extraFiles.AddRange(metadataFiles.ToResource());
extraFiles.AddRange(otherExtraFiles.ToResource());
return extraFiles;
}
}
}

View File

@ -1,91 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Extras.Files;
using NzbDrone.Core.Extras.Metadata.Files;
using NzbDrone.Core.Extras.Others;
using NzbDrone.Core.Extras.Subtitles;
using Radarr.Http.REST;
namespace NzbDrone.Api.ExtraFiles
{
public class ExtraFileResource : RestResource
{
public int MovieId { get; set; }
public int? MovieFileId { get; set; }
public string RelativePath { get; set; }
public string Extension { get; set; }
public ExtraFileType Type { get; set; }
}
public static class ExtraFileResourceMapper
{
public static ExtraFileResource ToResource(this MetadataFile model)
{
if (model == null)
{
return null;
}
return new ExtraFileResource
{
Id = model.Id,
MovieId = model.MovieId,
MovieFileId = model.MovieFileId,
RelativePath = model.RelativePath,
Extension = model.Extension,
Type = ExtraFileType.Metadata
};
}
public static ExtraFileResource ToResource(this SubtitleFile model)
{
if (model == null)
{
return null;
}
return new ExtraFileResource
{
Id = model.Id,
MovieId = model.MovieId,
MovieFileId = model.MovieFileId,
RelativePath = model.RelativePath,
Extension = model.Extension,
Type = ExtraFileType.Subtitle
};
}
public static ExtraFileResource ToResource(this OtherExtraFile model)
{
if (model == null)
{
return null;
}
return new ExtraFileResource
{
Id = model.Id,
MovieId = model.MovieId,
MovieFileId = model.MovieFileId,
RelativePath = model.RelativePath,
Extension = model.Extension,
Type = ExtraFileType.Other
};
}
public static List<ExtraFileResource> ToResource(this IEnumerable<SubtitleFile> movies)
{
return movies.Select(ToResource).ToList();
}
public static List<ExtraFileResource> ToResource(this IEnumerable<MetadataFile> movies)
{
return movies.Select(ToResource).ToList();
}
public static List<ExtraFileResource> ToResource(this IEnumerable<OtherExtraFile> movies)
{
return movies.Select(ToResource).ToList();
}
}
}

View File

@ -1,72 +0,0 @@
using System;
using System.IO;
using System.Linq;
using Nancy;
using NzbDrone.Common.Disk;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.MediaFiles;
using Radarr.Http.Extensions;
namespace NzbDrone.Api.FileSystem
{
public class FileSystemModule : NzbDroneApiModule
{
private readonly IFileSystemLookupService _fileSystemLookupService;
private readonly IDiskProvider _diskProvider;
private readonly IDiskScanService _diskScanService;
public FileSystemModule(IFileSystemLookupService fileSystemLookupService,
IDiskProvider diskProvider,
IDiskScanService diskScanService)
: base("/filesystem")
{
_fileSystemLookupService = fileSystemLookupService;
_diskProvider = diskProvider;
_diskScanService = diskScanService;
Get("/", x => GetContents());
Get("/type", x => GetEntityType());
Get("/mediafiles", x => GetMediaFiles());
}
private object GetContents()
{
var pathQuery = Request.Query.path;
var includeFiles = Request.GetBooleanQueryParameter("includeFiles");
var allowFoldersWithoutTrailingSlashes = Request.GetBooleanQueryParameter("allowFoldersWithoutTrailingSlashes");
return _fileSystemLookupService.LookupContents((string)pathQuery.Value, includeFiles, allowFoldersWithoutTrailingSlashes);
}
private object GetEntityType()
{
var pathQuery = Request.Query.path;
var path = (string)pathQuery.Value;
if (_diskProvider.FileExists(path))
{
return new { type = "file" };
}
//Return folder even if it doesn't exist on disk to avoid leaking anything from the UI about the underlying system
return new { type = "folder" };
}
private object GetMediaFiles()
{
var pathQuery = Request.Query.path;
var path = (string)pathQuery.Value;
if (!_diskProvider.FolderExists(path))
{
return Array.Empty<string>();
}
return _diskScanService.GetVideoFiles(path).Select(f => new
{
Path = f,
RelativePath = path.GetRelativePath(f),
Name = Path.GetFileName(f)
});
}
}
}

View File

@ -1,32 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.HealthCheck;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.Health
{
public class HealthModule : RadarrRestModuleWithSignalR<HealthResource, HealthCheck>,
IHandle<HealthCheckCompleteEvent>
{
private readonly IHealthCheckService _healthCheckService;
public HealthModule(IBroadcastSignalRMessage signalRBroadcaster, IHealthCheckService healthCheckService)
: base(signalRBroadcaster)
{
_healthCheckService = healthCheckService;
GetResourceAll = GetHealth;
}
private List<HealthResource> GetHealth()
{
return _healthCheckService.Results().ToResource();
}
public void Handle(HealthCheckCompleteEvent message)
{
BroadcastResourceChange(ModelAction.Sync);
}
}
}

View File

@ -1,40 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Common.Http;
using NzbDrone.Core.HealthCheck;
using Radarr.Http.REST;
namespace NzbDrone.Api.Health
{
public class HealthResource : RestResource
{
public HealthCheckResult Type { get; set; }
public string Message { get; set; }
public HttpUri WikiUrl { get; set; }
}
public static class HealthResourceMapper
{
public static HealthResource ToResource(this HealthCheck model)
{
if (model == null)
{
return null;
}
return new HealthResource
{
Id = model.Id,
Type = model.Type,
Message = model.Message,
WikiUrl = model.WikiUrl
};
}
public static List<HealthResource> ToResource(this IEnumerable<HealthCheck> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,72 +0,0 @@
using System;
using System.Linq;
using Nancy;
using NzbDrone.Api.Movies;
using NzbDrone.Core.Datastore;
using NzbDrone.Core.DecisionEngine.Specifications;
using NzbDrone.Core.Download;
using NzbDrone.Core.History;
using Radarr.Http;
namespace NzbDrone.Api.History
{
public class HistoryModule : RadarrRestModule<HistoryResource>
{
private readonly IHistoryService _historyService;
private readonly IUpgradableSpecification _qualityUpgradableSpecification;
private readonly IFailedDownloadService _failedDownloadService;
public HistoryModule(IHistoryService historyService,
IUpgradableSpecification qualityUpgradableSpecification,
IFailedDownloadService failedDownloadService)
{
_historyService = historyService;
_qualityUpgradableSpecification = qualityUpgradableSpecification;
_failedDownloadService = failedDownloadService;
GetResourcePaged = GetHistory;
Post("/failed", x => MarkAsFailed());
}
protected HistoryResource MapToResource(MovieHistory model)
{
var resource = model.ToResource();
resource.Movie = model.Movie.ToResource();
if (model.Movie != null)
{
resource.QualityCutoffNotMet = _qualityUpgradableSpecification.QualityCutoffNotMet(model.Movie.Profile, model.Quality);
}
return resource;
}
private PagingResource<HistoryResource> GetHistory(PagingResource<HistoryResource> pagingResource)
{
var movieId = Request.Query.MovieId;
var pagingSpec = pagingResource.MapToPagingSpec<HistoryResource, MovieHistory>("date", SortDirection.Descending);
var filter = pagingResource.Filters.FirstOrDefault();
if (filter != null && filter.Key == "eventType")
{
var filterValue = (MovieHistoryEventType)Convert.ToInt32(filter.Value);
pagingSpec.FilterExpressions.Add(v => v.EventType == filterValue);
}
if (movieId.HasValue)
{
int i = (int)movieId;
pagingSpec.FilterExpressions.Add(h => h.MovieId == i);
}
return ApplyToPage(_historyService.Paged, pagingSpec, MapToResource);
}
private object MarkAsFailed()
{
var id = (int)Request.Form.Id;
_failedDownloadService.MarkAsFailed(id);
return new object();
}
}
}

View File

@ -1,51 +0,0 @@
using System;
using System.Collections.Generic;
using NzbDrone.Api.Movies;
using NzbDrone.Core.History;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.History
{
public class HistoryResource : RestResource
{
public int MovieId { get; set; }
public string SourceTitle { get; set; }
public QualityModel Quality { get; set; }
public bool QualityCutoffNotMet { get; set; }
public DateTime Date { get; set; }
public string DownloadId { get; set; }
public MovieHistoryEventType EventType { get; set; }
public Dictionary<string, string> Data { get; set; }
public MovieResource Movie { get; set; }
}
public static class HistoryResourceMapper
{
public static HistoryResource ToResource(this MovieHistory model)
{
if (model == null)
{
return null;
}
return new HistoryResource
{
Id = model.Id,
MovieId = model.MovieId,
SourceTitle = model.SourceTitle,
Quality = model.Quality,
//QualityCutoffNotMet
Date = model.Date,
DownloadId = model.DownloadId,
EventType = model.EventType,
Data = model.Data
};
}
}
}

View File

@ -1,44 +0,0 @@
using NzbDrone.Core.Indexers;
namespace NzbDrone.Api.Indexers
{
public class IndexerModule : ProviderModuleBase<IndexerResource, IIndexer, IndexerDefinition>
{
public IndexerModule(IndexerFactory indexerFactory)
: base(indexerFactory, "indexer")
{
}
protected override void MapToResource(IndexerResource resource, IndexerDefinition definition)
{
base.MapToResource(resource, definition);
resource.EnableRss = definition.EnableRss;
resource.EnableSearch = definition.EnableAutomaticSearch || definition.EnableInteractiveSearch;
resource.SupportsRss = definition.SupportsRss;
resource.SupportsSearch = definition.SupportsSearch;
resource.Protocol = definition.Protocol;
resource.Priority = definition.Priority;
}
protected override void MapToModel(IndexerDefinition definition, IndexerResource resource)
{
base.MapToModel(definition, resource);
definition.EnableRss = resource.EnableRss;
definition.EnableAutomaticSearch = resource.EnableSearch;
definition.EnableInteractiveSearch = resource.EnableSearch;
definition.Priority = resource.Priority;
}
protected override void Validate(IndexerDefinition definition, bool includeWarnings)
{
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}
}

View File

@ -1,14 +0,0 @@
using NzbDrone.Core.Indexers;
namespace NzbDrone.Api.Indexers
{
public class IndexerResource : ProviderResource<IndexerResource>
{
public bool EnableRss { get; set; }
public bool EnableSearch { get; set; }
public bool SupportsRss { get; set; }
public bool SupportsSearch { get; set; }
public DownloadProtocol Protocol { get; set; }
public int Priority { get; set; }
}
}

View File

@ -1,124 +0,0 @@
using System;
using System.Collections.Generic;
using FluentValidation;
using Nancy;
using Nancy.ModelBinding;
using NLog;
using NzbDrone.Common.Cache;
using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Download;
using NzbDrone.Core.Exceptions;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.IndexerSearch;
using NzbDrone.Core.Parser.Model;
using HttpStatusCode = System.Net.HttpStatusCode;
namespace NzbDrone.Api.Indexers
{
public class ReleaseModule : ReleaseModuleBase
{
private readonly IFetchAndParseRss _rssFetcherAndParser;
private readonly ISearchForNzb _nzbSearchService;
private readonly IMakeDownloadDecision _downloadDecisionMaker;
private readonly IPrioritizeDownloadDecision _prioritizeDownloadDecision;
private readonly IDownloadService _downloadService;
private readonly Logger _logger;
private readonly ICached<RemoteMovie> _remoteMovieCache;
public ReleaseModule(IFetchAndParseRss rssFetcherAndParser,
ISearchForNzb nzbSearchService,
IMakeDownloadDecision downloadDecisionMaker,
IPrioritizeDownloadDecision prioritizeDownloadDecision,
IDownloadService downloadService,
ICacheManager cacheManager,
Logger logger)
{
_rssFetcherAndParser = rssFetcherAndParser;
_nzbSearchService = nzbSearchService;
_downloadDecisionMaker = downloadDecisionMaker;
_prioritizeDownloadDecision = prioritizeDownloadDecision;
_downloadService = downloadService;
_logger = logger;
GetResourceAll = GetReleases;
Post("/", x => DownloadRelease(this.Bind<ReleaseResource>()));
//PostValidator.RuleFor(s => s.DownloadAllowed).Equal(true);
PostValidator.RuleFor(s => s.Guid).NotEmpty();
_remoteMovieCache = cacheManager.GetCache<RemoteMovie>(GetType(), "remoteMovies");
}
private object DownloadRelease(ReleaseResource release)
{
var remoteMovie = _remoteMovieCache.Find(release.Guid);
if (remoteMovie == null)
{
_logger.Debug("Couldn't find requested release in cache, cache timeout probably expired.");
return new NotFoundResponse();
}
try
{
_downloadService.DownloadReport(remoteMovie);
}
catch (ReleaseDownloadException ex)
{
_logger.Error(ex, ex.Message);
throw new NzbDroneClientException(HttpStatusCode.Conflict, "Getting release from indexer failed");
}
return release;
}
private List<ReleaseResource> GetReleases()
{
if (Request.Query.movieId != null)
{
return GetMovieReleases(Request.Query.movieId);
}
return GetRss();
}
private List<ReleaseResource> GetMovieReleases(int movieId)
{
try
{
var decisions = _nzbSearchService.MovieSearch(movieId, true, true);
var prioritizedDecisions = _prioritizeDownloadDecision.PrioritizeDecisionsForMovies(decisions);
return MapDecisions(prioritizedDecisions);
}
catch (NotImplementedException ex)
{
_logger.Error(ex, "One or more indexer you selected does not support movie search yet: " + ex.Message);
}
catch (Exception ex)
{
_logger.Error(ex, "Movie search failed: " + ex.Message);
}
return new List<ReleaseResource>();
}
private List<ReleaseResource> GetRss()
{
var reports = _rssFetcherAndParser.Fetch();
var decisions = _downloadDecisionMaker.GetRssDecision(reports);
var prioritizedDecisions = _prioritizeDownloadDecision.PrioritizeDecisionsForMovies(decisions);
return MapDecisions(prioritizedDecisions);
}
protected override ReleaseResource MapDecision(DownloadDecision decision, int initialWeight)
{
_remoteMovieCache.Set(decision.RemoteMovie.Release.Guid, decision.RemoteMovie, TimeSpan.FromMinutes(30));
return base.MapDecision(decision, initialWeight);
}
}
}

View File

@ -1,42 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.DecisionEngine;
using Radarr.Http;
namespace NzbDrone.Api.Indexers
{
public abstract class ReleaseModuleBase : RadarrRestModule<ReleaseResource>
{
protected virtual List<ReleaseResource> MapDecisions(IEnumerable<DownloadDecision> decisions)
{
var result = new List<ReleaseResource>();
foreach (var downloadDecision in decisions)
{
var release = MapDecision(downloadDecision, result.Count);
result.Add(release);
}
return result;
}
protected virtual ReleaseResource MapDecision(DownloadDecision decision, int initialWeight)
{
var release = decision.ToResource();
release.ReleaseWeight = initialWeight;
if (decision.RemoteMovie.Movie != null)
{
release.QualityWeight = decision.RemoteMovie.Movie
.Profile
.Items.FindIndex(v => v.Quality == release.Quality.Quality) * 100;
}
release.QualityWeight += release.Quality.Revision.Real * 10;
release.QualityWeight += release.Quality.Revision.Version;
return release;
}
}
}

View File

@ -1,90 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NLog;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Datastore;
using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Download;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Parser.Model;
namespace NzbDrone.Api.Indexers
{
public class ReleasePushModule : ReleaseModuleBase
{
private readonly IMakeDownloadDecision _downloadDecisionMaker;
private readonly IProcessDownloadDecisions _downloadDecisionProcessor;
private readonly IIndexerFactory _indexerFactory;
private readonly Logger _logger;
public ReleasePushModule(IMakeDownloadDecision downloadDecisionMaker,
IProcessDownloadDecisions downloadDecisionProcessor,
IIndexerFactory indexerFactory,
Logger logger)
{
_downloadDecisionMaker = downloadDecisionMaker;
_downloadDecisionProcessor = downloadDecisionProcessor;
_indexerFactory = indexerFactory;
_logger = logger;
Post("/push", x => ProcessRelease(ReadResourceFromRequest()));
PostValidator.RuleFor(s => s.Title).NotEmpty();
PostValidator.RuleFor(s => s.DownloadUrl).NotEmpty();
PostValidator.RuleFor(s => s.Protocol).NotEmpty();
PostValidator.RuleFor(s => s.PublishDate).NotEmpty();
}
private object ProcessRelease(ReleaseResource release)
{
_logger.Info("Release pushed: {0} - {1}", release.Title, release.DownloadUrl);
var info = release.ToModel();
info.Guid = "PUSH-" + info.DownloadUrl;
ResolveIndexer(info);
var decisions = _downloadDecisionMaker.GetRssDecision(new List<ReleaseInfo> { info });
_downloadDecisionProcessor.ProcessDecisions(decisions);
return MapDecisions(decisions).First();
}
private void ResolveIndexer(ReleaseInfo release)
{
if (release.IndexerId == 0 && release.Indexer.IsNotNullOrWhiteSpace())
{
var indexer = _indexerFactory.All().FirstOrDefault(v => v.Name == release.Indexer);
if (indexer != null)
{
release.IndexerId = indexer.Id;
_logger.Debug("Push Release {0} associated with indexer {1} - {2}.", release.Title, release.IndexerId, release.Indexer);
}
else
{
_logger.Debug("Push Release {0} not associated with unknown indexer {1}.", release.Title, release.Indexer);
}
}
else if (release.IndexerId != 0 && release.Indexer.IsNullOrWhiteSpace())
{
try
{
var indexer = _indexerFactory.Get(release.IndexerId);
release.Indexer = indexer.Name;
_logger.Debug("Push Release {0} associated with indexer {1} - {2}.", release.Title, release.IndexerId, release.Indexer);
}
catch (ModelNotFoundException)
{
_logger.Debug("Push Release {0} not associated with unknown indexer {0}.", release.Title, release.IndexerId);
release.IndexerId = 0;
}
}
else
{
_logger.Debug("Push Release {0} not associated with an indexer.", release.Title);
}
}
}
}

View File

@ -1,165 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Parser.Model;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Indexers
{
public class ReleaseResource : RestResource
{
public string Guid { get; set; }
public QualityModel Quality { get; set; }
public int QualityWeight { get; set; }
public int Age { get; set; }
public double AgeHours { get; set; }
public double AgeMinutes { get; set; }
public long Size { get; set; }
public int IndexerId { get; set; }
public string Indexer { get; set; }
public string ReleaseGroup { get; set; }
public string ReleaseHash { get; set; }
public string Edition { get; set; }
public string Title { get; set; }
public List<Language> Languages { get; set; }
public int Year { get; set; }
public string MovieTitle { get; set; }
public bool Approved { get; set; }
public bool TemporarilyRejected { get; set; }
public bool Rejected { get; set; }
public int TvdbId { get; set; }
public int TvRageId { get; set; }
public IEnumerable<string> Rejections { get; set; }
public DateTime PublishDate { get; set; }
public string CommentUrl { get; set; }
public string DownloadUrl { get; set; }
public string InfoUrl { get; set; }
public MappingResultType MappingResult { get; set; }
public int ReleaseWeight { get; set; }
public int SuspectedMovieId { get; set; }
public IEnumerable<string> IndexerFlags { get; set; }
public string MagnetUrl { get; set; }
public string InfoHash { get; set; }
public int? Seeders { get; set; }
public int? Leechers { get; set; }
public DownloadProtocol Protocol { get; set; }
// JsonIgnore so we don't serialize it, but can still parse it, removed in v3
[JsonIgnore]
public DownloadProtocol DownloadProtocol
{
get
{
return Protocol;
}
set
{
if (value > 0 && Protocol == 0)
{
Protocol = value;
}
}
}
public bool IsDaily { get; set; }
public bool IsAbsoluteNumbering { get; set; }
public bool IsPossibleSpecialEpisode { get; set; }
public bool Special { get; set; }
}
public static class ReleaseResourceMapper
{
public static ReleaseResource ToResource(this DownloadDecision model)
{
var releaseInfo = model.RemoteMovie.Release;
var remoteMovie = model.RemoteMovie;
var torrentInfo = (model.RemoteMovie.Release as TorrentInfo) ?? new TorrentInfo();
var mappingResult = MappingResultType.Success;
mappingResult = model.RemoteMovie.MappingResult;
var parsedMovieInfo = model.RemoteMovie.ParsedMovieInfo;
var movieId = model.RemoteMovie.Movie?.Id ?? 0; //Why not pull this out in frontend instead of passing another variable
return new ReleaseResource
{
Guid = releaseInfo.Guid,
Quality = parsedMovieInfo.Quality,
QualityWeight = parsedMovieInfo.Quality.Quality.Id, //Id kinda hacky for wheight, but what you gonna do? TODO: Fix this shit!
Age = releaseInfo.Age,
AgeHours = releaseInfo.AgeHours,
AgeMinutes = releaseInfo.AgeMinutes,
Size = releaseInfo.Size,
IndexerId = releaseInfo.IndexerId,
Indexer = releaseInfo.Indexer,
ReleaseGroup = parsedMovieInfo.ReleaseGroup,
ReleaseHash = parsedMovieInfo.ReleaseHash,
Title = releaseInfo.Title,
Languages = parsedMovieInfo.Languages,
Year = parsedMovieInfo.Year,
MovieTitle = parsedMovieInfo.MovieTitle,
Approved = model.Approved,
TemporarilyRejected = model.TemporarilyRejected,
Rejected = model.Rejected,
Rejections = model.Rejections.Select(r => r.Reason).ToList(),
PublishDate = releaseInfo.PublishDate,
CommentUrl = releaseInfo.CommentUrl,
DownloadUrl = releaseInfo.DownloadUrl,
InfoUrl = releaseInfo.InfoUrl,
MappingResult = mappingResult,
//ReleaseWeight
SuspectedMovieId = movieId,
MagnetUrl = torrentInfo.MagnetUrl,
InfoHash = torrentInfo.InfoHash,
Seeders = torrentInfo.Seeders,
Leechers = (torrentInfo.Peers.HasValue && torrentInfo.Seeders.HasValue) ? (torrentInfo.Peers.Value - torrentInfo.Seeders.Value) : (int?)null,
Protocol = releaseInfo.DownloadProtocol,
IndexerFlags = torrentInfo.IndexerFlags.ToString().Split(new string[] { ", " }, StringSplitOptions.None),
Edition = parsedMovieInfo.Edition,
//Special = parsedMovieInfo.Special,
};
}
public static ReleaseInfo ToModel(this ReleaseResource resource)
{
ReleaseInfo model;
if (resource.Protocol == DownloadProtocol.Torrent)
{
model = new TorrentInfo
{
MagnetUrl = resource.MagnetUrl,
InfoHash = resource.InfoHash,
Seeders = resource.Seeders,
Peers = (resource.Seeders.HasValue && resource.Leechers.HasValue) ? (resource.Seeders + resource.Leechers) : null
};
}
else
{
model = new ReleaseInfo();
}
model.Guid = resource.Guid;
model.Title = resource.Title;
model.Size = resource.Size;
model.DownloadUrl = resource.DownloadUrl;
model.InfoUrl = resource.InfoUrl;
model.CommentUrl = resource.CommentUrl;
model.IndexerId = resource.IndexerId;
model.Indexer = resource.Indexer;
model.DownloadProtocol = resource.DownloadProtocol;
model.PublishDate = resource.PublishDate;
return model;
}
}
}

View File

@ -1,36 +0,0 @@
using System.Collections.Generic;
using System.IO;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Logs
{
public class LogFileModule : LogFileModuleBase
{
private readonly IAppFolderInfo _appFolderInfo;
private readonly IDiskProvider _diskProvider;
public LogFileModule(IAppFolderInfo appFolderInfo,
IDiskProvider diskProvider,
IConfigFileProvider configFileProvider)
: base(diskProvider, configFileProvider, "")
{
_appFolderInfo = appFolderInfo;
_diskProvider = diskProvider;
}
protected override IEnumerable<string> GetLogFiles()
{
return _diskProvider.GetFiles(_appFolderInfo.GetLogFolder(), SearchOption.TopDirectoryOnly);
}
protected override string GetLogFilePath(string filename)
{
return Path.Combine(_appFolderInfo.GetLogFolder(), filename);
}
protected override string DownloadUrlRoot => "logfile";
}
}

View File

@ -1,77 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Nancy;
using Nancy.Responses;
using NLog;
using NzbDrone.Common.Disk;
using NzbDrone.Core.Configuration;
using Radarr.Http;
namespace NzbDrone.Api.Logs
{
public abstract class LogFileModuleBase : RadarrRestModule<LogFileResource>
{
protected const string LOGFILE_ROUTE = @"/(?<filename>[-.a-zA-Z0-9]+?\.txt)";
private readonly IDiskProvider _diskProvider;
private readonly IConfigFileProvider _configFileProvider;
public LogFileModuleBase(IDiskProvider diskProvider,
IConfigFileProvider configFileProvider,
string route)
: base("log/file" + route)
{
_diskProvider = diskProvider;
_configFileProvider = configFileProvider;
GetResourceAll = GetLogFilesResponse;
Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename));
}
private List<LogFileResource> GetLogFilesResponse()
{
var result = new List<LogFileResource>();
var files = GetLogFiles().ToList();
for (int i = 0; i < files.Count; i++)
{
var file = files[i];
var filename = Path.GetFileName(file);
result.Add(new LogFileResource
{
Id = i + 1,
Filename = filename,
LastWriteTime = _diskProvider.FileGetLastWrite(file),
ContentsUrl = string.Format("{0}/api/{1}/{2}", _configFileProvider.UrlBase, Resource, filename),
DownloadUrl = string.Format("{0}/{1}/{2}", _configFileProvider.UrlBase, DownloadUrlRoot, filename)
});
}
return result.OrderByDescending(l => l.LastWriteTime).ToList();
}
private object GetLogFileResponse(string filename)
{
LogManager.Flush();
var filePath = GetLogFilePath(filename);
if (!_diskProvider.FileExists(filePath))
{
return new NotFoundResponse();
}
var data = _diskProvider.ReadAllText(filePath);
return new TextResponse(data);
}
protected abstract IEnumerable<string> GetLogFiles();
protected abstract string GetLogFilePath(string filename);
protected abstract string DownloadUrlRoot { get; }
}
}

View File

@ -1,13 +0,0 @@
using System;
using Radarr.Http.REST;
namespace NzbDrone.Api.Logs
{
public class LogFileResource : RestResource
{
public string Filename { get; set; }
public DateTime LastWriteTime { get; set; }
public string ContentsUrl { get; set; }
public string DownloadUrl { get; set; }
}
}

View File

@ -1,56 +0,0 @@
using System.Linq;
using NzbDrone.Core.Instrumentation;
using Radarr.Http;
namespace NzbDrone.Api.Logs
{
public class LogModule : RadarrRestModule<LogResource>
{
private readonly ILogService _logService;
public LogModule(ILogService logService)
{
_logService = logService;
GetResourcePaged = GetLogs;
}
private PagingResource<LogResource> GetLogs(PagingResource<LogResource> pagingResource)
{
var pageSpec = pagingResource.MapToPagingSpec<LogResource, Log>();
if (pageSpec.SortKey == "time")
{
pageSpec.SortKey = "id";
}
var filter = pagingResource.Filters.FirstOrDefault();
if (filter != null && filter.Key == "level")
{
switch (filter.Value)
{
case "Fatal":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal");
break;
case "Error":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal" || h.Level == "Error");
break;
case "Warn":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal" || h.Level == "Error" || h.Level == "Warn");
break;
case "Info":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal" || h.Level == "Error" || h.Level == "Warn" || h.Level == "Info");
break;
case "Debug":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal" || h.Level == "Error" || h.Level == "Warn" || h.Level == "Info" || h.Level == "Debug");
break;
case "Trace":
pageSpec.FilterExpressions.Add(h => h.Level == "Fatal" || h.Level == "Error" || h.Level == "Warn" || h.Level == "Info" || h.Level == "Debug" || h.Level == "Trace");
break;
}
}
return ApplyToPage(_logService.Paged, pageSpec, LogResourceMapper.ToResource);
}
}
}

View File

@ -1,38 +0,0 @@
using System;
using Radarr.Http.REST;
namespace NzbDrone.Api.Logs
{
public class LogResource : RestResource
{
public DateTime Time { get; set; }
public string Exception { get; set; }
public string ExceptionType { get; set; }
public string Level { get; set; }
public string Logger { get; set; }
public string Message { get; set; }
}
public static class LogResourceMapper
{
public static LogResource ToResource(this Core.Instrumentation.Log model)
{
if (model == null)
{
return null;
}
return new LogResource
{
Id = model.Id,
Time = model.Time,
Exception = model.Exception,
ExceptionType = model.ExceptionType,
Level = model.Level,
Logger = model.Logger,
Message = model.Message
};
}
}
}

View File

@ -1,45 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Logs
{
public class UpdateLogFileModule : LogFileModuleBase
{
private readonly IAppFolderInfo _appFolderInfo;
private readonly IDiskProvider _diskProvider;
public UpdateLogFileModule(IAppFolderInfo appFolderInfo,
IDiskProvider diskProvider,
IConfigFileProvider configFileProvider)
: base(diskProvider, configFileProvider, "/update")
{
_appFolderInfo = appFolderInfo;
_diskProvider = diskProvider;
}
protected override IEnumerable<string> GetLogFiles()
{
if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder()))
{
return Enumerable.Empty<string>();
}
return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly)
.Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase))
.ToList();
}
protected override string GetLogFilePath(string filename)
{
return Path.Combine(_appFolderInfo.GetUpdateLogFolder(), filename);
}
protected override string DownloadUrlRoot => "updatelogfile";
}
}

View File

@ -1,46 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.MediaFiles.MovieImport.Manual;
using NzbDrone.Core.Qualities;
using Radarr.Http;
using Radarr.Http.Extensions;
namespace NzbDrone.Api.ManualImport
{
public class ManualImportModule : RadarrRestModule<ManualImportResource>
{
private readonly IManualImportService _manualImportService;
public ManualImportModule(IManualImportService manualImportService)
: base("/manualimport")
{
_manualImportService = manualImportService;
GetResourceAll = GetMediaFiles;
}
private List<ManualImportResource> GetMediaFiles()
{
var folderQuery = Request.Query.folder;
var folder = (string)folderQuery.Value;
var downloadIdQuery = Request.Query.downloadId;
var downloadId = (string)downloadIdQuery.Value;
var filterExistingFiles = Request.GetBooleanQueryParameter("filterExistingFiles", true);
return _manualImportService.GetMediaFiles(folder, downloadId, null, filterExistingFiles).ToResource().Select(AddQualityWeight).ToList();
}
private ManualImportResource AddQualityWeight(ManualImportResource item)
{
if (item.Quality != null)
{
item.QualityWeight = Quality.DefaultQualityDefinitions.Single(q => q.Quality == item.Quality.Quality).Weight;
item.QualityWeight += item.Quality.Revision.Real * 10;
item.QualityWeight += item.Quality.Revision.Version;
}
return item;
}
}
}

View File

@ -1,55 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.Movies;
using NzbDrone.Common.Crypto;
using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.ManualImport
{
public class ManualImportResource : RestResource
{
public string Path { get; set; }
public string RelativePath { get; set; }
public string Name { get; set; }
public long Size { get; set; }
public MovieResource Movie { get; set; }
public QualityModel Quality { get; set; }
public int QualityWeight { get; set; }
public string DownloadId { get; set; }
public IEnumerable<Rejection> Rejections { get; set; }
}
public static class ManualImportResourceMapper
{
public static ManualImportResource ToResource(this Core.MediaFiles.MovieImport.Manual.ManualImportItem model)
{
if (model == null)
{
return null;
}
return new ManualImportResource
{
Id = HashConverter.GetHashInt31(model.Path),
Path = model.Path,
RelativePath = model.RelativePath,
Name = model.Name,
Size = model.Size,
Movie = model.Movie.ToResource(),
Quality = model.Quality,
//QualityWeight
DownloadId = model.DownloadId,
Rejections = model.Rejections
};
}
public static List<ManualImportResource> ToResource(this IEnumerable<Core.MediaFiles.MovieImport.Manual.ManualImportItem> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,48 +0,0 @@
using System.IO;
using System.Text.RegularExpressions;
using Nancy;
using Nancy.Responses;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
namespace NzbDrone.Api.MediaCovers
{
public class MediaCoverModule : NzbDroneApiModule
{
private const string MEDIA_COVER_ROUTE = @"/(?<movieId>\d+)/(?<filename>(.+)\.(jpg|png|gif))";
private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly IAppFolderInfo _appFolderInfo;
private readonly IDiskProvider _diskProvider;
public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider)
: base("MediaCover")
{
_appFolderInfo = appFolderInfo;
_diskProvider = diskProvider;
Get(MEDIA_COVER_ROUTE, options => GetMediaCover(options.movieId, options.filename));
}
private object GetMediaCover(int movieId, string filename)
{
var filePath = Path.Combine(_appFolderInfo.GetAppDataPath(), "MediaCover", movieId.ToString(), filename);
if (!_diskProvider.FileExists(filePath) || _diskProvider.GetFileSize(filePath) == 0)
{
// Return the full sized image if someone requests a non-existing resized one.
// TODO: This code can be removed later once everyone had the update for a while.
var basefilePath = RegexResizedImage.Replace(filePath, ".jpg");
if (basefilePath == filePath || !_diskProvider.FileExists(basefilePath))
{
return new NotFoundResponse();
}
filePath = basefilePath;
}
return new StreamResponse(() => File.OpenRead(filePath), MimeTypes.GetMimeType(filePath));
}
}
}

View File

@ -1,36 +0,0 @@
using NzbDrone.Core.Extras.Metadata;
namespace NzbDrone.Api.Metadata
{
public class MetadataModule : ProviderModuleBase<MetadataResource, IMetadata, MetadataDefinition>
{
public MetadataModule(IMetadataFactory metadataFactory)
: base(metadataFactory, "metadata")
{
}
protected override void MapToResource(MetadataResource resource, MetadataDefinition definition)
{
base.MapToResource(resource, definition);
resource.Enable = definition.Enable;
}
protected override void MapToModel(MetadataDefinition definition, MetadataResource resource)
{
base.MapToModel(definition, resource);
definition.Enable = resource.Enable;
}
protected override void Validate(MetadataDefinition definition, bool includeWarnings)
{
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}
}

View File

@ -1,7 +0,0 @@
namespace NzbDrone.Api.Metadata
{
public class MetadataResource : ProviderResource<MetadataResource>
{
public bool Enable { get; set; }
}
}

View File

@ -1,72 +0,0 @@
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.DecisionEngine.Specifications;
using NzbDrone.Core.Exceptions;
using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.MediaFiles.Events;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Movies;
using NzbDrone.SignalR;
using Radarr.Http;
using HttpStatusCode = System.Net.HttpStatusCode;
namespace NzbDrone.Api.MovieFiles
{
public class MovieFileModule : RadarrRestModuleWithSignalR<MovieFileResource, MovieFile>, IHandle<MovieFileAddedEvent>
{
private readonly IMediaFileService _mediaFileService;
private readonly IDeleteMediaFiles _mediaFileDeletionService;
private readonly IMovieService _movieService;
private readonly IUpgradableSpecification _qualityUpgradableSpecification;
public MovieFileModule(IBroadcastSignalRMessage signalRBroadcaster,
IMediaFileService mediaFileService,
IDeleteMediaFiles mediaFileDeletionService,
IMovieService movieService,
IUpgradableSpecification qualityUpgradableSpecification)
: base(signalRBroadcaster)
{
_mediaFileService = mediaFileService;
_mediaFileDeletionService = mediaFileDeletionService;
_movieService = movieService;
_qualityUpgradableSpecification = qualityUpgradableSpecification;
GetResourceById = GetMovieFile;
UpdateResource = SetQuality;
DeleteResource = DeleteMovieFile;
}
private MovieFileResource GetMovieFile(int id)
{
var movie = _mediaFileService.GetMovie(id);
return movie.ToResource();
}
private void SetQuality(MovieFileResource movieFileResource)
{
var movieFile = _mediaFileService.GetMovie(movieFileResource.Id);
movieFile.Quality = movieFileResource.Quality;
_mediaFileService.Update(movieFile);
BroadcastResourceChange(ModelAction.Updated, movieFile.Id);
}
private void DeleteMovieFile(int id)
{
var movieFile = _mediaFileService.GetMovie(id);
if (movieFile == null)
{
throw new NzbDroneClientException(HttpStatusCode.NotFound, "Movie file not found");
}
var movie = _movieService.GetMovie(movieFile.MovieId);
_mediaFileDeletionService.DeleteMovieFile(movie, movieFile);
}
public void Handle(MovieFileAddedEvent message)
{
BroadcastResourceChange(ModelAction.Updated, message.MovieFile.Id);
}
}
}

View File

@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.Movies;
using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.MovieFiles
{
public class MovieFileResource : RestResource
{
public MovieFileResource()
{
}
//Todo: Sorters should be done completely on the client
//Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing?
//Todo: We should get the entire Profile instead of ID and Name separately
public int MovieId { get; set; }
public string RelativePath { get; set; }
public string Path { get; set; }
public long Size { get; set; }
public DateTime DateAdded { get; set; }
public string SceneName { get; set; }
public string ReleaseGroup { get; set; }
public QualityModel Quality { get; set; }
public MovieResource Movie { get; set; }
public string Edition { get; set; }
public Core.MediaFiles.MediaInfo.MediaInfoModel MediaInfo { get; set; }
//TODO: Add series statistics as a property of the series (instead of individual properties)
}
public static class MovieFileResourceMapper
{
public static MovieFileResource ToResource(this MovieFile model)
{
if (model == null)
{
return null;
}
MovieResource movie = null;
/*if (model.Movie != null)
{
//model.Movie.LazyLoad();
if (model.Movie.Value != null)
{
//movie = model.Movie.Value.ToResource();
}
}*/
return new MovieFileResource
{
Id = model.Id,
RelativePath = model.RelativePath,
Path = model.Path,
Size = model.Size,
DateAdded = model.DateAdded,
SceneName = model.SceneName,
ReleaseGroup = model.ReleaseGroup,
Quality = model.Quality,
Movie = movie,
MediaInfo = model.MediaInfo,
Edition = model.Edition
};
}
public static MovieFile ToModel(this MovieFileResource resource)
{
if (resource == null)
{
return null;
}
return new MovieFile
{
};
}
public static List<MovieFileResource> ToResource(this IEnumerable<MovieFile> movies)
{
return movies.Select(ToResource).ToList();
}
}
}

View File

@ -1,22 +0,0 @@
using NzbDrone.Core.Movies.AlternativeTitles;
using Radarr.Http;
namespace NzbDrone.Api.Movies
{
public class AlternativeTitleModule : RadarrRestModule<AlternativeTitleResource>
{
private readonly IAlternativeTitleService _altTitleService;
public AlternativeTitleModule(IAlternativeTitleService altTitleService)
: base("/alttitle")
{
_altTitleService = altTitleService;
GetResourceById = GetTitle;
}
private AlternativeTitleResource GetTitle(int id)
{
return _altTitleService.GetById(id).ToResource();
}
}
}

View File

@ -1,77 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Movies.AlternativeTitles;
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class AlternativeTitleResource : RestResource
{
public AlternativeTitleResource()
{
}
//Todo: Sorters should be done completely on the client
//Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing?
//Todo: We should get the entire Profile instead of ID and Name separately
public SourceType SourceType { get; set; }
public int MovieId { get; set; }
public string Title { get; set; }
public string CleanTitle { get; set; }
public int SourceId { get; set; }
public int Votes { get; set; }
public int VoteCount { get; set; }
public Language Language { get; set; }
//TODO: Add series statistics as a property of the series (instead of individual properties)
}
public static class AlternativeTitleResourceMapper
{
public static AlternativeTitleResource ToResource(this AlternativeTitle model)
{
if (model == null)
{
return null;
}
return new AlternativeTitleResource
{
Id = model.Id,
SourceType = model.SourceType,
MovieId = model.MovieId,
Title = model.Title,
SourceId = model.SourceId,
Votes = model.Votes,
VoteCount = model.VoteCount,
Language = model.Language
};
}
public static AlternativeTitle ToModel(this AlternativeTitleResource resource)
{
if (resource == null)
{
return null;
}
return new AlternativeTitle
{
Id = resource.Id,
SourceType = resource.SourceType,
MovieId = resource.MovieId,
Title = resource.Title,
SourceId = resource.SourceId,
Votes = resource.Votes,
VoteCount = resource.VoteCount,
Language = resource.Language
};
}
public static List<AlternativeTitleResource> ToResource(this IEnumerable<AlternativeTitle> movies)
{
return movies.Select(ToResource).ToList();
}
}
}

View File

@ -1,25 +0,0 @@
using NzbDrone.Common.Cache;
using Radarr.Http;
namespace NzbDrone.Api.Movies
{
public class AlternativeYearModule : RadarrRestModule<AlternativeYearResource>
{
private readonly ICached<int> _yearCache;
public AlternativeYearModule(ICacheManager cacheManager)
: base("/altyear")
{
GetResourceById = GetYear;
_yearCache = cacheManager.GetCache<int>(GetType(), "altYears");
}
private AlternativeYearResource GetYear(int id)
{
return new AlternativeYearResource
{
Year = _yearCache.Find(id.ToString())
};
}
}
}

View File

@ -1,63 +0,0 @@
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class AlternativeYearResource : RestResource
{
public AlternativeYearResource()
{
}
//Todo: Sorters should be done completely on the client
//Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing?
//Todo: We should get the entire Profile instead of ID and Name separately
public int MovieId { get; set; }
public int Year { get; set; }
//TODO: Add series statistics as a property of the series (instead of individual properties)
}
/*public static class AlternativeYearResourceMapper
{
/*public static AlternativeYearResource ToResource(this AlternativeTitle model)
{
if (model == null) return null;
AlternativeTitleResource resource = null;
return new AlternativeTitleResource
{
Id = model.Id,
SourceType = model.SourceType,
MovieId = model.MovieId,
Title = model.Title,
SourceId = model.SourceId,
Votes = model.Votes,
VoteCount = model.VoteCount,
Language = model.Language
};
}
public static AlternativeTitle ToModel(this AlternativeTitleResource resource)
{
if (resource == null) return null;
return new AlternativeTitle
{
Id = resource.Id,
SourceType = resource.SourceType,
MovieId = resource.MovieId,
Title = resource.Title,
SourceId = resource.SourceId,
Votes = resource.Votes,
VoteCount = resource.VoteCount,
Language = resource.Language
};
}
public static List<AlternativeTitleResource> ToResource(this IEnumerable<AlternativeTitle> movies)
{
return movies.Select(ToResource).ToList();
}
}*/
}

View File

@ -1,60 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.ImportList;
using NzbDrone.Core.ImportLists;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.Movies;
using Radarr.Http;
namespace NzbDrone.Api.Movies
{
public class MovieDiscoverModule : RadarrRestModule<MovieResource>
{
private readonly IImportListFactory _importListFactory;
public MovieDiscoverModule(IImportListFactory importListFactory)
: base("/movies/discover")
{
_importListFactory = importListFactory;
Get("/lists", x => GetLists());
Get("/{action?recommendations}", x => Search(x.action));
}
private object Search(string action)
{
//Return empty for now so as not to break 3rd Party
var imdbResults = new List<Movie>();
return MapToResource(imdbResults);
}
private object GetLists()
{
var lists = _importListFactory.Discoverable();
return lists.Select(definition =>
{
var resource = new ImportListResource();
resource.Id = definition.Definition.Id;
resource.Name = definition.Definition.Name;
return resource;
});
}
private static IEnumerable<MovieResource> MapToResource(IEnumerable<Movie> movies)
{
foreach (var currentMovie in movies)
{
var resource = currentMovie.ToResource();
var poster = currentMovie.Images.FirstOrDefault(c => c.CoverType == MediaCoverTypes.Poster);
if (poster != null)
{
resource.RemotePoster = poster.Url;
}
yield return resource;
}
}
}
}

View File

@ -1,63 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy;
using NzbDrone.Core.Movies;
using Radarr.Http.Extensions;
namespace NzbDrone.Api.Movies
{
public class MovieEditorModule : NzbDroneApiModule
{
private readonly IMovieService _movieService;
public MovieEditorModule(IMovieService movieService)
: base("/movie/editor")
{
_movieService = movieService;
Put("/", movie => SaveAll());
Put("/delete", movie => DeleteSelected());
}
private object SaveAll()
{
var resources = Request.Body.FromJson<List<MovieResource>>();
var movie = resources.Select(movieResource => movieResource.ToModel(_movieService.GetMovie(movieResource.Id))).ToList();
return ResponseWithCode(_movieService.UpdateMovie(movie, true)
.ToResource(),
HttpStatusCode.Accepted);
}
private object DeleteSelected()
{
var deleteFiles = false;
var addExclusion = false;
var deleteFilesQuery = Request.Query.deleteFiles;
var addExclusionQuery = Request.Query.addExclusion;
if (deleteFilesQuery.HasValue)
{
deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value);
}
if (addExclusionQuery.HasValue)
{
addExclusion = Convert.ToBoolean(addExclusionQuery.Value);
}
var ids = Request.Body.FromJson<List<int>>();
foreach (var id in ids)
{
_movieService.DeleteMovie(id, deleteFiles, addExclusion);
}
return new Response
{
StatusCode = HttpStatusCode.Accepted
};
}
}
}

View File

@ -1,66 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Nancy;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.MetadataSource;
using Radarr.Http;
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class MovieLookupModule : RadarrRestModule<MovieResource>
{
private readonly ISearchForNewMovie _searchProxy;
private readonly IProvideMovieInfo _movieInfo;
public MovieLookupModule(ISearchForNewMovie searchProxy, IProvideMovieInfo movieInfo)
: base("/movie/lookup")
{
_movieInfo = movieInfo;
_searchProxy = searchProxy;
Get("/", x => Search());
Get("/tmdb", x => SearchByTmdbId());
Get("/imdb", x => SearchByImdbId());
}
private object SearchByTmdbId()
{
int tmdbId = -1;
if (int.TryParse(Request.Query.tmdbId, out tmdbId))
{
var result = _movieInfo.GetMovieInfo(tmdbId).Item1;
return result.ToResource();
}
throw new BadRequestException("Tmdb Id was not valid");
}
private object SearchByImdbId()
{
string imdbId = Request.Query.imdbId;
var result = _movieInfo.GetMovieByImdbId(imdbId);
return result.ToResource();
}
private object Search()
{
var imdbResults = _searchProxy.SearchForNewMovie((string)Request.Query.term);
return MapToResource(imdbResults);
}
private static IEnumerable<MovieResource> MapToResource(IEnumerable<Core.Movies.Movie> movies)
{
foreach (var currentSeries in movies)
{
var resource = currentSeries.ToResource();
var poster = currentSeries.Images.FirstOrDefault(c => c.CoverType == MediaCoverTypes.Poster);
if (poster != null)
{
resource.RemotePoster = poster.Url;
}
yield return resource;
}
}
}
}

View File

@ -1,204 +0,0 @@
using System;
using System.Collections.Generic;
using FluentValidation;
using Nancy;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.MediaFiles.Events;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Movies;
using NzbDrone.Core.Movies.Events;
using NzbDrone.Core.Validation;
using NzbDrone.Core.Validation.Paths;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.Movies
{
public class MovieModule : RadarrRestModuleWithSignalR<MovieResource, Movie>,
IHandle<MovieImportedEvent>,
IHandle<MovieFileDeletedEvent>,
IHandle<MoviesDeletedEvent>,
IHandle<MovieUpdatedEvent>,
IHandle<MovieEditedEvent>,
IHandle<MovieRenamedEvent>,
IHandle<MediaCoversUpdatedEvent>
{
private const string TITLE_SLUG_ROUTE = "/titleslug/(?<slug>[^/]+)";
private readonly IMovieService _movieService;
private readonly IAddMovieService _addMovieService;
private readonly IMapCoversToLocal _coverMapper;
public MovieModule(IBroadcastSignalRMessage signalRBroadcaster,
IMovieService movieService,
IAddMovieService addMovieService,
IMapCoversToLocal coverMapper,
RootFolderValidator rootFolderValidator,
RecycleBinValidator recycleBinValidator,
MappedNetworkDriveValidator mappedNetworkDriveValidator,
MoviePathValidator moviesPathValidator,
MovieExistsValidator moviesExistsValidator,
MovieAncestorValidator moviesAncestorValidator,
SystemFolderValidator systemFolderValidator,
ProfileExistsValidator profileExistsValidator)
: base(signalRBroadcaster)
{
_movieService = movieService;
_addMovieService = addMovieService;
_coverMapper = coverMapper;
GetResourceAll = AllMovie;
GetResourceById = GetMovie;
CreateResource = AddMovie;
UpdateResource = UpdateMovie;
DeleteResource = DeleteMovie;
SharedValidator.RuleFor(s => s.ProfileId).ValidId();
SharedValidator.RuleFor(s => s.Path)
.Cascade(CascadeMode.StopOnFirstFailure)
.IsValidPath()
.SetValidator(rootFolderValidator)
.SetValidator(mappedNetworkDriveValidator)
.SetValidator(moviesPathValidator)
.SetValidator(moviesAncestorValidator)
.SetValidator(recycleBinValidator)
.SetValidator(systemFolderValidator)
.When(s => !s.Path.IsNullOrWhiteSpace());
SharedValidator.RuleFor(s => s.ProfileId).SetValidator(profileExistsValidator);
PostValidator.RuleFor(s => s.Path).IsValidPath().When(s => s.RootFolderPath.IsNullOrWhiteSpace());
PostValidator.RuleFor(s => s.RootFolderPath)
.IsValidPath()
.When(s => s.Path.IsNullOrWhiteSpace());
PostValidator.RuleFor(s => s.Title).NotEmpty().When(s => s.TmdbId <= 0);
PostValidator.RuleFor(s => s.TmdbId).NotNull().NotEmpty().SetValidator(moviesExistsValidator);
PutValidator.RuleFor(s => s.Path).IsValidPath();
}
private MovieResource GetMovie(int id)
{
var movies = _movieService.GetMovie(id);
return MapToResource(movies);
}
protected MovieResource MapToResource(Movie movies)
{
if (movies == null)
{
return null;
}
var resource = movies.ToResource();
MapCoversToLocal(resource);
return resource;
}
private List<MovieResource> AllMovie()
{
var moviesResources = _movieService.GetAllMovies().ToResource();
MapCoversToLocal(moviesResources.ToArray());
return moviesResources;
}
private int AddMovie(MovieResource moviesResource)
{
var model = moviesResource.ToModel();
return _addMovieService.AddMovie(model).Id;
}
private void UpdateMovie(MovieResource moviesResource)
{
var model = moviesResource.ToModel(_movieService.GetMovie(moviesResource.Id));
_movieService.UpdateMovie(model);
BroadcastResourceChange(ModelAction.Updated, moviesResource);
}
private void DeleteMovie(int id)
{
var deleteFiles = false;
var addExclusion = false;
var deleteFilesQuery = Request.Query.deleteFiles;
var addExclusionQuery = Request.Query.addExclusion;
if (deleteFilesQuery.HasValue)
{
deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value);
}
if (addExclusionQuery.HasValue)
{
addExclusion = Convert.ToBoolean(addExclusionQuery.Value);
}
_movieService.DeleteMovie(id, deleteFiles, addExclusion);
}
private void MapCoversToLocal(params MovieResource[] movies)
{
foreach (var moviesResource in movies)
{
_coverMapper.ConvertToLocalUrls(moviesResource.Id, moviesResource.Images);
}
}
public void Handle(MovieImportedEvent message)
{
BroadcastResourceChange(ModelAction.Updated, message.ImportedMovie.MovieId);
}
public void Handle(MovieFileDeletedEvent message)
{
if (message.Reason == DeleteMediaFileReason.Upgrade)
{
return;
}
BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId);
}
public void Handle(MoviesDeletedEvent message)
{
foreach (var movie in message.Movies)
{
BroadcastResourceChange(ModelAction.Deleted, movie.Id);
}
}
public void Handle(MovieUpdatedEvent message)
{
BroadcastResourceChange(ModelAction.Updated, message.Movie.Id);
}
public void Handle(MovieEditedEvent message)
{
BroadcastResourceChange(ModelAction.Updated, message.Movie.Id);
}
public void Handle(MovieRenamedEvent message)
{
BroadcastResourceChange(ModelAction.Updated, message.Movie.Id);
}
public void Handle(MediaCoversUpdatedEvent message)
{
if (message.Updated)
{
BroadcastResourceChange(ModelAction.Updated, message.Movie.Id);
}
}
}
}

View File

@ -1,70 +0,0 @@
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.DecisionEngine.Specifications;
using NzbDrone.Core.Download;
using NzbDrone.Core.MediaFiles.Events;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Movies;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.Movies
{
public abstract class MovieModuleWithSignalR : RadarrRestModuleWithSignalR<MovieResource, Core.Movies.Movie>,
IHandle<MovieGrabbedEvent>,
IHandle<MovieDownloadedEvent>
{
protected readonly IMovieService _movieService;
protected readonly IUpgradableSpecification _qualityUpgradableSpecification;
protected MovieModuleWithSignalR(IMovieService movieService,
IUpgradableSpecification qualityUpgradableSpecification,
IBroadcastSignalRMessage signalRBroadcaster)
: base(signalRBroadcaster)
{
_movieService = movieService;
_qualityUpgradableSpecification = qualityUpgradableSpecification;
GetResourceById = GetMovie;
}
protected MovieModuleWithSignalR(IMovieService movieService,
IUpgradableSpecification qualityUpgradableSpecification,
IBroadcastSignalRMessage signalRBroadcaster,
string resource)
: base(signalRBroadcaster, resource)
{
_movieService = movieService;
_qualityUpgradableSpecification = qualityUpgradableSpecification;
GetResourceById = GetMovie;
}
protected MovieResource GetMovie(int id)
{
var movie = _movieService.GetMovie(id);
return MapToResource(movie);
}
protected MovieResource MapToResource(Movie movie)
{
var resource = movie.ToResource();
return resource;
}
public void Handle(MovieGrabbedEvent message)
{
var resource = message.Movie.Movie.ToResource();
//add a grabbed field in MovieResource?
//resource.Grabbed = true;
BroadcastResourceChange(ModelAction.Updated, resource);
}
public void Handle(MovieDownloadedEvent message)
{
var resource = message.Movie.Movie.ToResource();
BroadcastResourceChange(ModelAction.Updated, resource);
}
}
}

View File

@ -1,244 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.MovieFiles;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.Movies;
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class MovieResource : RestResource
{
public MovieResource()
{
Monitored = true;
}
//Todo: Sorters should be done completely on the client
//Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing?
//Todo: We should get the entire Profile instead of ID and Name separately
//View Only
public string Title { get; set; }
public List<AlternativeTitleResource> AlternativeTitles { get; set; }
public int? SecondaryYear { get; set; }
public int SecondaryYearSourceId { get; set; }
public string SortTitle { get; set; }
public long? SizeOnDisk { get; set; }
public MovieStatusType Status { get; set; }
public string Overview { get; set; }
public DateTime? InCinemas { get; set; }
public DateTime? PhysicalRelease { get; set; }
public string PhysicalReleaseNote { get; set; }
public List<MediaCover> Images { get; set; }
public string Website { get; set; }
public bool Downloaded { get; set; }
public string RemotePoster { get; set; }
public int Year { get; set; }
public bool HasFile { get; set; }
public string YouTubeTrailerId { get; set; }
public string Studio { get; set; }
//View & Edit
public string Path { get; set; }
public int ProfileId { get; set; }
//Editing Only
public bool Monitored { get; set; }
public MovieStatusType MinimumAvailability { get; set; }
public bool IsAvailable { get; set; }
public string FolderName { get; set; }
public int Runtime { get; set; }
public DateTime? LastInfoSync { get; set; }
public string CleanTitle { get; set; }
public string ImdbId { get; set; }
public int TmdbId { get; set; }
public string TitleSlug { get; set; }
public string RootFolderPath { get; set; }
public string Certification { get; set; }
public List<string> Genres { get; set; }
public HashSet<int> Tags { get; set; }
public DateTime Added { get; set; }
public AddMovieOptions AddOptions { get; set; }
public Ratings Ratings { get; set; }
//public List<string> AlternativeTitles { get; set; }
public MovieFileResource MovieFile { get; set; }
//TODO: Add series statistics as a property of the series (instead of individual properties)
//Used to support legacy consumers
public int QualityProfileId
{
get
{
return ProfileId;
}
set
{
if (value > 0 && ProfileId == 0)
{
ProfileId = value;
}
}
}
}
public static class MovieResourceMapper
{
public static MovieResource ToResource(this Core.Movies.Movie model)
{
if (model == null)
{
return null;
}
long size = model.MovieFile?.Size ?? 0;
bool downloaded = model.MovieFile != null;
MovieFileResource movieFile = model.MovieFile?.ToResource();
/*if(model.MovieFile != null)
{
model.MovieFile.LazyLoad();
}
if (model.MovieFile != null && model.MovieFile.IsLoaded && model.MovieFile.Value != null)
{
size = model.MovieFile.Value.Size;
downloaded = true;
movieFile = model.MovieFile.Value.ToResource();
}*/
//model.AlternativeTitles.LazyLoad();
return new MovieResource
{
Id = model.Id,
TmdbId = model.TmdbId,
Title = model.Title,
//AlternateTitles
SortTitle = model.SortTitle,
InCinemas = model.InCinemas,
PhysicalRelease = model.PhysicalRelease,
HasFile = model.HasFile,
Downloaded = downloaded,
//TotalEpisodeCount
//EpisodeCount
//EpisodeFileCount
SizeOnDisk = size,
Status = model.Status,
Overview = model.Overview,
//NextAiring
//PreviousAiring
Images = model.Images,
Year = model.Year,
SecondaryYear = model.SecondaryYear,
Path = model.Path,
ProfileId = model.ProfileId,
Monitored = model.Monitored,
MinimumAvailability = model.MinimumAvailability,
IsAvailable = model.IsAvailable(),
FolderName = model.FolderName(),
//SizeOnDisk = size,
Runtime = model.Runtime,
LastInfoSync = model.LastInfoSync,
CleanTitle = model.CleanTitle,
ImdbId = model.ImdbId,
TitleSlug = model.TitleSlug,
RootFolderPath = model.RootFolderPath,
Certification = model.Certification,
Website = model.Website,
Genres = model.Genres,
Tags = model.Tags,
Added = model.Added,
AddOptions = model.AddOptions,
AlternativeTitles = model.AlternativeTitles.ToResource(),
Ratings = model.Ratings,
MovieFile = movieFile,
YouTubeTrailerId = model.YouTubeTrailerId,
Studio = model.Studio
};
}
public static Core.Movies.Movie ToModel(this MovieResource resource)
{
if (resource == null)
{
return null;
}
return new Core.Movies.Movie
{
Id = resource.Id,
TmdbId = resource.TmdbId,
Title = resource.Title,
//AlternateTitles
SortTitle = resource.SortTitle,
InCinemas = resource.InCinemas,
PhysicalRelease = resource.PhysicalRelease,
//TotalEpisodeCount
//EpisodeCount
//EpisodeFileCount
//SizeOnDisk
Overview = resource.Overview,
//NextAiring
//PreviousAiring
Images = resource.Images,
Year = resource.Year,
SecondaryYear = resource.SecondaryYear,
Path = resource.Path,
ProfileId = resource.ProfileId,
Monitored = resource.Monitored,
MinimumAvailability = resource.MinimumAvailability,
Runtime = resource.Runtime,
LastInfoSync = resource.LastInfoSync,
CleanTitle = resource.CleanTitle,
ImdbId = resource.ImdbId,
TitleSlug = resource.TitleSlug,
RootFolderPath = resource.RootFolderPath,
Certification = resource.Certification,
Website = resource.Website,
Genres = resource.Genres,
Tags = resource.Tags,
Added = resource.Added,
AddOptions = resource.AddOptions,
//AlternativeTitles = resource.AlternativeTitles,
Ratings = resource.Ratings,
YouTubeTrailerId = resource.YouTubeTrailerId,
Studio = resource.Studio
};
}
public static Core.Movies.Movie ToModel(this MovieResource resource, Core.Movies.Movie movie)
{
var updatedmovie = resource.ToModel();
movie.ApplyChanges(updatedmovie);
return movie;
}
public static List<MovieResource> ToResource(this IEnumerable<Core.Movies.Movie> movies)
{
return movies.Select(ToResource).ToList();
}
}
}

View File

@ -1,32 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.MediaFiles;
using Radarr.Http;
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class RenameMovieModule : RadarrRestModule<RenameMovieResource>
{
private readonly IRenameMovieFileService _renameMovieFileService;
public RenameMovieModule(IRenameMovieFileService renameMovieFileService)
: base("renameMovie")
{
_renameMovieFileService = renameMovieFileService;
GetResourceAll = GetMovies; //TODO: GetResourceSingle?
}
private List<RenameMovieResource> GetMovies()
{
if (!Request.Query.MovieId.HasValue)
{
throw new BadRequestException("movieId is missing");
}
var movieId = (int)Request.Query.MovieId;
return _renameMovieFileService.GetRenamePreviews(movieId).ToResource();
}
}
}

View File

@ -1,38 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Radarr.Http.REST;
namespace NzbDrone.Api.Movies
{
public class RenameMovieResource : RestResource
{
public int MovieId { get; set; }
public int MovieFileId { get; set; }
public string ExistingPath { get; set; }
public string NewPath { get; set; }
}
public static class RenameMovieResourceMapper
{
public static RenameMovieResource ToResource(this Core.MediaFiles.RenameMovieFilePreview model)
{
if (model == null)
{
return null;
}
return new RenameMovieResource
{
MovieId = model.MovieId,
MovieFileId = model.MovieFileId,
ExistingPath = model.ExistingPath,
NewPath = model.NewPath
};
}
public static List<RenameMovieResource> ToResource(this IEnumerable<Core.MediaFiles.RenameMovieFilePreview> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,44 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.ImportLists;
using NzbDrone.Core.ImportLists.ImportExclusions;
using Radarr.Http;
namespace NzbDrone.Api.ImportList
{
public class ImportExclusionsModule : RadarrRestModule<ImportExclusionsResource>
{
private readonly IImportExclusionsService _exclusionService;
public ImportExclusionsModule(ImportListFactory importListFactory, IImportExclusionsService exclusionService)
: base("exclusions")
{
_exclusionService = exclusionService;
GetResourceAll = GetAll;
CreateResource = AddExclusion;
DeleteResource = RemoveExclusion;
GetResourceById = GetById;
}
public List<ImportExclusionsResource> GetAll()
{
return _exclusionService.GetAllExclusions().ToResource();
}
public ImportExclusionsResource GetById(int id)
{
return _exclusionService.GetById(id).ToResource();
}
public int AddExclusion(ImportExclusionsResource exclusionResource)
{
var model = exclusionResource.ToModel();
return _exclusionService.AddExclusion(model).Id;
}
public void RemoveExclusion(int id)
{
_exclusionService.RemoveExclusion(new ImportExclusion { Id = id });
}
}
}

View File

@ -1,47 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace NzbDrone.Api.ImportList
{
public class ImportExclusionsResource : ProviderResource<ImportExclusionsResource>
{
//public int Id { get; set; }
public int TmdbId { get; set; }
public string MovieTitle { get; set; }
public int MovieYear { get; set; }
}
public static class ImportExclusionsResourceMapper
{
public static ImportExclusionsResource ToResource(this Core.ImportLists.ImportExclusions.ImportExclusion model)
{
if (model == null)
{
return null;
}
return new ImportExclusionsResource
{
Id = model.Id,
TmdbId = model.TmdbId,
MovieTitle = model.MovieTitle,
MovieYear = model.MovieYear
};
}
public static List<ImportExclusionsResource> ToResource(this IEnumerable<Core.ImportLists.ImportExclusions.ImportExclusion> exclusions)
{
return exclusions.Select(ToResource).ToList();
}
public static Core.ImportLists.ImportExclusions.ImportExclusion ToModel(this ImportExclusionsResource resource)
{
return new Core.ImportLists.ImportExclusions.ImportExclusion
{
TmdbId = resource.TmdbId,
MovieTitle = resource.MovieTitle,
MovieYear = resource.MovieYear
};
}
}
}

View File

@ -1,55 +0,0 @@
using FluentValidation;
using NzbDrone.Core.ImportLists;
using NzbDrone.Core.Validation;
using NzbDrone.Core.Validation.Paths;
namespace NzbDrone.Api.ImportList
{
public class ImportListModule : ProviderModuleBase<ImportListResource, IImportList, ImportListDefinition>
{
public ImportListModule(ImportListFactory importListFactory, ProfileExistsValidator profileExistsValidator)
: base(importListFactory, "netimport")
{
PostValidator.RuleFor(c => c.RootFolderPath).IsValidPath();
PostValidator.RuleFor(c => c.MinimumAvailability).NotNull();
SharedValidator.RuleFor(c => c.ProfileId).ValidId();
SharedValidator.RuleFor(c => c.ProfileId).SetValidator(profileExistsValidator);
}
protected override void MapToResource(ImportListResource resource, ImportListDefinition definition)
{
base.MapToResource(resource, definition);
resource.Enabled = definition.Enabled;
resource.EnableAuto = definition.EnableAuto;
resource.ProfileId = definition.ProfileId;
resource.RootFolderPath = definition.RootFolderPath;
resource.ShouldMonitor = definition.ShouldMonitor;
resource.MinimumAvailability = definition.MinimumAvailability;
resource.Tags = definition.Tags;
}
protected override void MapToModel(ImportListDefinition definition, ImportListResource resource)
{
base.MapToModel(definition, resource);
definition.Enabled = resource.Enabled;
definition.EnableAuto = resource.EnableAuto;
definition.ProfileId = resource.ProfileId;
definition.RootFolderPath = resource.RootFolderPath;
definition.ShouldMonitor = resource.ShouldMonitor;
definition.MinimumAvailability = resource.MinimumAvailability;
definition.Tags = resource.Tags;
}
protected override void Validate(ImportListDefinition definition, bool includeWarnings)
{
if (!definition.Enable)
{
return;
}
base.Validate(definition, includeWarnings);
}
}
}

View File

@ -1,16 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.Movies;
namespace NzbDrone.Api.ImportList
{
public class ImportListResource : ProviderResource<ImportListResource>
{
public bool Enabled { get; set; }
public bool EnableAuto { get; set; }
public bool ShouldMonitor { get; set; }
public string RootFolderPath { get; set; }
public int ProfileId { get; set; }
public MovieStatusType MinimumAvailability { get; set; }
public HashSet<int> Tags { get; set; }
}
}

View File

@ -1,64 +0,0 @@
using NzbDrone.Core.Notifications;
namespace NzbDrone.Api.Notifications
{
public class NotificationModule : ProviderModuleBase<NotificationResource, INotification, NotificationDefinition>
{
public NotificationModule(NotificationFactory notificationFactory)
: base(notificationFactory, "notification")
{
}
protected override void MapToResource(NotificationResource resource, NotificationDefinition definition)
{
base.MapToResource(resource, definition);
resource.OnGrab = definition.OnGrab;
resource.OnDownload = definition.OnDownload;
resource.OnUpgrade = definition.OnUpgrade;
resource.OnRename = definition.OnRename;
resource.OnMovieDelete = definition.OnMovieDelete;
resource.OnMovieFileDelete = definition.OnMovieFileDelete;
resource.OnMovieFileDeleteForUpgrade = definition.OnMovieFileDeleteForUpgrade;
resource.SupportsOnGrab = definition.SupportsOnGrab;
resource.SupportsOnDownload = definition.SupportsOnDownload;
resource.SupportsOnUpgrade = definition.SupportsOnUpgrade;
resource.SupportsOnRename = definition.SupportsOnRename;
resource.SupportsOnMovieDelete = definition.SupportsOnMovieDelete;
resource.SupportsOnMovieFileDelete = definition.SupportsOnMovieFileDelete;
resource.SupportsOnMovieFileDeleteForUpgrade = definition.SupportsOnMovieFileDeleteForUpgrade;
resource.Tags = definition.Tags;
}
protected override void MapToModel(NotificationDefinition definition, NotificationResource resource)
{
base.MapToModel(definition, resource);
definition.OnGrab = resource.OnGrab;
definition.OnDownload = resource.OnDownload;
definition.OnUpgrade = resource.OnUpgrade;
definition.OnRename = resource.OnRename;
definition.OnMovieDelete = resource.OnMovieDelete;
definition.OnMovieFileDelete = resource.OnMovieFileDelete;
definition.OnMovieFileDeleteForUpgrade = resource.OnMovieFileDeleteForUpgrade;
definition.SupportsOnGrab = resource.SupportsOnGrab;
definition.SupportsOnDownload = resource.SupportsOnDownload;
definition.SupportsOnUpgrade = resource.SupportsOnUpgrade;
definition.SupportsOnRename = resource.SupportsOnRename;
definition.SupportsOnMovieDelete = resource.SupportsOnMovieDelete;
definition.SupportsOnMovieFileDelete = resource.SupportsOnMovieFileDelete;
definition.SupportsOnMovieFileDeleteForUpgrade = resource.SupportsOnMovieFileDeleteForUpgrade;
definition.Tags = resource.Tags;
}
protected override void Validate(NotificationDefinition definition, bool includeWarnings)
{
if (!definition.OnGrab && !definition.OnDownload)
{
return;
}
base.Validate(definition, includeWarnings);
}
}
}

View File

@ -1,23 +0,0 @@
using System.Collections.Generic;
namespace NzbDrone.Api.Notifications
{
public class NotificationResource : ProviderResource<NotificationResource>
{
public bool OnGrab { get; set; }
public bool OnDownload { get; set; }
public bool OnUpgrade { get; set; }
public bool OnRename { get; set; }
public bool OnMovieDelete { get; set; }
public bool OnMovieFileDelete { get; set; }
public bool OnMovieFileDeleteForUpgrade { get; set; }
public bool SupportsOnGrab { get; set; }
public bool SupportsOnDownload { get; set; }
public bool SupportsOnUpgrade { get; set; }
public bool SupportsOnRename { get; set; }
public bool SupportsOnMovieDelete { get; set; }
public bool SupportsOnMovieFileDelete { get; set; }
public bool SupportsOnMovieFileDeleteForUpgrade { get; set; }
public HashSet<int> Tags { get; set; }
}
}

View File

@ -1,12 +0,0 @@
using Radarr.Http;
namespace NzbDrone.Api
{
public abstract class NzbDroneApiModule : RadarrModule
{
protected NzbDroneApiModule(string resource)
: base("/api/" + resource.Trim('/'))
{
}
}
}

View File

@ -1,12 +0,0 @@
using Radarr.Http;
namespace NzbDrone.Api
{
public abstract class NzbDroneFeedModule : RadarrModule
{
protected NzbDroneFeedModule(string resource)
: base("/feed/" + resource.Trim('/'))
{
}
}
}

View File

@ -1,50 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Api.Movies;
using NzbDrone.Core.Parser;
using Radarr.Http;
namespace NzbDrone.Api.Parse
{
public class ParseModule : RadarrRestModule<ParseResource>
{
private readonly IParsingService _parsingService;
public ParseModule(IParsingService parsingService)
{
_parsingService = parsingService;
GetResourceSingle = Parse;
}
private ParseResource Parse()
{
var title = Request.Query.Title.Value as string;
var parsedMovieInfo = _parsingService.ParseMovieInfo(title, new List<object>());
if (parsedMovieInfo == null)
{
return null;
}
var remoteMovie = _parsingService.Map(parsedMovieInfo, "");
if (remoteMovie != null)
{
return new ParseResource
{
Title = title,
ParsedMovieInfo = remoteMovie.RemoteMovie.ParsedMovieInfo,
Movie = remoteMovie.Movie.ToResource()
};
}
else
{
return new ParseResource
{
Title = title,
ParsedMovieInfo = parsedMovieInfo
};
}
}
}
}

View File

@ -1,13 +0,0 @@
using NzbDrone.Api.Movies;
using NzbDrone.Core.Parser.Model;
using Radarr.Http.REST;
namespace NzbDrone.Api.Parse
{
public class ParseResource : RestResource
{
public string Title { get; set; }
public ParsedMovieInfo ParsedMovieInfo { get; set; }
public MovieResource Movie { get; set; }
}
}

View File

@ -1,73 +0,0 @@
using System.Collections.Generic;
using FluentValidation;
using NzbDrone.Core.Profiles.Delay;
using Radarr.Http;
using Radarr.Http.REST;
using Radarr.Http.Validation;
namespace NzbDrone.Api.Profiles.Delay
{
public class DelayProfileModule : RadarrRestModule<DelayProfileResource>
{
private readonly IDelayProfileService _delayProfileService;
public DelayProfileModule(IDelayProfileService delayProfileService, DelayProfileTagInUseValidator tagInUseValidator)
{
_delayProfileService = delayProfileService;
GetResourceAll = GetAll;
GetResourceById = GetById;
UpdateResource = Update;
CreateResource = Create;
DeleteResource = DeleteProfile;
SharedValidator.RuleFor(d => d.Tags).NotEmpty().When(d => d.Id != 1);
SharedValidator.RuleFor(d => d.Tags).EmptyCollection<DelayProfileResource, int>().When(d => d.Id == 1);
SharedValidator.RuleFor(d => d.Tags).SetValidator(tagInUseValidator);
SharedValidator.RuleFor(d => d.UsenetDelay).GreaterThanOrEqualTo(0);
SharedValidator.RuleFor(d => d.TorrentDelay).GreaterThanOrEqualTo(0);
SharedValidator.RuleFor(d => d).Custom((delayProfile, context) =>
{
if (!delayProfile.EnableUsenet && !delayProfile.EnableTorrent)
{
context.AddFailure("Either Usenet or Torrent should be enabled");
}
});
}
private int Create(DelayProfileResource resource)
{
var model = resource.ToModel();
model = _delayProfileService.Add(model);
return model.Id;
}
private void DeleteProfile(int id)
{
if (id == 1)
{
throw new MethodNotAllowedException("Cannot delete global delay profile");
}
_delayProfileService.Delete(id);
}
private void Update(DelayProfileResource resource)
{
var model = resource.ToModel();
_delayProfileService.Update(model);
}
private DelayProfileResource GetById(int id)
{
return _delayProfileService.Get(id).ToResource();
}
private List<DelayProfileResource> GetAll()
{
return _delayProfileService.All().ToResource();
}
}
}

View File

@ -1,72 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Profiles.Delay;
using Radarr.Http.REST;
namespace NzbDrone.Api.Profiles.Delay
{
public class DelayProfileResource : RestResource
{
public bool EnableUsenet { get; set; }
public bool EnableTorrent { get; set; }
public DownloadProtocol PreferredProtocol { get; set; }
public int UsenetDelay { get; set; }
public int TorrentDelay { get; set; }
public bool BypassIfHighestQuality { get; set; }
public int Order { get; set; }
public HashSet<int> Tags { get; set; }
}
public static class DelayProfileResourceMapper
{
public static DelayProfileResource ToResource(this DelayProfile model)
{
if (model == null)
{
return null;
}
return new DelayProfileResource
{
Id = model.Id,
EnableUsenet = model.EnableUsenet,
EnableTorrent = model.EnableTorrent,
PreferredProtocol = model.PreferredProtocol,
UsenetDelay = model.UsenetDelay,
TorrentDelay = model.TorrentDelay,
BypassIfHighestQuality = model.BypassIfHighestQuality,
Order = model.Order,
Tags = new HashSet<int>(model.Tags)
};
}
public static DelayProfile ToModel(this DelayProfileResource resource)
{
if (resource == null)
{
return null;
}
return new DelayProfile
{
Id = resource.Id,
EnableUsenet = resource.EnableUsenet,
EnableTorrent = resource.EnableTorrent,
PreferredProtocol = resource.PreferredProtocol,
UsenetDelay = resource.UsenetDelay,
TorrentDelay = resource.TorrentDelay,
BypassIfHighestQuality = resource.BypassIfHighestQuality,
Order = resource.Order,
Tags = new HashSet<int>(resource.Tags)
};
}
public static List<DelayProfileResource> ToResource(this IEnumerable<DelayProfile> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,40 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Languages;
using Radarr.Http;
namespace NzbDrone.Api.Profiles.Languages
{
public class LanguageModule : RadarrRestModule<LanguageResource>
{
public LanguageModule()
{
GetResourceAll = GetAll;
GetResourceById = GetById;
}
private LanguageResource GetById(int id)
{
var language = (Language)id;
return new LanguageResource
{
Id = (int)language,
Name = language.ToString()
};
}
private List<LanguageResource> GetAll()
{
return ((Language[])Enum.GetValues(typeof(Language)))
.Select(l => new LanguageResource
{
Id = (int)l,
Name = l.ToString()
})
.OrderBy(l => l.Name)
.ToList();
}
}
}

View File

@ -1,13 +0,0 @@
using System.Text.Json.Serialization;
using Radarr.Http.REST;
namespace NzbDrone.Api.Profiles.Languages
{
public class LanguageResource : RestResource
{
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public new int Id { get; set; }
public string Name { get; set; }
public string NameLower => Name.ToLowerInvariant();
}
}

View File

@ -1,34 +0,0 @@
using System.Text;
using Nancy;
namespace NzbDrone.Api.Profiles
{
public class LegacyProfileModule : NzbDroneApiModule
{
public LegacyProfileModule()
: base("qualityprofile")
{
Get("/", x =>
{
string queryString = ConvertQueryParams(Request.Query);
var url = string.Format("/api/profile?{0}", queryString);
return Response.AsRedirect(url);
});
}
private string ConvertQueryParams(DynamicDictionary query)
{
var sb = new StringBuilder();
foreach (var key in query)
{
var value = query[key];
sb.AppendFormat("&{0}={1}", key, value);
}
return sb.ToString().Trim('&');
}
}
}

View File

@ -1,67 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.CustomFormats;
using NzbDrone.Core.Profiles;
using Radarr.Http;
namespace NzbDrone.Api.Profiles
{
public class ProfileModule : RadarrRestModule<ProfileResource>
{
private readonly IProfileService _profileService;
private readonly ICustomFormatService _formatService;
public ProfileModule(IProfileService profileService, ICustomFormatService formatService)
{
_profileService = profileService;
_formatService = formatService;
SharedValidator.RuleFor(c => c.Name).NotEmpty();
SharedValidator.RuleFor(c => c.Cutoff).NotNull();
SharedValidator.RuleFor(c => c.Items).MustHaveAllowedQuality();
SharedValidator.RuleFor(c => c.FormatItems).Must(items =>
{
var all = _formatService.All().Select(f => f.Id).ToList();
var ids = items.Select(i => i.Format.Id);
return all.Except(ids).Empty();
}).WithMessage("All Custom Formats and no extra ones need to be present inside your Profile! Try refreshing your browser.");
GetResourceAll = GetAll;
GetResourceById = GetById;
UpdateResource = Update;
CreateResource = Create;
DeleteResource = DeleteProfile;
}
private int Create(ProfileResource resource)
{
var model = resource.ToModel();
return _profileService.Add(model).Id;
}
private void DeleteProfile(int id)
{
_profileService.Delete(id);
}
private void Update(ProfileResource resource)
{
var model = resource.ToModel();
_profileService.Update(model);
}
private ProfileResource GetById(int id)
{
return _profileService.Get(id).ToResource();
}
private List<ProfileResource> GetAll()
{
return _profileService.All().ToResource();
}
}
}

View File

@ -1,164 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.CustomFormats;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Profiles;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Profiles
{
public class ProfileResource : RestResource
{
public string Name { get; set; }
public Quality Cutoff { get; set; }
public List<ProfileQualityItemResource> Items { get; set; }
public int MinFormatScore { get; set; }
public int CutoffFormatScore { get; set; }
public List<ProfileFormatItemResource> FormatItems { get; set; }
public Language Language { get; set; }
}
public class ProfileQualityItemResource : RestResource
{
public Quality Quality { get; set; }
public bool Allowed { get; set; }
}
public class ProfileFormatItemResource : RestResource
{
public CustomFormatResource Format { get; set; }
public int Score { get; set; }
}
public static class ProfileResourceMapper
{
public static ProfileResource ToResource(this Profile model)
{
if (model == null)
{
return null;
}
var cutoffItem = model.Items.First(q =>
{
if (q.Id == model.Cutoff)
{
return true;
}
if (q.Quality == null)
{
return false;
}
return q.Quality.Id == model.Cutoff;
});
var cutoff = cutoffItem.Items == null || cutoffItem.Items.Empty()
? cutoffItem.Quality
: cutoffItem.Items.First().Quality;
return new ProfileResource
{
Id = model.Id,
Name = model.Name,
Cutoff = cutoff,
// Flatten groups so things don't explode
Items = model.Items.SelectMany(i =>
{
if (i == null)
{
return null;
}
if (i.Items.Any())
{
return i.Items.ConvertAll(ToResource);
}
return new List<ProfileQualityItemResource> { ToResource(i) };
}).ToList(),
MinFormatScore = model.MinFormatScore,
CutoffFormatScore = model.CutoffFormatScore,
FormatItems = model.FormatItems.ConvertAll(ToResource),
Language = model.Language
};
}
public static ProfileQualityItemResource ToResource(this ProfileQualityItem model)
{
if (model == null)
{
return null;
}
return new ProfileQualityItemResource
{
Quality = model.Quality,
Allowed = model.Allowed
};
}
public static ProfileFormatItemResource ToResource(this ProfileFormatItem model)
{
return new ProfileFormatItemResource
{
Format = model.Format.ToResource(),
Score = model.Score,
};
}
public static Profile ToModel(this ProfileResource resource)
{
if (resource == null)
{
return null;
}
return new Profile
{
Id = resource.Id,
Name = resource.Name,
Cutoff = resource.Cutoff.Id,
Items = resource.Items.ConvertAll(ToModel),
MinFormatScore = resource.MinFormatScore,
CutoffFormatScore = resource.CutoffFormatScore,
FormatItems = resource.FormatItems.ConvertAll(ToModel),
Language = resource.Language
};
}
public static ProfileQualityItem ToModel(this ProfileQualityItemResource resource)
{
if (resource == null)
{
return null;
}
return new ProfileQualityItem
{
Quality = (Quality)resource.Quality.Id,
Allowed = resource.Allowed
};
}
public static ProfileFormatItem ToModel(this ProfileFormatItemResource resource)
{
return new ProfileFormatItem
{
Format = resource.Format.ToModel(),
Score = resource.Score
};
}
public static List<ProfileResource> ToResource(this IEnumerable<Profile> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,51 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.CustomFormats;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Profiles;
using NzbDrone.Core.Qualities;
using Radarr.Http;
namespace NzbDrone.Api.Profiles
{
public class ProfileSchemaModule : RadarrRestModule<ProfileResource>
{
private readonly IQualityDefinitionService _qualityDefinitionService;
private readonly ICustomFormatService _formatService;
public ProfileSchemaModule(IQualityDefinitionService qualityDefinitionService, ICustomFormatService formatService)
: base("/profile/schema")
{
_qualityDefinitionService = qualityDefinitionService;
_formatService = formatService;
GetResourceAll = GetAll;
}
private List<ProfileResource> GetAll()
{
var items = _qualityDefinitionService.All()
.OrderBy(v => v.Weight)
.Select(v => new ProfileQualityItem { Quality = v.Quality, Allowed = false })
.ToList();
var formatItems = _formatService.All().Select(v => new ProfileFormatItem
{
Format = v,
Score = 0
}).ToList();
var profile = new Profile
{
Cutoff = Quality.Unknown.Id,
Items = items,
MinFormatScore = 0,
CutoffFormatScore = 0,
FormatItems = formatItems,
Language = Language.English
};
return new List<ProfileResource> { profile.ToResource() };
}
}
}

View File

@ -1,42 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using FluentValidation.Validators;
namespace NzbDrone.Api.Profiles
{
public static class ProfileValidation
{
public static IRuleBuilderOptions<T, IList<ProfileQualityItemResource>> MustHaveAllowedQuality<T>(this IRuleBuilder<T, IList<ProfileQualityItemResource>> ruleBuilder)
{
ruleBuilder.SetValidator(new NotEmptyValidator(null));
return ruleBuilder.SetValidator(new AllowedValidator<T>());
}
}
public class AllowedValidator<T> : PropertyValidator
{
public AllowedValidator()
: base("Must contain at least one allowed quality")
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
var list = context.PropertyValue as IList<ProfileQualityItemResource>;
if (list == null)
{
return false;
}
if (!list.Any(c => c.Allowed))
{
return false;
}
return true;
}
}
}

View File

@ -1,224 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using FluentValidation.Results;
using Nancy;
using NzbDrone.Common.Reflection;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.ThingiProvider;
using NzbDrone.Core.Validation;
using Radarr.Http;
using Radarr.Http.ClientSchema;
namespace NzbDrone.Api
{
public abstract class ProviderModuleBase<TProviderResource, TProvider, TProviderDefinition> : RadarrRestModule<TProviderResource>
where TProviderDefinition : ProviderDefinition, new()
where TProvider : IProvider
where TProviderResource : ProviderResource<TProviderResource>, new()
{
private readonly IProviderFactory<TProvider, TProviderDefinition> _providerFactory;
protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> providerFactory, string resource)
: base(resource)
{
_providerFactory = providerFactory;
Get("schema", x => GetTemplates());
Post("test", x => Test(ReadResourceFromRequest(true)));
Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true)));
GetResourceAll = GetAll;
GetResourceById = GetProviderById;
CreateResource = CreateProvider;
UpdateResource = UpdateProvider;
DeleteResource = DeleteProvider;
SharedValidator.RuleFor(c => c.Name).NotEmpty();
SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique");
SharedValidator.RuleFor(c => c.Implementation).NotEmpty();
SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty();
PostValidator.RuleFor(c => c.Fields).NotNull();
}
private TProviderResource GetProviderById(int id)
{
var definition = _providerFactory.Get(id);
_providerFactory.SetProviderCharacteristics(definition);
var resource = new TProviderResource();
MapToResource(resource, definition);
return resource;
}
private List<TProviderResource> GetAll()
{
var providerDefinitions = _providerFactory.All().OrderBy(p => p.ImplementationName);
var result = new List<TProviderResource>(providerDefinitions.Count());
foreach (var definition in providerDefinitions)
{
_providerFactory.SetProviderCharacteristics(definition);
var providerResource = new TProviderResource();
MapToResource(providerResource, definition);
result.Add(providerResource);
}
return result.OrderBy(p => p.Name).ToList();
}
private int CreateProvider(TProviderResource providerResource)
{
var providerDefinition = GetDefinition(providerResource, false);
if (providerDefinition.Enable)
{
Test(providerDefinition, false);
}
providerDefinition = _providerFactory.Create(providerDefinition);
return providerDefinition.Id;
}
private void UpdateProvider(TProviderResource providerResource)
{
var providerDefinition = GetDefinition(providerResource, false);
_providerFactory.Update(providerDefinition);
}
private TProviderDefinition GetDefinition(TProviderResource providerResource, bool includeWarnings = false, bool validate = true)
{
var definition = new TProviderDefinition();
MapToModel(definition, providerResource);
if (validate)
{
Validate(definition, includeWarnings);
}
return definition;
}
protected virtual void MapToResource(TProviderResource resource, TProviderDefinition definition)
{
resource.Id = definition.Id;
resource.Name = definition.Name;
resource.ImplementationName = definition.ImplementationName;
resource.Implementation = definition.Implementation;
resource.ConfigContract = definition.ConfigContract;
resource.Message = definition.Message;
resource.Fields = SchemaBuilder.ToSchema(definition.Settings);
//Radarr_Supported_{0} are custom build redirect pages; if passing a new var, create a new redirect
resource.InfoLink = string.Format("https://wiki.servarr.com/Radarr_Supported_{0}",
definition.Implementation.ToLower());
}
protected virtual void MapToModel(TProviderDefinition definition, TProviderResource resource)
{
definition.Id = resource.Id;
definition.Name = resource.Name;
definition.ImplementationName = resource.ImplementationName;
definition.Implementation = resource.Implementation;
definition.ConfigContract = resource.ConfigContract;
definition.Message = resource.Message;
var configContract = ReflectionExtensions.CoreAssembly.FindTypeByName(definition.ConfigContract);
definition.Settings = (IProviderConfig)SchemaBuilder.ReadFromSchema(resource.Fields, configContract);
}
private void DeleteProvider(int id)
{
_providerFactory.Delete(id);
}
private object GetTemplates()
{
var defaultDefinitions = _providerFactory.GetDefaultDefinitions().OrderBy(p => p.ImplementationName).ToList();
var result = new List<TProviderResource>(defaultDefinitions.Count);
foreach (var providerDefinition in defaultDefinitions)
{
var providerResource = new TProviderResource();
MapToResource(providerResource, providerDefinition);
var presetDefinitions = _providerFactory.GetPresetDefinitions(providerDefinition);
providerResource.Presets = presetDefinitions.Select(v =>
{
var presetResource = new TProviderResource();
MapToResource(presetResource, v);
return presetResource;
}).ToList();
result.Add(providerResource);
}
return result;
}
private object Test(TProviderResource providerResource)
{
// Don't validate when getting the definition so we can validate afterwards (avoids validation being skipped because the provider is disabled)
var providerDefinition = GetDefinition(providerResource, true, false);
Validate(providerDefinition, true);
Test(providerDefinition, true);
return "{}";
}
private object RequestAction(string action, TProviderResource providerResource)
{
var providerDefinition = GetDefinition(providerResource, true, false);
var query = ((IDictionary<string, object>)Request.Query.ToDictionary()).ToDictionary(k => k.Key, k => k.Value.ToString());
var data = _providerFactory.RequestAction(providerDefinition, action, query);
Response resp = data.ToJson();
resp.ContentType = "application/json";
return resp;
}
protected virtual void Validate(TProviderDefinition definition, bool includeWarnings)
{
var validationResult = definition.Settings.Validate();
VerifyValidationResult(validationResult, includeWarnings);
}
protected virtual void Test(TProviderDefinition definition, bool includeWarnings)
{
var validationResult = _providerFactory.Test(definition);
VerifyValidationResult(validationResult, includeWarnings);
}
protected void VerifyValidationResult(ValidationResult validationResult, bool includeWarnings)
{
var result = new NzbDroneValidationResult(validationResult.Errors);
if (includeWarnings && (!result.IsValid || result.HasWarnings))
{
throw new ValidationException(result.Failures);
}
if (!result.IsValid)
{
throw new ValidationException(result.Errors);
}
}
}
}

View File

@ -1,20 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.ThingiProvider;
using Radarr.Http.ClientSchema;
using Radarr.Http.REST;
namespace NzbDrone.Api
{
public class ProviderResource<T> : RestResource
{
public string Name { get; set; }
public List<Field> Fields { get; set; }
public string ImplementationName { get; set; }
public string Implementation { get; set; }
public string ConfigContract { get; set; }
public string InfoLink { get; set; }
public ProviderMessage Message { get; set; }
public List<T> Presets { get; set; }
}
}

View File

@ -1,49 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Qualities;
using Radarr.Http;
using Radarr.Http.REST;
namespace NzbDrone.Api.Qualities
{
public class QualityDefinitionModule : RadarrRestModule<QualityDefinitionResource>
{
private readonly IQualityDefinitionService _qualityDefinitionService;
private readonly IParsingService _parsingService;
public QualityDefinitionModule(IQualityDefinitionService qualityDefinitionService, IParsingService parsingService)
{
_qualityDefinitionService = qualityDefinitionService;
_parsingService = parsingService;
GetResourceAll = GetAll;
GetResourceById = GetById;
UpdateResource = Update;
CreateResource = Create;
}
private int Create(QualityDefinitionResource qualityDefinitionResource)
{
throw new BadRequestException("Not allowed!");
}
private void Update(QualityDefinitionResource resource)
{
var model = resource.ToModel();
_qualityDefinitionService.Update(model);
}
private QualityDefinitionResource GetById(int id)
{
return _qualityDefinitionService.GetById(id).ToResource();
}
private List<QualityDefinitionResource> GetAll()
{
return _qualityDefinitionService.All().ToResource();
}
}
}

View File

@ -1,71 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Qualities
{
public class QualityDefinitionResource : RestResource
{
public Quality Quality { get; set; }
public string Title { get; set; }
public int Weight { get; set; }
public double? MinSize { get; set; }
public double? MaxSize { get; set; }
}
public static class QualityDefinitionResourceMapper
{
public static QualityDefinitionResource ToResource(this QualityDefinition model)
{
if (model == null)
{
return null;
}
return new QualityDefinitionResource
{
Id = model.Id,
Quality = model.Quality,
Title = model.Title,
Weight = model.Weight,
MinSize = model.MinSize,
MaxSize = model.MaxSize,
};
}
public static QualityDefinition ToModel(this QualityDefinitionResource resource)
{
if (resource == null)
{
return null;
}
return new QualityDefinition
{
Id = resource.Id,
Quality = resource.Quality,
Title = resource.Title,
Weight = resource.Weight,
MinSize = resource.MinSize,
MaxSize = resource.MaxSize,
};
}
public static List<QualityDefinitionResource> ToResource(this IEnumerable<QualityDefinition> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,124 +0,0 @@
using System;
using Nancy;
using NzbDrone.Core.Download;
using NzbDrone.Core.Download.Pending;
using NzbDrone.Core.Download.TrackedDownloads;
using NzbDrone.Core.Queue;
using Radarr.Http;
using Radarr.Http.Extensions;
using Radarr.Http.REST;
namespace NzbDrone.Api.Queue
{
public class QueueActionModule : RadarrRestModule<QueueResource>
{
private readonly IQueueService _queueService;
private readonly ITrackedDownloadService _trackedDownloadService;
private readonly IFailedDownloadService _failedDownloadService;
private readonly IProvideDownloadClient _downloadClientProvider;
private readonly IPendingReleaseService _pendingReleaseService;
private readonly IDownloadService _downloadService;
public QueueActionModule(IQueueService queueService,
ITrackedDownloadService trackedDownloadService,
IFailedDownloadService failedDownloadService,
IProvideDownloadClient downloadClientProvider,
IPendingReleaseService pendingReleaseService,
IDownloadService downloadService)
{
_queueService = queueService;
_trackedDownloadService = trackedDownloadService;
_failedDownloadService = failedDownloadService;
_downloadClientProvider = downloadClientProvider;
_pendingReleaseService = pendingReleaseService;
_downloadService = downloadService;
Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id));
Post("/import", x => Import());
Post("/grab", x => Grab());
}
private object Remove(int id)
{
var blacklist = false;
var blacklistQuery = Request.Query.blacklist;
if (blacklistQuery.HasValue)
{
blacklist = Convert.ToBoolean(blacklistQuery.Value);
}
var pendingRelease = _pendingReleaseService.FindPendingQueueItem(id);
if (pendingRelease != null)
{
_pendingReleaseService.RemovePendingQueueItems(pendingRelease.Id);
return new object();
}
var trackedDownload = GetTrackedDownload(id);
if (trackedDownload == null)
{
throw new NotFoundException();
}
var downloadClient = _downloadClientProvider.Get(trackedDownload.DownloadClient);
if (downloadClient == null)
{
throw new BadRequestException();
}
downloadClient.RemoveItem(trackedDownload.DownloadItem, true);
if (blacklist)
{
_failedDownloadService.MarkAsFailed(trackedDownload.DownloadItem.DownloadId);
}
return new object();
}
private object Import()
{
throw new BadRequestException("No longer available");
}
private object Grab()
{
var resource = Request.Body.FromJson<QueueResource>();
var pendingRelease = _pendingReleaseService.FindPendingQueueItem(resource.Id);
if (pendingRelease == null)
{
throw new NotFoundException();
}
_downloadService.DownloadReport(pendingRelease.RemoteMovie);
return resource;
}
private TrackedDownload GetTrackedDownload(int queueId)
{
var queueItem = _queueService.Find(queueId);
if (queueItem == null)
{
throw new NotFoundException();
}
var trackedDownload = _trackedDownloadService.Find(queueItem.DownloadId);
if (trackedDownload == null)
{
throw new NotFoundException();
}
return trackedDownload;
}
}
}

View File

@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.Download.Pending;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Queue;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.Queue
{
public class QueueModule : RadarrRestModuleWithSignalR<QueueResource, Core.Queue.Queue>,
IHandle<QueueUpdatedEvent>, IHandle<PendingReleasesUpdatedEvent>
{
private readonly IQueueService _queueService;
private readonly IPendingReleaseService _pendingReleaseService;
public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService)
: base(broadcastSignalRMessage)
{
_queueService = queueService;
_pendingReleaseService = pendingReleaseService;
GetResourceAll = GetQueue;
}
private List<QueueResource> GetQueue()
{
return GetQueueItems().ToResource();
}
private IEnumerable<Core.Queue.Queue> GetQueueItems()
{
var queue = _queueService.GetQueue();
var pending = _pendingReleaseService.GetPendingQueue();
return queue.Concat(pending);
}
public void Handle(QueueUpdatedEvent message)
{
BroadcastResourceChange(ModelAction.Sync);
}
public void Handle(PendingReleasesUpdatedEvent message)
{
BroadcastResourceChange(ModelAction.Sync);
}
}
}

View File

@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Api.Movies;
using NzbDrone.Core.Download.TrackedDownloads;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Qualities;
using Radarr.Http.REST;
namespace NzbDrone.Api.Queue
{
public class QueueResource : RestResource
{
public MovieResource Movie { get; set; }
public QualityModel Quality { get; set; }
public decimal Size { get; set; }
public string Title { get; set; }
public decimal Sizeleft { get; set; }
public TimeSpan? Timeleft { get; set; }
public DateTime? EstimatedCompletionTime { get; set; }
public string Status { get; set; }
public string TrackedDownloadStatus { get; set; }
public List<TrackedDownloadStatusMessage> StatusMessages { get; set; }
public string DownloadId { get; set; }
public DownloadProtocol Protocol { get; set; }
}
public static class QueueResourceMapper
{
public static QueueResource ToResource(this Core.Queue.Queue model)
{
if (model == null)
{
return null;
}
return new QueueResource
{
Id = model.Id,
Quality = model.Quality,
Size = model.Size,
Title = model.Title,
Sizeleft = model.Sizeleft,
Timeleft = model.Timeleft,
EstimatedCompletionTime = model.EstimatedCompletionTime,
Status = model.Status,
TrackedDownloadStatus = model.TrackedDownloadStatus.ToString(),
StatusMessages = model.StatusMessages,
DownloadId = model.DownloadId,
Protocol = model.Protocol,
Movie = model.Movie.ToResource()
};
}
public static List<QueueResource> ToResource(this IEnumerable<Core.Queue.Queue> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="8.6.2" />
<PackageReference Include="Ical.Net" Version="4.1.11" />
<PackageReference Include="Nancy" Version="2.0.0" />
<PackageReference Include="Nancy.Authentication.Basic" Version="2.0.0" />
<PackageReference Include="Nancy.Authentication.Forms" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NzbDrone.Core\Radarr.Core.csproj" />
<ProjectReference Include="..\Radarr.Http\Radarr.Http.csproj" />
</ItemGroup>
</Project>

View File

@ -1,68 +0,0 @@
using System.Collections.Generic;
using FluentValidation;
using NzbDrone.Core.RemotePathMappings;
using NzbDrone.Core.Validation.Paths;
using Radarr.Http;
namespace NzbDrone.Api.RemotePathMappings
{
public class RemotePathMappingModule : RadarrRestModule<RemotePathMappingResource>
{
private readonly IRemotePathMappingService _remotePathMappingService;
public RemotePathMappingModule(IRemotePathMappingService remotePathMappingService,
PathExistsValidator pathExistsValidator,
MappedNetworkDriveValidator mappedNetworkDriveValidator)
{
_remotePathMappingService = remotePathMappingService;
GetResourceAll = GetMappings;
GetResourceById = GetMappingById;
CreateResource = CreateMapping;
DeleteResource = DeleteMapping;
UpdateResource = UpdateMapping;
SharedValidator.RuleFor(c => c.Host)
.NotEmpty();
// We cannot use IsValidPath here, because it's a remote path, possibly other OS.
SharedValidator.RuleFor(c => c.RemotePath)
.NotEmpty();
SharedValidator.RuleFor(c => c.LocalPath)
.Cascade(CascadeMode.StopOnFirstFailure)
.IsValidPath()
.SetValidator(mappedNetworkDriveValidator)
.SetValidator(pathExistsValidator);
}
private RemotePathMappingResource GetMappingById(int id)
{
return _remotePathMappingService.Get(id).ToResource();
}
private int CreateMapping(RemotePathMappingResource resource)
{
var model = resource.ToModel();
return _remotePathMappingService.Add(model).Id;
}
private List<RemotePathMappingResource> GetMappings()
{
return _remotePathMappingService.All().ToResource();
}
private void DeleteMapping(int id)
{
_remotePathMappingService.Remove(id);
}
private void UpdateMapping(RemotePathMappingResource resource)
{
var mapping = resource.ToModel();
_remotePathMappingService.Update(mapping);
}
}
}

View File

@ -1,56 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.RemotePathMappings;
using Radarr.Http.REST;
namespace NzbDrone.Api.RemotePathMappings
{
public class RemotePathMappingResource : RestResource
{
public string Host { get; set; }
public string RemotePath { get; set; }
public string LocalPath { get; set; }
}
public static class RemotePathMappingResourceMapper
{
public static RemotePathMappingResource ToResource(this RemotePathMapping model)
{
if (model == null)
{
return null;
}
return new RemotePathMappingResource
{
Id = model.Id,
Host = model.Host,
RemotePath = model.RemotePath,
LocalPath = model.LocalPath
};
}
public static RemotePathMapping ToModel(this RemotePathMappingResource resource)
{
if (resource == null)
{
return null;
}
return new RemotePathMapping
{
Id = resource.Id,
Host = resource.Host,
RemotePath = resource.RemotePath,
LocalPath = resource.LocalPath
};
}
public static List<RemotePathMappingResource> ToResource(this IEnumerable<RemotePathMapping> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,56 +0,0 @@
using System.Collections.Generic;
using FluentValidation;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Restrictions;
namespace Radarr.Http.RESTrictions
{
public class RestrictionModule : RadarrRestModule<RestrictionResource>
{
private readonly IRestrictionService _restrictionService;
public RestrictionModule(IRestrictionService restrictionService)
{
_restrictionService = restrictionService;
GetResourceById = GetRestriction;
GetResourceAll = GetAllRestrictions;
CreateResource = CreateRestriction;
UpdateResource = UpdateRestriction;
DeleteResource = DeleteRestriction;
SharedValidator.RuleFor(r => r).Custom((restriction, context) =>
{
if (restriction.Ignored.IsNullOrWhiteSpace() && restriction.Required.IsNullOrWhiteSpace())
{
context.AddFailure("Either 'Must contain' or 'Must not contain' is required");
}
});
}
private RestrictionResource GetRestriction(int id)
{
return _restrictionService.Get(id).ToResource();
}
private List<RestrictionResource> GetAllRestrictions()
{
return _restrictionService.All().ToResource();
}
private int CreateRestriction(RestrictionResource resource)
{
return _restrictionService.Add(resource.ToModel()).Id;
}
private void UpdateRestriction(RestrictionResource resource)
{
_restrictionService.Update(resource.ToModel());
}
private void DeleteRestriction(int id)
{
_restrictionService.Delete(id);
}
}
}

View File

@ -1,64 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.Restrictions;
using Radarr.Http.REST;
namespace Radarr.Http.RESTrictions
{
public class RestrictionResource : RestResource
{
public string Required { get; set; }
public string Preferred { get; set; }
public string Ignored { get; set; }
public HashSet<int> Tags { get; set; }
public RestrictionResource()
{
Tags = new HashSet<int>();
}
}
public static class RestrictionResourceMapper
{
public static RestrictionResource ToResource(this Restriction model)
{
if (model == null)
{
return null;
}
return new RestrictionResource
{
Id = model.Id,
Required = model.Required,
Preferred = model.Preferred,
Ignored = model.Ignored,
Tags = new HashSet<int>(model.Tags)
};
}
public static Restriction ToModel(this RestrictionResource resource)
{
if (resource == null)
{
return null;
}
return new Restriction
{
Id = resource.Id,
Required = resource.Required,
Preferred = resource.Preferred,
Ignored = resource.Ignored,
Tags = new HashSet<int>(resource.Tags)
};
}
public static List<RestrictionResource> ToResource(this IEnumerable<Restriction> models)
{
return models.Select(ToResource).ToList();
}
}
}

View File

@ -1,66 +0,0 @@
using System.Collections.Generic;
using FluentValidation;
using NzbDrone.Core.RootFolders;
using NzbDrone.Core.Validation.Paths;
using NzbDrone.SignalR;
using Radarr.Http;
namespace NzbDrone.Api.RootFolders
{
public class RootFolderModule : RadarrRestModuleWithSignalR<RootFolderResource, RootFolder>
{
private readonly IRootFolderService _rootFolderService;
public RootFolderModule(IRootFolderService rootFolderService,
IBroadcastSignalRMessage signalRBroadcaster,
RootFolderValidator rootFolderValidator,
PathExistsValidator pathExistsValidator,
MappedNetworkDriveValidator mappedNetworkDriveValidator,
RecycleBinValidator recycleBinValidator,
StartupFolderValidator startupFolderValidator,
SystemFolderValidator systemFolderValidator,
FolderWritableValidator folderWritableValidator)
: base(signalRBroadcaster)
{
_rootFolderService = rootFolderService;
GetResourceAll = GetRootFolders;
GetResourceById = GetRootFolder;
CreateResource = CreateRootFolder;
DeleteResource = DeleteFolder;
SharedValidator.RuleFor(c => c.Path)
.Cascade(CascadeMode.StopOnFirstFailure)
.IsValidPath()
.SetValidator(rootFolderValidator)
.SetValidator(mappedNetworkDriveValidator)
.SetValidator(startupFolderValidator)
.SetValidator(recycleBinValidator)
.SetValidator(pathExistsValidator)
.SetValidator(systemFolderValidator)
.SetValidator(folderWritableValidator);
}
private RootFolderResource GetRootFolder(int id)
{
return _rootFolderService.Get(id, true).ToResource();
}
private int CreateRootFolder(RootFolderResource rootFolderResource)
{
var model = rootFolderResource.ToModel();
return _rootFolderService.Add(model).Id;
}
private List<RootFolderResource> GetRootFolders()
{
return _rootFolderService.AllWithUnmappedFolders().ToResource();
}
private void DeleteFolder(int id)
{
_rootFolderService.Remove(id);
}
}
}

View File

@ -1,59 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Core.RootFolders;
using Radarr.Http.REST;
namespace NzbDrone.Api.RootFolders
{
public class RootFolderResource : RestResource
{
public string Path { get; set; }
public long? FreeSpace { get; set; }
public long? TotalSpace { get; set; }
public List<UnmappedFolder> UnmappedFolders { get; set; }
}
public static class RootFolderResourceMapper
{
public static RootFolderResource ToResource(this RootFolder model)
{
if (model == null)
{
return null;
}
return new RootFolderResource
{
Id = model.Id,
Path = model.Path,
FreeSpace = model.FreeSpace,
TotalSpace = model.TotalSpace,
UnmappedFolders = model.UnmappedFolders
};
}
public static RootFolder ToModel(this RootFolderResource resource)
{
if (resource == null)
{
return null;
}
return new RootFolder
{
Id = resource.Id,
Path = resource.Path,
FreeSpace = resource.FreeSpace,
UnmappedFolders = resource.UnmappedFolders
};
}
public static List<RootFolderResource> ToResource(this IEnumerable<RootFolder> models)
{
return models.Select(ToResource).ToList();
}
}
}

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