Commands return immediately and signalr is used to control the UI

This commit is contained in:
Mark McDowall 2013-08-30 20:08:19 -07:00
parent 772ab3c921
commit c96ba5efd3
55 changed files with 439 additions and 238 deletions

View File

@ -0,0 +1,42 @@
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using NzbDrone.Api.SignalR;
using NzbDrone.Common.Messaging;
using NzbDrone.Common.Messaging.Events;
using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Api.Commands
{
public class CommandConnection : NzbDronePersistentConnection,
IHandleAsync<CommandStartedEvent>,
IHandleAsync<CommandCompletedEvent>,
IHandle<CommandFailedEvent>
{
public override string Resource
{
get { return "/Command"; }
}
public void HandleAsync(CommandStartedEvent message)
{
BroadcastMessage(message.Command);
}
public void HandleAsync(CommandCompletedEvent message)
{
BroadcastMessage(message.Command);
}
public void Handle(CommandFailedEvent message)
{
BroadcastMessage(message.Command);
}
private void BroadcastMessage(TrackedCommand trackedCommand)
{
var context = ((ConnectionManager)GlobalHost.ConnectionManager).GetConnection(GetType());
context.Connection.Broadcast(trackedCommand);
}
}
}

View File

@ -2,6 +2,7 @@
using System.Linq; using System.Linq;
using Nancy; using Nancy;
using NzbDrone.Api.Extensions; using NzbDrone.Api.Extensions;
using NzbDrone.Api.Mapping;
using NzbDrone.Common.Composition; using NzbDrone.Common.Composition;
using NzbDrone.Common.Messaging; using NzbDrone.Common.Messaging;
using NzbDrone.Common.Messaging.Tracking; using NzbDrone.Common.Messaging.Tracking;
@ -32,9 +33,10 @@ namespace NzbDrone.Api.Commands
.Equals(resource.Command, StringComparison.InvariantCultureIgnoreCase)); .Equals(resource.Command, StringComparison.InvariantCultureIgnoreCase));
dynamic command = Request.Body.FromJson(commandType); dynamic command = Request.Body.FromJson(commandType);
_messageAggregator.PublishCommand(command);
return resource.AsResponse(HttpStatusCode.Created); var response = (TrackedCommand) _messageAggregator.PublishCommandAsync(command);
return response.AsResponse(HttpStatusCode.Created);
} }
private Response GetAllCommands() private Response GetAllCommands()

View File

@ -12,7 +12,6 @@ namespace NzbDrone.Api.Extensions
{ {
private static readonly NancyJsonSerializer NancySerializer = new NancyJsonSerializer(); private static readonly NancyJsonSerializer NancySerializer = new NancyJsonSerializer();
public static readonly string LastModified = BuildInfo.BuildDateTime.ToString("r"); public static readonly string LastModified = BuildInfo.BuildDateTime.ToString("r");
public static T FromJson<T>(this Stream body) where T : class, new() public static T FromJson<T>(this Stream body) where T : class, new()
@ -25,7 +24,6 @@ namespace NzbDrone.Api.Extensions
return (T)FromJson(body, type); return (T)FromJson(body, type);
} }
public static object FromJson(this Stream body, Type type) public static object FromJson(this Stream body, Type type)
{ {
var reader = new StreamReader(body, true); var reader = new StreamReader(body, true);

View File

@ -83,6 +83,7 @@
<Compile Include="ClientSchema\SelectOption.cs" /> <Compile Include="ClientSchema\SelectOption.cs" />
<Compile Include="Commands\CommandModule.cs" /> <Compile Include="Commands\CommandModule.cs" />
<Compile Include="Commands\CommandResource.cs" /> <Compile Include="Commands\CommandResource.cs" />
<Compile Include="Commands\CommandConnection.cs" />
<Compile Include="Config\NamingConfigResource.cs" /> <Compile Include="Config\NamingConfigResource.cs" />
<Compile Include="Config\NamingModule.cs" /> <Compile Include="Config\NamingModule.cs" />
<Compile Include="EpisodeFiles\EpisodeFileModule.cs" /> <Compile Include="EpisodeFiles\EpisodeFileModule.cs" />

View File

@ -76,7 +76,7 @@ namespace NzbDrone.Common.Test.EventingTests
public class CommandA : ICommand public class CommandA : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
// ReSharper disable UnusedParameter.Local // ReSharper disable UnusedParameter.Local
public CommandA(int id = 0) public CommandA(int id = 0)
// ReSharper restore UnusedParameter.Local // ReSharper restore UnusedParameter.Local
@ -87,7 +87,7 @@ namespace NzbDrone.Common.Test.EventingTests
public class CommandB : ICommand public class CommandB : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public CommandB() public CommandB()
{ {

View File

@ -1,10 +1,12 @@
namespace NzbDrone.Common.Messaging.Events using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Common.Messaging.Events
{ {
public class CommandCompletedEvent : IEvent public class CommandCompletedEvent : IEvent
{ {
public ICommand Command { get; private set; } public TrackedCommand Command { get; private set; }
public CommandCompletedEvent(ICommand command) public CommandCompletedEvent(TrackedCommand command)
{ {
Command = command; Command = command;
} }

View File

@ -1,10 +1,12 @@
namespace NzbDrone.Common.Messaging.Events using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Common.Messaging.Events
{ {
public class CommandExecutedEvent : IEvent public class CommandExecutedEvent : IEvent
{ {
public ICommand Command { get; private set; } public TrackedCommand Command { get; private set; }
public CommandExecutedEvent(ICommand command) public CommandExecutedEvent(TrackedCommand command)
{ {
Command = command; Command = command;
} }

View File

@ -1,13 +1,14 @@
using System; using System;
using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Common.Messaging.Events namespace NzbDrone.Common.Messaging.Events
{ {
public class CommandFailedEvent : IEvent public class CommandFailedEvent : IEvent
{ {
public ICommand Command { get; private set; } public TrackedCommand Command { get; private set; }
public Exception Exception { get; private set; } public Exception Exception { get; private set; }
public CommandFailedEvent(ICommand command, Exception exception) public CommandFailedEvent(TrackedCommand command, Exception exception)
{ {
Command = command; Command = command;
Exception = exception; Exception = exception;

View File

@ -1,10 +1,12 @@
namespace NzbDrone.Common.Messaging.Events using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Common.Messaging.Events
{ {
public class CommandStartedEvent : IEvent public class CommandStartedEvent : IEvent
{ {
public ICommand Command { get; private set; } public TrackedCommand Command { get; private set; }
public CommandStartedEvent(ICommand command) public CommandStartedEvent(TrackedCommand command)
{ {
Command = command; Command = command;
} }

View File

@ -1,4 +1,6 @@
namespace NzbDrone.Common.Messaging using NzbDrone.Common.Messaging.Tracking;
namespace NzbDrone.Common.Messaging
{ {
/// <summary> /// <summary>
/// Enables loosely-coupled publication of events. /// Enables loosely-coupled publication of events.
@ -7,6 +9,8 @@
{ {
void PublishEvent<TEvent>(TEvent @event) where TEvent : class, IEvent; void PublishEvent<TEvent>(TEvent @event) where TEvent : class, IEvent;
void PublishCommand<TCommand>(TCommand command) where TCommand : class, ICommand; void PublishCommand<TCommand>(TCommand command) where TCommand : class, ICommand;
void PublishCommand(string commandType); void PublishCommand(string commandTypeName);
TrackedCommand PublishCommandAsync<TCommand>(TCommand command) where TCommand : class, ICommand;
TrackedCommand PublishCommandAsync(string commandTypeName);
} }
} }

View File

@ -78,20 +78,9 @@ namespace NzbDrone.Common.Messaging
{ {
Ensure.That(() => command).IsNotNull(); Ensure.That(() => command).IsNotNull();
var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType());
_logger.Trace("Publishing {0}", command.GetType().Name); _logger.Trace("Publishing {0}", command.GetType().Name);
var handler = (IExecute<TCommand>)_serviceFactory.Build(handlerContract); var trackedCommand = _trackCommands.TrackIfNew(command);
_logger.Debug("{0} -> {1}", command.GetType().Name, handler.GetType().Name);
var sw = Stopwatch.StartNew();
TrackedCommand trackedCommand = null;
try
{
trackedCommand = _trackCommands.TrackIfNew(command);
if (trackedCommand == null) if (trackedCommand == null)
{ {
@ -99,40 +88,84 @@ namespace NzbDrone.Common.Messaging
return; return;
} }
MappedDiagnosticsContext.Set("CommandId", trackedCommand.Command.CommandId); ExecuteCommand<TCommand>(trackedCommand);
PublishEvent(new CommandStartedEvent(command));
handler.Execute(command);
sw.Stop();
_trackCommands.Completed(trackedCommand, sw.Elapsed);
PublishEvent(new CommandCompletedEvent(command));
}
catch (Exception e)
{
if (trackedCommand != null)
{
_trackCommands.Failed(trackedCommand, e);
}
PublishEvent(new CommandFailedEvent(command, e));
throw;
}
finally
{
PublishEvent(new CommandExecutedEvent(command));
}
_logger.Debug("{0} <- {1} [{2}]", command.GetType().Name, handler.GetType().Name, sw.Elapsed.ToString(""));
} }
public void PublishCommand(string commandTypeName) public void PublishCommand(string commandTypeName)
{
dynamic command = GetCommand(commandTypeName);
PublishCommand(command);
}
public TrackedCommand PublishCommandAsync<TCommand>(TCommand command) where TCommand : class, ICommand
{
Ensure.That(() => command).IsNotNull();
_logger.Trace("Publishing {0}", command.GetType().Name);
var existingCommand = _trackCommands.TrackNewOrGet(command);
if (existingCommand.Existing)
{
_logger.Info("Command is already in progress: {0}", command.GetType().Name);
return existingCommand.TrackedCommand;
}
_taskFactory.StartNew(() => ExecuteCommand<TCommand>(existingCommand.TrackedCommand)
, TaskCreationOptions.PreferFairness)
.LogExceptions();
return existingCommand.TrackedCommand;
}
public TrackedCommand PublishCommandAsync(string commandTypeName)
{
dynamic command = GetCommand(commandTypeName);
return PublishCommandAsync(command);
}
private dynamic GetCommand(string commandTypeName)
{ {
var commandType = _serviceFactory.GetImplementations(typeof(ICommand)) var commandType = _serviceFactory.GetImplementations(typeof(ICommand))
.Single(c => c.FullName.Equals(commandTypeName, StringComparison.InvariantCultureIgnoreCase)); .Single(c => c.FullName.Equals(commandTypeName, StringComparison.InvariantCultureIgnoreCase));
dynamic command = Json.Deserialize("{}", commandType); return Json.Deserialize("{}", commandType);
PublishCommand(command); }
private void ExecuteCommand<TCommand>(TrackedCommand trackedCommand) where TCommand : class, ICommand
{
var command = (TCommand)trackedCommand.Command;
var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType());
var handler = (IExecute<TCommand>)_serviceFactory.Build(handlerContract);
_logger.Debug("{0} -> {1}", command.GetType().Name, handler.GetType().Name);
var sw = Stopwatch.StartNew();
try
{
MappedDiagnosticsContext.Set("CommandId", trackedCommand.Command.CommandId);
PublishEvent(new CommandStartedEvent(trackedCommand));
handler.Execute(command);
sw.Stop();
_trackCommands.Completed(trackedCommand, sw.Elapsed);
PublishEvent(new CommandCompletedEvent(trackedCommand));
}
catch (Exception e)
{
_trackCommands.Failed(trackedCommand, e);
PublishEvent(new CommandFailedEvent(trackedCommand, e));
throw;
}
finally
{
PublishEvent(new CommandExecutedEvent(trackedCommand));
}
_logger.Debug("{0} <- {1} [{2}]", command.GetType().Name, handler.GetType().Name, sw.Elapsed.ToString(""));
} }
} }
} }

View File

@ -5,7 +5,7 @@ namespace NzbDrone.Common.Messaging
public class TestCommand : ICommand public class TestCommand : ICommand
{ {
public int Duration { get; set; } public int Duration { get; set; }
public String CommandId { get; set; } public String CommandId { get; private set; }
public TestCommand() public TestCommand()
{ {

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Remoting;
using NzbDrone.Common.Cache; using NzbDrone.Common.Cache;
namespace NzbDrone.Common.Messaging.Tracking namespace NzbDrone.Common.Messaging.Tracking
@ -8,10 +9,12 @@ namespace NzbDrone.Common.Messaging.Tracking
public interface ITrackCommands public interface ITrackCommands
{ {
TrackedCommand TrackIfNew(ICommand command); TrackedCommand TrackIfNew(ICommand command);
ExistingCommand TrackNewOrGet(ICommand command);
TrackedCommand Completed(TrackedCommand trackedCommand, TimeSpan runtime); TrackedCommand Completed(TrackedCommand trackedCommand, TimeSpan runtime);
TrackedCommand Failed(TrackedCommand trackedCommand, Exception e); TrackedCommand Failed(TrackedCommand trackedCommand, Exception e);
List<TrackedCommand> AllTracked(); List<TrackedCommand> AllTracked();
Boolean ExistingCommand(ICommand command); Boolean ExistingCommand(ICommand command);
TrackedCommand FindExisting(ICommand command);
} }
public class TrackCommands : ITrackCommands, IExecute<TrackedCommandCleanupCommand> public class TrackCommands : ITrackCommands, IExecute<TrackedCommandCleanupCommand>
@ -36,6 +39,21 @@ namespace NzbDrone.Common.Messaging.Tracking
return trackedCommand; return trackedCommand;
} }
public ExistingCommand TrackNewOrGet(ICommand command)
{
var trackedCommand = FindExisting(command);
if (trackedCommand == null)
{
trackedCommand = new TrackedCommand(command, CommandState.Running);
Store(trackedCommand);
return new ExistingCommand(false, trackedCommand);
}
return new ExistingCommand(true, trackedCommand);
}
public TrackedCommand Completed(TrackedCommand trackedCommand, TimeSpan runtime) public TrackedCommand Completed(TrackedCommand trackedCommand, TimeSpan runtime)
{ {
trackedCommand.StateChangeTime = DateTime.UtcNow; trackedCommand.StateChangeTime = DateTime.UtcNow;
@ -65,11 +83,25 @@ namespace NzbDrone.Common.Messaging.Tracking
public bool ExistingCommand(ICommand command) public bool ExistingCommand(ICommand command)
{ {
var running = AllTracked().Where(i => i.Type == command.GetType().FullName && i.State == CommandState.Running); return FindExisting(command) != null;
}
var result = running.Select(r => r.Command).Contains(command, new CommandEqualityComparer()); public TrackedCommand FindExisting(ICommand command)
{
var comparer = new CommandEqualityComparer();
return Running(command.GetType()).SingleOrDefault(t => comparer.Equals(t.Command, command));
}
return result; private List<TrackedCommand> Running(Type type = null)
{
var running = AllTracked().Where(i => i.State == CommandState.Running);
if (type != null)
{
return running.Where(t => t.Type == type.FullName).ToList();
}
return running.ToList();
} }
private void Store(TrackedCommand trackedCommand) private void Store(TrackedCommand trackedCommand)
@ -84,7 +116,7 @@ namespace NzbDrone.Common.Messaging.Tracking
public void Execute(TrackedCommandCleanupCommand message) public void Execute(TrackedCommandCleanupCommand message)
{ {
var old = AllTracked().Where(c => c.StateChangeTime < DateTime.UtcNow.AddMinutes(-15)); var old = AllTracked().Where(c => c.State != CommandState.Running && c.StateChangeTime < DateTime.UtcNow.AddMinutes(-5));
foreach (var trackedCommand in old) foreach (var trackedCommand in old)
{ {

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NzbDrone.Common.Messaging.Tracking
{
public class ExistingCommand
{
public Boolean Existing { get; set; }
public TrackedCommand TrackedCommand { get; set; }
public ExistingCommand(Boolean exisitng, TrackedCommand trackedCommand)
{
Existing = exisitng;
TrackedCommand = trackedCommand;
}
}
}

View File

@ -4,6 +4,8 @@ namespace NzbDrone.Common.Messaging.Tracking
{ {
public class TrackedCommand public class TrackedCommand
{ {
public String Id { get; private set; }
public String Name { get; private set; }
public String Type { get; private set; } public String Type { get; private set; }
public ICommand Command { get; private set; } public ICommand Command { get; private set; }
public CommandState State { get; set; } public CommandState State { get; set; }
@ -13,6 +15,8 @@ namespace NzbDrone.Common.Messaging.Tracking
public TrackedCommand(ICommand command, CommandState state) public TrackedCommand(ICommand command, CommandState state)
{ {
Id = command.CommandId;
Name = command.GetType().Name;
Type = command.GetType().FullName; Type = command.GetType().FullName;
Command = command; Command = command;
State = state; State = state;

View File

@ -93,6 +93,7 @@
<Compile Include="Instrumentation\GlobalExceptionHandlers.cs" /> <Compile Include="Instrumentation\GlobalExceptionHandlers.cs" />
<Compile Include="Instrumentation\ExceptronTarget.cs" /> <Compile Include="Instrumentation\ExceptronTarget.cs" />
<Compile Include="Messaging\Tracking\CommandTrackingService.cs" /> <Compile Include="Messaging\Tracking\CommandTrackingService.cs" />
<Compile Include="Messaging\Tracking\ExistingCommand.cs" />
<Compile Include="Messaging\Tracking\TrackedCommand.cs" /> <Compile Include="Messaging\Tracking\TrackedCommand.cs" />
<Compile Include="Messaging\Events\CommandStartedEvent.cs" /> <Compile Include="Messaging\Events\CommandStartedEvent.cs" />
<Compile Include="Messaging\CommandEqualityComparer.cs" /> <Compile Include="Messaging\CommandEqualityComparer.cs" />

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.DataAugmentation.Scene
{ {
public class UpdateSceneMappingCommand : ICommand public class UpdateSceneMappingCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public UpdateSceneMappingCommand() public UpdateSceneMappingCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.IndexerSearch
{ {
public class EpisodeSearchCommand : ICommand public class EpisodeSearchCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int EpisodeId { get; set; } public int EpisodeId { get; set; }
public EpisodeSearchCommand() public EpisodeSearchCommand()

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.IndexerSearch
{ {
public class SeasonSearchCommand : ICommand public class SeasonSearchCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int SeriesId { get; set; } public int SeriesId { get; set; }
public int SeasonNumber { get; set; } public int SeasonNumber { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.IndexerSearch
{ {
public class SeriesSearchCommand : ICommand public class SeriesSearchCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int SeriesId { get; set; } public int SeriesId { get; set; }
public SeriesSearchCommand() public SeriesSearchCommand()

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Indexers
{ {
public class RssSyncCommand : ICommand public class RssSyncCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public RssSyncCommand() public RssSyncCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Instrumentation.Commands
{ {
public class ClearLogCommand : ICommand public class ClearLogCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public ClearLogCommand() public ClearLogCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Instrumentation.Commands
{ {
public class DeleteLogFilesCommand : ICommand public class DeleteLogFilesCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public DeleteLogFilesCommand() public DeleteLogFilesCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Instrumentation.Commands
{ {
public class TrimLogCommand : ICommand public class TrimLogCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public TrimLogCommand() public TrimLogCommand()
{ {

View File

@ -50,7 +50,7 @@ namespace NzbDrone.Core.Jobs
new ScheduledTask{ Interval = 1, TypeName = typeof(DownloadedEpisodesScanCommand).FullName}, new ScheduledTask{ Interval = 1, TypeName = typeof(DownloadedEpisodesScanCommand).FullName},
new ScheduledTask{ Interval = 60, TypeName = typeof(ApplicationUpdateCommand).FullName}, new ScheduledTask{ Interval = 60, TypeName = typeof(ApplicationUpdateCommand).FullName},
new ScheduledTask{ Interval = 1*60, TypeName = typeof(TrimLogCommand).FullName}, new ScheduledTask{ Interval = 1*60, TypeName = typeof(TrimLogCommand).FullName},
new ScheduledTask{ Interval = 5, TypeName = typeof(TrackedCommandCleanupCommand).FullName} new ScheduledTask{ Interval = 1, TypeName = typeof(TrackedCommandCleanupCommand).FullName}
}; };
var currentTasks = _scheduledTaskRepository.All(); var currentTasks = _scheduledTaskRepository.All();

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.MediaFiles.Commands
{ {
public class CleanMediaFileDb : ICommand public class CleanMediaFileDb : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int SeriesId { get; private set; } public int SeriesId { get; private set; }
public CleanMediaFileDb() public CleanMediaFileDb()

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.MediaFiles.Commands
{ {
public class CleanUpRecycleBinCommand : ICommand public class CleanUpRecycleBinCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public CleanUpRecycleBinCommand() public CleanUpRecycleBinCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.MediaFiles.Commands
{ {
public class DownloadedEpisodesScanCommand : ICommand public class DownloadedEpisodesScanCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public DownloadedEpisodesScanCommand() public DownloadedEpisodesScanCommand()
{ {

View File

@ -6,10 +6,10 @@ namespace NzbDrone.Core.MediaFiles.Commands
{ {
public class RenameSeasonCommand : ICommand public class RenameSeasonCommand : ICommand
{ {
public int SeriesId { get; private set; } public int SeriesId { get; set; }
public int SeasonNumber { get; private set; } public int SeasonNumber { get; set; }
public String CommandId { get; set; } public String CommandId { get; private set; }
public RenameSeasonCommand() public RenameSeasonCommand()
{ {

View File

@ -6,8 +6,8 @@ namespace NzbDrone.Core.MediaFiles.Commands
{ {
public class RenameSeriesCommand : ICommand public class RenameSeriesCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int SeriesId { get; private set; } public int SeriesId { get; set; }
public RenameSeriesCommand() public RenameSeriesCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Email
{ {
public class TestEmailCommand : ICommand public class TestEmailCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string Server { get; set; } public string Server { get; set; }
public int Port { get; set; } public int Port { get; set; }
public bool Ssl { get; set; } public bool Ssl { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Growl
{ {
public class TestGrowlCommand : ICommand public class TestGrowlCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string Host { get; set; } public string Host { get; set; }
public int Port { get; set; } public int Port { get; set; }
public string Password { get; set; } public string Password { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Plex
{ {
public class TestPlexClientCommand : ICommand public class TestPlexClientCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string Host { get; set; } public string Host { get; set; }
public int Port { get; set; } public int Port { get; set; }
public string Username { get; set; } public string Username { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Plex
{ {
public class TestPlexServerCommand : ICommand public class TestPlexServerCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string Host { get; set; } public string Host { get; set; }
public int Port { get; set; } public int Port { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Prowl
{ {
public class TestProwlCommand : ICommand public class TestProwlCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string ApiKey { get; set; } public string ApiKey { get; set; }
public int Priority { get; set; } public int Priority { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Pushover
{ {
public class TestPushoverCommand : ICommand public class TestPushoverCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string UserKey { get; set; } public string UserKey { get; set; }
public int Priority { get; set; } public int Priority { get; set; }

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Notifications.Xbmc
{ {
public class TestXbmcCommand : ICommand public class TestXbmcCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public string Host { get; set; } public string Host { get; set; }
public int Port { get; set; } public int Port { get; set; }
public string Username { get; set; } public string Username { get; set; }

View File

@ -6,13 +6,12 @@ namespace NzbDrone.Core.Providers
{ {
public class UpdateXemMappingsCommand : ICommand public class UpdateXemMappingsCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int? SeriesId { get; private set; } public int? SeriesId { get; set; }
public UpdateXemMappingsCommand(int? seriesId) public UpdateXemMappingsCommand(int? seriesId)
{ {
CommandId = HashUtil.GenerateCommandId(); CommandId = HashUtil.GenerateCommandId();
SeriesId = seriesId; SeriesId = seriesId;
} }
} }

View File

@ -6,8 +6,8 @@ namespace NzbDrone.Core.Tv.Commands
{ {
public class RefreshSeriesCommand : ICommand public class RefreshSeriesCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public int? SeriesId { get; private set; } public int? SeriesId { get; set; }
public RefreshSeriesCommand() public RefreshSeriesCommand()
{ {

View File

@ -6,7 +6,7 @@ namespace NzbDrone.Core.Update.Commands
{ {
public class ApplicationUpdateCommand : ICommand public class ApplicationUpdateCommand : ICommand
{ {
public String CommandId { get; set; } public String CommandId { get; private set; }
public ApplicationUpdateCommand() public ApplicationUpdateCommand()
{ {

View File

@ -0,0 +1,17 @@
'use strict';
define(
[
'backbone',
'Commands/CommandModel',
'Mixins/backbone.signalr.mixin'
], function (Backbone, CommandModel) {
var CommandCollection = Backbone.Collection.extend({
url : window.ApiRoot + '/command',
model: CommandModel
});
var collection = new CommandCollection().bindSignalR();
return collection;
});

View File

@ -0,0 +1,8 @@
'use strict';
define(
[
'backbone'
], function (Backbone) {
return Backbone.Model.extend({
});
});

View File

@ -9,9 +9,9 @@ define(
'Series/SeriesCollection', 'Series/SeriesCollection',
'Shared/LoadingView', 'Shared/LoadingView',
'Shared/Messenger', 'Shared/Messenger',
'Commands/CommandController', 'Shared/Actioneer',
'Shared/FormatHelpers' 'Shared/FormatHelpers'
], function (App, Marionette, ButtonsView, ManualSearchLayout, ReleaseCollection, SeriesCollection, LoadingView, Messenger, CommandController, FormatHelpers) { ], function (App, Marionette, ButtonsView, ManualSearchLayout, ReleaseCollection, SeriesCollection, LoadingView, Messenger, Actioneer, FormatHelpers) {
return Marionette.Layout.extend({ return Marionette.Layout.extend({
template: 'Episode/Search/LayoutTemplate', template: 'Episode/Search/LayoutTemplate',
@ -39,16 +39,19 @@ define(
e.preventDefault(); e.preventDefault();
} }
CommandController.Execute('episodeSearch', { episodeId: this.model.get('id') });
var series = SeriesCollection.get(this.model.get('seriesId')); var series = SeriesCollection.get(this.model.get('seriesId'));
var seriesTitle = series.get('title'); var seriesTitle = series.get('title');
var season = this.model.get('seasonNumber'); var season = this.model.get('seasonNumber');
var episode = this.model.get('episodeNumber'); var episode = this.model.get('episodeNumber');
var message = seriesTitle + ' - ' + season + 'x' + FormatHelpers.pad(episode, 2); var message = seriesTitle + ' - ' + season + 'x' + FormatHelpers.pad(episode, 2);
Messenger.show({ Actioneer.ExecuteCommand({
message: 'Search started for: ' + message command : 'episodeSearch',
properties : {
episodeId: this.model.get('id')
},
errorMessage: 'Search failed for: ' + message,
startMessage: 'Search started for: ' + message
}); });
App.vent.trigger(App.Commands.CloseModalCommand); App.vent.trigger(App.Commands.CloseModalCommand);

View File

@ -5,10 +5,11 @@ require(
'marionette', 'marionette',
'Controller', 'Controller',
'Series/SeriesCollection', 'Series/SeriesCollection',
'Shared/Actioneer',
'Navbar/NavbarView', 'Navbar/NavbarView',
'jQuery/RouteBinder', 'jQuery/RouteBinder',
'jquery' 'jquery'
], function (App, Marionette, Controller, SeriesCollection, NavbarView, RouterBinder, $) { ], function (App, Marionette, Controller, SeriesCollection, Actioneer, NavbarView, RouterBinder, $) {
var Router = Marionette.AppRouter.extend({ var Router = Marionette.AppRouter.extend({

View File

@ -113,6 +113,8 @@ define(
}, },
_setMonitored: function (seasonNumber) { _setMonitored: function (seasonNumber) {
//TODO: use Actioneer?
var self = this; var self = this;
var promise = $.ajax({ var promise = $.ajax({

View File

@ -7,9 +7,8 @@ define(
'Cells/EpisodeTitleCell', 'Cells/EpisodeTitleCell',
'Cells/RelativeDateCell', 'Cells/RelativeDateCell',
'Cells/EpisodeStatusCell', 'Cells/EpisodeStatusCell',
'Commands/CommandController',
'Shared/Actioneer' 'Shared/Actioneer'
], function ( Marionette, Backgrid, ToggleCell, EpisodeTitleCell, RelativeDateCell, EpisodeStatusCell, CommandController, Actioneer) { ], function ( Marionette, Backgrid, ToggleCell, EpisodeTitleCell, RelativeDateCell, EpisodeStatusCell, Actioneer) {
return Marionette.Layout.extend({ return Marionette.Layout.extend({
template: 'Series/Details/SeasonLayoutTemplate', template: 'Series/Details/SeasonLayoutTemplate',
@ -102,8 +101,9 @@ define(
seasonNumber: this.model.get('seasonNumber') seasonNumber: this.model.get('seasonNumber')
}, },
element : this.ui.seasonSearch, element : this.ui.seasonSearch,
failMessage : 'Search for season {0} failed'.format(this.model.get('seasonNumber')), errorMessage : 'Search for season {0} failed'.format(this.model.get('seasonNumber')),
startMessage: 'Search for season {0} started'.format(this.model.get('seasonNumber')) startMessage : 'Search for season {0} started'.format(this.model.get('seasonNumber')),
successMessage: 'Search for season {0} completed'.format(this.model.get('seasonNumber'))
}); });
}, },
@ -149,7 +149,7 @@ define(
seasonNumber: this.model.get('seasonNumber') seasonNumber: this.model.get('seasonNumber')
}, },
element : this.ui.seasonRename, element : this.ui.seasonRename,
failMessage: 'Season rename failed' errorMessage: 'Season rename failed'
}); });
} }
}); });

View File

@ -51,7 +51,7 @@ define(
seasonNumber: this.model.get('seasonNumber') seasonNumber: this.model.get('seasonNumber')
}, },
element : this.ui.seasonSearch, element : this.ui.seasonSearch,
failMessage : 'Search for season {0} failed'.format(this.model.get('seasonNumber')), errorMessage: 'Search for season {0} failed'.format(this.model.get('seasonNumber')),
startMessage: 'Search for season {0} started'.format(this.model.get('seasonNumber')) startMessage: 'Search for season {0} started'.format(this.model.get('seasonNumber'))
}); });
}, },

View File

@ -157,7 +157,7 @@ define(
element : this.ui.rename, element : this.ui.rename,
context : this, context : this,
onSuccess : this._refetchEpisodeFiles, onSuccess : this._refetchEpisodeFiles,
failMessage: 'Series search failed' errorMessage: 'Series search failed'
}); });
}, },
@ -168,7 +168,7 @@ define(
seriesId: this.model.get('id') seriesId: this.model.get('id')
}, },
element : this.ui.search, element : this.ui.search,
failMessage : 'Series search failed', errorMessage: 'Series search failed',
startMessage: 'Search for {0} started'.format(this.model.get('title')) startMessage: 'Search for {0} started'.format(this.model.get('title'))
}); });
}, },

View File

@ -140,7 +140,6 @@ define(
this._fetchCollection(); this._fetchCollection();
}, },
initialize: function () { initialize: function () {
this.seriesCollection = SeriesCollection; this.seriesCollection = SeriesCollection;
@ -148,7 +147,6 @@ define(
this.listenTo(SeriesCollection, 'remove', this._renderView); this.listenTo(SeriesCollection, 'remove', this._renderView);
}, },
_renderView: function () { _renderView: function () {
if (SeriesCollection.length === 0) { if (SeriesCollection.length === 0) {
@ -164,7 +162,6 @@ define(
} }
}, },
onShow: function () { onShow: function () {
this._showToolbar(); this._showToolbar();
this._renderView(); this._renderView();

View File

@ -66,7 +66,7 @@
<button class="btn pull-left x-back">back</button> <button class="btn pull-left x-back">back</button>
{{/if}} {{/if}}
<button class="btn x-test">test <i class="x-test-icon"/></button> <button class="btn x-test">test <i class="x-test-icon icon-nd-test"/></button>
<button class="btn" data-dismiss="modal">cancel</button> <button class="btn" data-dismiss="modal">cancel</button>
<div class="btn-group"> <div class="btn-group">

View File

@ -6,11 +6,11 @@ define([
'Settings/Notifications/Model', 'Settings/Notifications/Model',
'Settings/Notifications/DeleteView', 'Settings/Notifications/DeleteView',
'Shared/Messenger', 'Shared/Messenger',
'Commands/CommandController', 'Shared/Actioneer',
'Mixins/AsModelBoundView', 'Mixins/AsModelBoundView',
'Form/FormBuilder' 'Form/FormBuilder'
], function (App, Marionette, NotificationModel, DeleteView, Messenger, CommandController, AsModelBoundView) { ], function (App, Marionette, NotificationModel, DeleteView, Messenger, Actioneer, AsModelBoundView) {
var model = Marionette.ItemView.extend({ var model = Marionette.ItemView.extend({
template: 'Settings/Notifications/EditTemplate', template: 'Settings/Notifications/EditTemplate',
@ -70,41 +70,28 @@ define([
var testCommand = this.model.get('testCommand'); var testCommand = this.model.get('testCommand');
if (testCommand) { if (testCommand) {
this.idle = false; this.idle = false;
this.ui.testButton.addClass('disabled');
this.ui.testIcon.addClass('icon-spinner icon-spin');
var properties = {}; var properties = {};
_.each(this.model.get('fields'), function (field) { _.each(this.model.get('fields'), function (field) {
properties[field.name] = field.value; properties[field.name] = field.value;
}); });
var self = this; Actioneer.ExecuteCommand({
var commandPromise = CommandController.Execute(testCommand, properties); command : testCommand,
commandPromise.done(function () { properties : properties,
Messenger.show({ button : this.ui.testButton,
message: 'Notification settings tested successfully' element : this.ui.testIcon,
errorMessage : 'Failed to test notification settings',
successMessage: 'Notification settings tested successfully',
always : this._testOnAlways,
context : this
}); });
});
commandPromise.fail(function (options) {
if (options.readyState === 0 || options.status === 0) {
return;
} }
},
Messenger.show({ _testOnAlways: function () {
message: 'Failed to test notification settings', if (!this.isClosed) {
type : 'error' this.idle = true;
});
});
commandPromise.always(function () {
if (!self.isClosed) {
self.ui.testButton.removeClass('disabled');
self.ui.testIcon.removeClass('icon-spinner icon-spin');
self.idle = true;
}
});
} }
} }
}); });

View File

@ -1,15 +1,30 @@
'use strict'; 'use strict';
define(['Commands/CommandController', 'Shared/Messenger'], define(
function(CommandController, Messenger) { [
return { 'Commands/CommandController',
'Commands/CommandCollection',
'Shared/Messenger'],
function(CommandController, CommandCollection, Messenger) {
var actioneer = Marionette.AppRouter.extend({
initialize: function () {
this.trackedCommands = [];
CommandCollection.fetch();
this.listenTo(CommandCollection, 'sync', this._handleCommands);
},
ExecuteCommand: function (options) { ExecuteCommand: function (options) {
options.iconClass = this._getIconClass(options.element); options.iconClass = this._getIconClass(options.element);
this._showStartMessage(options); if (options.button) {
options.button.addClass('disable');
}
this._setSpinnerOnElement(options); this._setSpinnerOnElement(options);
var promise = CommandController.Execute(options.command, options.properties); var promise = CommandController.Execute(options.command, options.properties);
this._handlePromise(promise, options); this._showStartMessage(options, promise);
}, },
SaveModel: function (options) { SaveModel: function (options) {
@ -24,15 +39,7 @@ define(['Commands/CommandController', 'Shared/Messenger'],
_handlePromise: function (promise, options) { _handlePromise: function (promise, options) {
promise.done(function () { promise.done(function () {
if (options.successMessage) { self._onSuccess(options);
Messenger.show({
message: options.successMessage
});
}
if (options.onSuccess) {
options.onSuccess.call(options.context);
}
}); });
promise.fail(function (ajaxOptions) { promise.fail(function (ajaxOptions) {
@ -40,31 +47,41 @@ define(['Commands/CommandController', 'Shared/Messenger'],
return; return;
} }
if (options.failMessage) { self._onError(options);
Messenger.show({
message: options.failMessage,
type : 'error'
});
}
if (options.onError) {
options.onError.call(options.context);
}
}); });
promise.always(function () { promise.always(function () {
self._onComplete(options);
});
},
if (options.leaveIcon) { _handleCommands: function () {
options.element.removeClass('icon-spin'); var self = this;
_.each(this.trackedCommands, function (trackedCommand){
if (trackedCommand.completed === true) {
return;
} }
else { var options = trackedCommand.options;
options.element.addClass(options.iconClass); var command = CommandCollection.find({ 'id': trackedCommand.id });
options.element.removeClass('icon-nd-spinner');
if (!command) {
return;
} }
if (options.always) { if (command.get('state') === 'completed') {
options.always.call(options.context); trackedCommand.completed = true;
self._onSuccess(options, command.get('id'));
self._onComplete(options);
}
if (command.get('state') === 'failed') {
trackedCommand.completed = true;
self._onError(options, command.get('id'));
self._onComplete(options);
} }
}); });
}, },
@ -74,6 +91,10 @@ define(['Commands/CommandController', 'Shared/Messenger'],
}, },
_setSpinnerOnElement: function (options) { _setSpinnerOnElement: function (options) {
if (!options.element) {
return;
}
if (options.leaveIcon) { if (options.leaveIcon) {
options.element.addClass('icon-spin'); options.element.addClass('icon-spin');
} }
@ -84,12 +105,79 @@ define(['Commands/CommandController', 'Shared/Messenger'],
} }
}, },
_showStartMessage: function (options) { _onSuccess: function (options, id) {
if (options.successMessage) {
Messenger.show({
id : id,
message: options.successMessage,
type : 'success'
});
}
if (options.onSuccess) {
options.onSuccess.call(options.context);
}
},
_onError: function (options, id) {
if (options.errorMessage) {
Messenger.show({
id : id,
message: options.errorMessage,
type : 'error'
});
}
if (options.onError) {
options.onError.call(options.context);
}
},
_onComplete: function (options) {
if (options.button) {
options.button.removeClass('disable');
}
if (options.leaveIcon) {
options.element.removeClass('icon-spin');
}
else {
options.element.addClass(options.iconClass);
options.element.removeClass('icon-nd-spinner');
options.element.removeClass('icon-spin');
}
if (options.always) {
options.always.call(options.context);
}
},
_showStartMessage: function (options, promise) {
var self = this;
if (!promise) {
if (options.startMessage) { if (options.startMessage) {
Messenger.show({ Messenger.show({
message: options.startMessage message: options.startMessage
}); });
} }
return;
} }
promise.done(function (data) {
self.trackedCommands.push({ id: data.id, options: options });
if (options.startMessage) {
Messenger.show({
id : data.id,
message: options.startMessage
});
} }
});
}
});
return new actioneer();
}); });

View File

@ -13,6 +13,10 @@ define(function () {
options.hideAfter = 5; options.hideAfter = 5;
break; break;
case 'success':
options.hideAfter = 5;
break;
default : default :
options.hideAfter = 0; options.hideAfter = 0;
} }
@ -22,11 +26,11 @@ define(function () {
message : options.message, message : options.message,
type : options.type, type : options.type,
showCloseButton: true, showCloseButton: true,
hideAfter : options.hideAfter hideAfter : options.hideAfter,
id : options.id
}); });
}, },
monitor: function (options) { monitor: function (options) {
if (!options.promise) { if (!options.promise) {

View File

@ -3,9 +3,9 @@ define(
[ [
'app', 'app',
'marionette', 'marionette',
'Commands/CommandController', 'Shared/Actioneer',
'Shared/Messenger' 'Shared/Messenger'
], function (App, Marionette, CommandController, Messenger) { ], function (App, Marionette, Actioneer, Messenger) {
return Marionette.ItemView.extend({ return Marionette.ItemView.extend({
template : 'Shared/Toolbar/ButtonTemplate', template : 'Shared/Toolbar/ButtonTemplate',
@ -19,7 +19,6 @@ define(
icon: '.x-icon' icon: '.x-icon'
}, },
initialize: function () { initialize: function () {
this.storageKey = this.model.get('menuKey') + ':' + this.model.get('key'); this.storageKey = this.model.get('menuKey') + ':' + this.model.get('key');
this.idle = true; this.idle = true;
@ -45,69 +44,20 @@ define(
}, },
invokeCommand: function () { invokeCommand: function () {
//TODO: Use Actioneer to handle icon swapping
var command = this.model.get('command'); var command = this.model.get('command');
if (command) { if (command) {
this.idle = false; this.idle = false;
this.$el.addClass('disabled');
this.ui.icon.addClass('icon-spinner icon-spin');
var self = this; Actioneer.ExecuteCommand({
var commandPromise = CommandController.Execute(command); command : command,
commandPromise.done(function () { button : this.$el,
if (self.model.get('successMessage')) { element : this.ui.icon,
Messenger.show({ errorMessage : this.model.get('errorMessage'),
message: self.model.get('successMessage') successMessage: this.model.get('successMessage'),
always : this._commandAlways,
context : this
}); });
} }
if (self.model.get('onSuccess')) {
if (!self.model.ownerContext) {
throw 'ownerContext must be set.';
}
self.model.get('onSuccess').call(self.model.ownerContext);
}
});
commandPromise.fail(function (options) {
if (options.readyState === 0 || options.status === 0) {
return;
}
if (self.model.get('errorMessage')) {
Messenger.show({
message: self.model.get('errorMessage'),
type : 'error'
});
}
if (self.model.get('onError')) {
if (!self.model.ownerContext) {
throw 'ownerContext must be set.';
}
self.model.get('onError').call(self.model.ownerContext);
}
});
commandPromise.always(function () {
if (!self.isClosed) {
self.$el.removeClass('disabled');
self.ui.icon.removeClass('icon-spinner icon-spin');
self.idle = true;
}
});
if (self.model.get('always')) {
if (!self.model.ownerContext) {
throw 'ownerContext must be set.';
}
self.model.get('always').call(self.model.ownerContext);
}
}
}, },
invokeRoute: function () { invokeRoute: function () {
@ -133,8 +83,13 @@ define(
if (callback) { if (callback) {
callback.call(this.model.ownerContext); callback.call(this.model.ownerContext);
} }
},
_commandAlways: function () {
if (!this.isClosed) {
this.idle = true;
}
} }
}); });
}); });

View File

@ -30,10 +30,8 @@ define(
this.left = options.left; this.left = options.left;
this.right = options.right; this.right = options.right;
this.toolbarContext = options.context; this.toolbarContext = options.context;
}, },
onShow: function () { onShow: function () {
if (this.left) { if (this.left) {
_.each(this.left, this._showToolbarLeft, this); _.each(this.left, this._showToolbarLeft, this);
@ -51,7 +49,6 @@ define(
this._showToolbar(element, index, 'right'); this._showToolbar(element, index, 'right');
}, },
_showToolbar: function (buttonGroup, index, position) { _showToolbar: function (buttonGroup, index, position) {
var groupCollection = new ButtonCollection(); var groupCollection = new ButtonCollection();