added a notifications service

This commit is contained in:
Luke Pulverenti 2013-07-06 17:23:32 -04:00
parent b3054a6a22
commit 53450bd514
36 changed files with 1368 additions and 114 deletions

View File

@ -81,6 +81,7 @@
<Compile Include="Library\LibraryStructureService.cs" />
<Compile Include="LocalizationService.cs" />
<Compile Include="MoviesService.cs" />
<Compile Include="NotificationsService.cs" />
<Compile Include="PackageService.cs" />
<Compile Include="Playback\Hls\AudioHlsService.cs" />
<Compile Include="Playback\Hls\BaseHlsService.cs" />

View File

@ -0,0 +1,218 @@
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Notifications;
using ServiceStack.ServiceHost;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Api
{
[Route("/Notifications/{UserId}", "GET")]
[Api(Description = "Gets notifications")]
public class GetNotifications : IReturn<NotificationResult>
{
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public Guid UserId { get; set; }
[ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool? IsRead { get; set; }
[ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? StartIndex { get; set; }
[ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? Limit { get; set; }
}
[Route("/Notifications/{UserId}/Summary", "GET")]
[Api(Description = "Gets a notification summary for a user")]
public class GetNotificationsSummary : IReturn<NotificationsSummary>
{
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public Guid UserId { get; set; }
}
[Route("/Notifications/{UserId}", "POST")]
[Api(Description = "Adds a notifications")]
public class AddNotification : IReturn<Notification>
{
[ApiMember(Name = "Id", Description = "The Id of the new notification. If unspecified one will be provided.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public Guid? Id { get; set; }
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public Guid UserId { get; set; }
[ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Name { get; set; }
[ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Description { get; set; }
[ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Url { get; set; }
[ApiMember(Name = "Category", Description = "The notification's category", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Category { get; set; }
[ApiMember(Name = "RelatedId", Description = "The notification's related id (item)", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string RelatedId { get; set; }
[ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public NotificationLevel Level { get; set; }
}
[Route("/Notifications/{UserId}/{Id}", "POST")]
[Api(Description = "Updates a notifications")]
public class UpdateNotification : IReturnVoid
{
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public Guid UserId { get; set; }
[ApiMember(Name = "Id", Description = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public Guid Id { get; set; }
[ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Name { get; set; }
[ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Description { get; set; }
[ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Url { get; set; }
[ApiMember(Name = "Category", Description = "The notification's category", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Category { get; set; }
[ApiMember(Name = "RelatedId", Description = "The notification's related id (item)", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string RelatedId { get; set; }
[ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public NotificationLevel Level { get; set; }
}
[Route("/Notifications/{UserId}/Read", "POST")]
[Api(Description = "Marks notifications as read")]
public class MarkRead : IReturnVoid
{
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public Guid UserId { get; set; }
[ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
public string Ids { get; set; }
}
[Route("/Notifications/{UserId}/Unread", "POST")]
[Api(Description = "Marks notifications as unread")]
public class MarkUnread : IReturnVoid
{
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public Guid UserId { get; set; }
[ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
public string Ids { get; set; }
}
public class NotificationsService : BaseApiService
{
private readonly INotificationsRepository _notificationsRepo;
public NotificationsService(INotificationsRepository notificationsRepo)
{
_notificationsRepo = notificationsRepo;
}
public object Post(AddNotification request)
{
var task = AddNotification(request);
return ToOptimizedResult(task.Result);
}
public void Post(UpdateNotification request)
{
var task = UpdateNotification(request);
Task.WaitAll(task);
}
public object Get(GetNotificationsSummary request)
{
var result = _notificationsRepo.GetNotificationsSummary(request.UserId);
return result;
}
private async Task<Notification> AddNotification(AddNotification request)
{
var notification = new Notification
{
Id = request.Id ?? Guid.NewGuid(),
Date = DateTime.UtcNow,
Description = request.Description,
Level = request.Level,
Name = request.Name,
Url = request.Url,
UserId = request.UserId,
Category = request.Category,
RelatedId = request.RelatedId
};
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
return notification;
}
private Task UpdateNotification(UpdateNotification request)
{
var notification = _notificationsRepo.GetNotification(request.Id, request.UserId);
notification.Description = request.Description;
notification.Level = request.Level;
notification.Url = request.Url;
notification.Date = DateTime.UtcNow;
notification.RelatedId = request.RelatedId;
notification.Category = request.Category;
notification.Name = request.Name;
return _notificationsRepo.UpdateNotification(notification, CancellationToken.None);
}
public void Post(MarkRead request)
{
var task = MarkRead(request.Ids, request.UserId, true);
Task.WaitAll(task);
}
public void Post(MarkUnread request)
{
var task = MarkRead(request.Ids, request.UserId, false);
Task.WaitAll(task);
}
private Task MarkRead(string idList, Guid userId, bool read)
{
var ids = idList.Split(',').Select(i => new Guid(i));
return _notificationsRepo.MarkRead(ids, userId, read, CancellationToken.None);
}
public object Get(GetNotifications request)
{
var result = _notificationsRepo.GetNotifications(new NotificationQuery
{
IsRead = request.IsRead,
Limit = request.Limit,
StartIndex = request.StartIndex,
UserId = request.UserId
});
return ToOptimizedResult(result);
}
}
}

View File

@ -134,7 +134,7 @@ namespace MediaBrowser.Api
Task.Run(async () =>
{
await Task.Delay(100);
_appHost.PerformPendingRestart();
_appHost.Restart();
});
}

View File

@ -512,24 +512,6 @@ namespace MediaBrowser.Common.Implementations
Plugins = list;
}
/// <summary>
/// Performs the pending restart.
/// </summary>
/// <returns>Task.</returns>
public void PerformPendingRestart()
{
if (HasPendingRestart)
{
Logger.Info("Restarting the application");
Restart();
}
else
{
Logger.Info("PerformPendingRestart - not needed");
}
}
/// <summary>
/// Notifies that the kernel that a change has been made that requires a restart
/// </summary>

View File

@ -343,6 +343,8 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
Exception failureException = null;
try
{
await ExecuteTask(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);
@ -357,6 +359,8 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
{
Logger.ErrorException("Error", ex);
failureException = ex;
status = TaskCompletionStatus.Failed;
}
@ -368,7 +372,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
CurrentCancellationTokenSource = null;
CurrentProgress = null;
OnTaskCompleted(startTime, endTime, status);
OnTaskCompleted(startTime, endTime, status, failureException);
}
/// <summary>
@ -517,7 +521,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
/// <param name="startTime">The start time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="status">The status.</param>
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status)
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
{
var elapsedTime = endTime - startTime;
@ -532,6 +536,11 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
Id = Id
};
if (ex != null)
{
result.ErrorMessage = ex.Message;
}
JsonSerializer.SerializeToFile(result, GetHistoryFilePath(true));
LastExecutionResult = result;
@ -560,7 +569,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
if (State == TaskState.Running)
{
OnTaskCompleted(CurrentExecutionStartTime, DateTime.UtcNow, TaskCompletionStatus.Aborted);
OnTaskCompleted(CurrentExecutionStartTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
}
if (CurrentCancellationTokenSource != null)

View File

@ -21,10 +21,10 @@ namespace MediaBrowser.Common.Implementations.Updates
/// </summary>
public class InstallationManager : IInstallationManager
{
public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstalling;
public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCompleted;
public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationFailed;
public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCancelled;
public event EventHandler<InstallationEventArgs> PackageInstalling;
public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
/// <summary>
/// The current installations
@ -384,7 +384,13 @@ namespace MediaBrowser.Common.Implementations.Updates
var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
EventHelper.QueueEventIfNotNull(PackageInstalling, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
var installationEventArgs = new InstallationEventArgs
{
InstallationInfo = installationInfo,
PackageVersionInfo = package
};
EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
try
{
@ -397,7 +403,7 @@ namespace MediaBrowser.Common.Implementations.Updates
CompletedInstallations.Add(installationInfo);
EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
}
catch (OperationCanceledException)
{
@ -408,7 +414,7 @@ namespace MediaBrowser.Common.Implementations.Updates
_logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
throw;
}
@ -421,7 +427,12 @@ namespace MediaBrowser.Common.Implementations.Updates
CurrentInstallations.Remove(tuple);
}
EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
{
InstallationInfo = installationInfo,
Exception = ex
}, _logger);
throw;
}

View File

@ -18,11 +18,6 @@ namespace MediaBrowser.Common
/// </summary>
event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
/// <summary>
/// Performs the pending restart.
/// </summary>
void PerformPendingRestart();
/// <summary>
/// Gets or sets a value indicating whether this instance has pending kernel reload.
/// </summary>

View File

@ -107,6 +107,7 @@
<Compile Include="Security\IRequiresRegistration.cs" />
<Compile Include="Security\ISecurityManager.cs" />
<Compile Include="Updates\IInstallationManager.cs" />
<Compile Include="Updates\InstallationEventArgs.cs" />
<Compile Include="Updates\IPackageManager.cs" />
</ItemGroup>
<ItemGroup>

View File

@ -11,10 +11,10 @@ namespace MediaBrowser.Common.Updates
{
public interface IInstallationManager : IDisposable
{
event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstalling;
event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCompleted;
event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationFailed;
event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCancelled;
event EventHandler<InstallationEventArgs> PackageInstalling;
event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
/// <summary>
/// The current installations

View File

@ -0,0 +1,17 @@
using MediaBrowser.Model.Updates;
using System;
namespace MediaBrowser.Common.Updates
{
public class InstallationEventArgs
{
public InstallationInfo InstallationInfo { get; set; }
public PackageVersionInfo PackageVersionInfo { get; set; }
}
public class InstallationFailedEventArgs : InstallationEventArgs
{
public Exception Exception { get; set; }
}
}

View File

@ -85,6 +85,8 @@
<Compile Include="Library\IMetadataSaver.cs" />
<Compile Include="Library\ItemUpdateType.cs" />
<Compile Include="Localization\ILocalizationManager.cs" />
<Compile Include="Notifications\INotificationsRepository.cs" />
<Compile Include="Notifications\NotificationUpdateEventArgs.cs" />
<Compile Include="Session\ISessionManager.cs" />
<Compile Include="Drawing\ImageExtensions.cs" />
<Compile Include="Drawing\ImageHeader.cs" />

View File

@ -0,0 +1,76 @@
using System.Threading;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Notifications;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Notifications
{
/// <summary>
/// Interface INotificationsRepository
/// </summary>
public interface INotificationsRepository
{
/// <summary>
/// Occurs when [notification added].
/// </summary>
event EventHandler<NotificationUpdateEventArgs> NotificationAdded;
/// <summary>
/// Occurs when [notification updated].
/// </summary>
event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
/// <summary>
/// Occurs when [notifications marked read].
/// </summary>
event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead;
/// <summary>
/// Gets the notifications.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>NotificationResult.</returns>
NotificationResult GetNotifications(NotificationQuery query);
/// <summary>
/// Gets the notification.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Notification.</returns>
Notification GetNotification(Guid id, Guid userId);
/// <summary>
/// Adds the notification.
/// </summary>
/// <param name="notification">The notification.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task AddNotification(Notification notification, CancellationToken cancellationToken);
/// <summary>
/// Updates the notification.
/// </summary>
/// <param name="notification">The notification.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task UpdateNotification(Notification notification, CancellationToken cancellationToken);
/// <summary>
/// Marks the read.
/// </summary>
/// <param name="notificationIdList">The notification id list.</param>
/// <param name="userId">The user id.</param>
/// <param name="isRead">if set to <c>true</c> [is read].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task MarkRead(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken);
/// <summary>
/// Gets the notifications summary.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>NotificationsSummary.</returns>
NotificationsSummary GetNotificationsSummary(Guid userId);
}
}

View File

@ -0,0 +1,17 @@
using MediaBrowser.Model.Notifications;
using System;
namespace MediaBrowser.Controller.Notifications
{
public class NotificationUpdateEventArgs : EventArgs
{
public Notification Notification { get; set; }
}
public class NotificationReadEventArgs : EventArgs
{
public Guid[] IdList { get; set; }
public Guid UserId { get; set; }
public bool IsRead { get; set; }
}
}

View File

@ -214,6 +214,18 @@
<Compile Include="..\MediaBrowser.Model\Net\WebSocketState.cs">
<Link>Net\WebSocketState.cs</Link>
</Compile>
<Compile Include="..\MediaBrowser.Model\Notifications\Notification.cs">
<Link>Notifications\Notification.cs</Link>
</Compile>
<Compile Include="..\MediaBrowser.Model\Notifications\NotificationLevel.cs">
<Link>Notifications\NotificationLevel.cs</Link>
</Compile>
<Compile Include="..\MediaBrowser.Model\Notifications\NotificationQuery.cs">
<Link>Notifications\NotificationQuery.cs</Link>
</Compile>
<Compile Include="..\MediaBrowser.Model\Notifications\NotificationResult.cs">
<Link>Notifications\NotificationResult.cs</Link>
</Compile>
<Compile Include="..\MediaBrowser.Model\Plugins\BasePluginConfiguration.cs">
<Link>Plugins\BasePluginConfiguration.cs</Link>
</Compile>
@ -333,6 +345,7 @@
<ItemGroup>
<None Include="MediaBrowser.Model.snk" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>if $(ConfigurationName) == Release (

View File

@ -59,6 +59,11 @@
<Compile Include="Net\WebSocketMessage.cs" />
<Compile Include="Net\WebSocketMessageType.cs" />
<Compile Include="Net\WebSocketState.cs" />
<Compile Include="Notifications\Notification.cs" />
<Compile Include="Notifications\NotificationLevel.cs" />
<Compile Include="Notifications\NotificationQuery.cs" />
<Compile Include="Notifications\NotificationResult.cs" />
<Compile Include="Notifications\NotificationsSummary.cs" />
<Compile Include="Querying\ArtistsQuery.cs" />
<Compile Include="Querying\ItemReviewsResult.cs" />
<Compile Include="Querying\ItemsByNameQuery.cs" />

View File

@ -0,0 +1,33 @@
using System;
namespace MediaBrowser.Model.Notifications
{
public class Notification
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public DateTime Date { get; set; }
public bool IsRead { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public string Category { get; set; }
public string RelatedId { get; set; }
public NotificationLevel Level { get; set; }
public Notification()
{
Id = Guid.NewGuid();
Date = DateTime.UtcNow;
}
}
}

View File

@ -0,0 +1,10 @@

namespace MediaBrowser.Model.Notifications
{
public enum NotificationLevel
{
Normal,
Warning,
Error
}
}

View File

@ -0,0 +1,15 @@
using System;
namespace MediaBrowser.Model.Notifications
{
public class NotificationQuery
{
public Guid? UserId { get; set; }
public bool? IsRead { get; set; }
public int? StartIndex { get; set; }
public int? Limit { get; set; }
}
}

View File

@ -0,0 +1,9 @@

namespace MediaBrowser.Model.Notifications
{
public class NotificationResult
{
public Notification[] Notifications { get; set; }
public int TotalRecordCount { get; set; }
}
}

View File

@ -0,0 +1,9 @@

namespace MediaBrowser.Model.Notifications
{
public class NotificationsSummary
{
public int UnreadCount { get; set; }
public NotificationLevel MaxUnreadNotificationLevel { get; set; }
}
}

View File

@ -36,5 +36,11 @@ namespace MediaBrowser.Model.Tasks
/// </summary>
/// <value>The id.</value>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>The error message.</value>
public string ErrorMessage { get; set; }
}
}

View File

@ -0,0 +1,173 @@
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using System;
using System.Linq;
using System.Threading;
using MediaBrowser.Model.Tasks;
namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
/// <summary>
/// Creates notifications for various system events
/// </summary>
public class Notifications : IServerEntryPoint
{
private readonly INotificationsRepository _notificationsRepo;
private readonly IInstallationManager _installationManager;
private readonly IUserManager _userManager;
private readonly ILogger _logger;
private readonly ITaskManager _taskManager;
public Notifications(IInstallationManager installationManager, INotificationsRepository notificationsRepo, IUserManager userManager, ILogger logger, ITaskManager taskManager)
{
_installationManager = installationManager;
_notificationsRepo = notificationsRepo;
_userManager = userManager;
_logger = logger;
_taskManager = taskManager;
}
public void Run()
{
_installationManager.PackageInstallationCompleted += _installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
_installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
_taskManager.TaskCompleted += _taskManager_TaskCompleted;
}
async void _taskManager_TaskCompleted(object sender, GenericEventArgs<TaskResult> e)
{
var result = e.Argument;
if (result.Status == TaskCompletionStatus.Failed)
{
foreach (var user in _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.ToList())
{
var notification = new Notification
{
UserId = user.Id,
Category = "ScheduledTaskFailed",
Name = result.Name + " failed",
RelatedId = result.Name,
Description = result.ErrorMessage,
Level = NotificationLevel.Error
};
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
}
}
}
async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
{
var plugin = e.Argument;
foreach (var user in _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.ToList())
{
var notification = new Notification
{
UserId = user.Id,
Category = "PluginUninstalled",
Name = plugin.Name + " has been uninstalled",
RelatedId = plugin.Id.ToString()
};
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
}
}
async void _installationManager_PackageInstallationCompleted(object sender, InstallationEventArgs e)
{
var installationInfo = e.InstallationInfo;
foreach (var user in _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.ToList())
{
var notification = new Notification
{
UserId = user.Id,
Category = "PackageInstallationCompleted",
Name = installationInfo.Name + " " + installationInfo.Version + " was installed",
RelatedId = installationInfo.Name,
Description = e.PackageVersionInfo.description
};
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
}
}
async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
{
var installationInfo = e.InstallationInfo;
foreach (var user in _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.ToList())
{
var notification = new Notification
{
UserId = user.Id,
Category = "PackageInstallationFailed",
Level = NotificationLevel.Error,
Name = installationInfo.Name + " " + installationInfo.Version + " installation failed",
RelatedId = installationInfo.Name,
Description = e.Exception.Message
};
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
}
}
public void Dispose()
{
_installationManager.PackageInstallationCompleted -= _installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
}
}
}

View File

@ -0,0 +1,63 @@
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using System.Linq;
namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
/// <summary>
/// Sends out messages anytime a notification is added or udpated
/// </summary>
public class WebSocketNotifier : IServerEntryPoint
{
private readonly INotificationsRepository _notificationsRepo;
private readonly IServerManager _serverManager;
public WebSocketNotifier(INotificationsRepository notificationsRepo, IServerManager serverManager)
{
_notificationsRepo = notificationsRepo;
_serverManager = serverManager;
}
public void Run()
{
_notificationsRepo.NotificationAdded += _notificationsRepo_NotificationAdded;
_notificationsRepo.NotificationUpdated += _notificationsRepo_NotificationUpdated;
_notificationsRepo.NotificationsMarkedRead += _notificationsRepo_NotificationsMarkedRead;
}
void _notificationsRepo_NotificationsMarkedRead(object sender, NotificationReadEventArgs e)
{
var list = e.IdList.Select(i => i.ToString("N")).ToList();
list.Add(e.UserId.ToString("N"));
list.Add(e.IsRead.ToString().ToLower());
var msg = string.Join("|", list.ToArray());
_serverManager.SendWebSocketMessage("NotificationsMarkedRead", msg);
}
void _notificationsRepo_NotificationUpdated(object sender, NotificationUpdateEventArgs e)
{
var msg = e.Notification.UserId + "|" + e.Notification.Id;
_serverManager.SendWebSocketMessage("NotificationUpdated", msg);
}
void _notificationsRepo_NotificationAdded(object sender, NotificationUpdateEventArgs e)
{
var msg = e.Notification.UserId + "|" + e.Notification.Id;
_serverManager.SendWebSocketMessage("NotificationAdded", msg);
}
public void Dispose()
{
_notificationsRepo.NotificationAdded -= _notificationsRepo_NotificationAdded;
_notificationsRepo.NotificationUpdated -= _notificationsRepo_NotificationUpdated;
}
}
}

View File

@ -73,15 +73,35 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
_appHost.HasPendingRestartChanged += kernel_HasPendingRestartChanged;
_installationManager.PluginUninstalled += InstallationManager_PluginUninstalled;
_installationManager.PackageInstalling += installationManager_PackageInstalling;
_installationManager.PackageInstallationCancelled += installationManager_PackageInstallationCancelled;
_installationManager.PackageInstallationCompleted += installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed += installationManager_PackageInstallationFailed;
_installationManager.PackageInstalling += _installationManager_PackageInstalling;
_installationManager.PackageInstallationCancelled += _installationManager_PackageInstallationCancelled;
_installationManager.PackageInstallationCompleted += _installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
_taskManager.TaskExecuting += _taskManager_TaskExecuting;
_taskManager.TaskCompleted += _taskManager_TaskCompleted;
}
void _installationManager_PackageInstalling(object sender, InstallationEventArgs e)
{
_serverManager.SendWebSocketMessage("PackageInstalling", e.InstallationInfo);
}
void _installationManager_PackageInstallationCancelled(object sender, InstallationEventArgs e)
{
_serverManager.SendWebSocketMessage("PackageInstallationCancelled", e.InstallationInfo);
}
void _installationManager_PackageInstallationCompleted(object sender, InstallationEventArgs e)
{
_serverManager.SendWebSocketMessage("PackageInstallationCompleted", e.InstallationInfo);
}
void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
{
_serverManager.SendWebSocketMessage("PackageInstallationFailed", e.InstallationInfo);
}
void _taskManager_TaskCompleted(object sender, GenericEventArgs<TaskResult> e)
{
_serverManager.SendWebSocketMessage("ScheduledTaskEnded", e.Argument);
@ -93,46 +113,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
_serverManager.SendWebSocketMessage("ScheduledTaskStarted", task.Name);
}
/// <summary>
/// Installations the manager_ package installation failed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void installationManager_PackageInstallationFailed(object sender, GenericEventArgs<InstallationInfo> e)
{
_serverManager.SendWebSocketMessage("PackageInstallationFailed", e.Argument);
}
/// <summary>
/// Installations the manager_ package installation completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void installationManager_PackageInstallationCompleted(object sender, GenericEventArgs<InstallationInfo> e)
{
_serverManager.SendWebSocketMessage("PackageInstallationCompleted", e.Argument);
}
/// <summary>
/// Installations the manager_ package installation cancelled.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void installationManager_PackageInstallationCancelled(object sender, GenericEventArgs<InstallationInfo> e)
{
_serverManager.SendWebSocketMessage("PackageInstallationCancelled", e.Argument);
}
/// <summary>
/// Installations the manager_ package installing.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void installationManager_PackageInstalling(object sender, GenericEventArgs<InstallationInfo> e)
{
_serverManager.SendWebSocketMessage("PackageInstalling", e.Argument);
}
/// <summary>
/// Installations the manager_ plugin uninstalled.
/// </summary>
@ -195,10 +175,10 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
_userManager.UserUpdated -= userManager_UserUpdated;
_installationManager.PluginUninstalled -= InstallationManager_PluginUninstalled;
_installationManager.PackageInstalling -= installationManager_PackageInstalling;
_installationManager.PackageInstallationCancelled -= installationManager_PackageInstallationCancelled;
_installationManager.PackageInstallationCompleted -= installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed -= installationManager_PackageInstallationFailed;
_installationManager.PackageInstalling -= _installationManager_PackageInstalling;
_installationManager.PackageInstallationCancelled -= _installationManager_PackageInstallationCancelled;
_installationManager.PackageInstallationCompleted -= _installationManager_PackageInstallationCompleted;
_installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
_appHost.HasPendingRestartChanged -= kernel_HasPendingRestartChanged;
}

View File

@ -111,6 +111,8 @@
<Compile Include="Configuration\ServerConfigurationManager.cs" />
<Compile Include="EntryPoints\LibraryChangedNotifier.cs" />
<Compile Include="EntryPoints\LoadRegistrations.cs" />
<Compile Include="EntryPoints\Notifications\Notifier.cs" />
<Compile Include="EntryPoints\Notifications\WebSocketNotifier.cs" />
<Compile Include="EntryPoints\RefreshUsersMetadata.cs" />
<Compile Include="EntryPoints\WebSocketEvents.cs" />
<Compile Include="HttpServer\HttpResultFactory.cs" />
@ -144,6 +146,7 @@
<Compile Include="MediaEncoder\MediaEncoder.cs" />
<Compile Include="Persistence\SqliteChapterRepository.cs" />
<Compile Include="Persistence\SqliteExtensions.cs" />
<Compile Include="Persistence\SqliteNotificationsRepository.cs" />
<Compile Include="Persistence\TypeMapper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Providers\ImageSaver.cs" />

View File

@ -1,10 +1,8 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@ -16,30 +14,20 @@ namespace MediaBrowser.Server.Implementations.Persistence
private readonly ILogger _logger;
/// <summary>
/// The _app paths
/// </summary>
private readonly IApplicationPaths _appPaths;
private IDbCommand _deleteChaptersCommand;
private IDbCommand _saveChapterCommand;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteItemRepository" /> class.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="connection">The connection.</param>
/// <param name="logManager">The log manager.</param>
/// <exception cref="System.ArgumentNullException">appPaths
/// or
/// jsonSerializer</exception>
public SqliteChapterRepository(IApplicationPaths appPaths, ILogManager logManager)
public SqliteChapterRepository(IDbConnection connection, ILogManager logManager)
{
if (appPaths == null)
{
throw new ArgumentNullException("appPaths");
}
_appPaths = appPaths;
_connection = connection;
_logger = logManager.GetLogger(GetType().Name);
}
@ -48,12 +36,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// Opens the connection to the database
/// </summary>
/// <returns>Task.</returns>
public async Task Initialize()
public void Initialize()
{
var dbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
_connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
string[] queries = {
"create table if not exists chapters (ItemId GUID, ChapterIndex INT, StartPositionTicks BIGINT, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",

View File

@ -90,7 +90,11 @@ namespace MediaBrowser.Server.Implementations.Persistence
_logger = logManager.GetLogger(GetType().Name);
_chapterRepository = new SqliteChapterRepository(appPaths, logManager);
var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
var chapterConnection = SqliteExtensions.ConnectToDb(chapterDbFile).Result;
_chapterRepository = new SqliteChapterRepository(chapterConnection, logManager);
}
/// <summary>
@ -119,7 +123,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
PrepareStatements();
await _chapterRepository.Initialize().ConfigureAwait(false);
_chapterRepository.Initialize();
}
/// <summary>

View File

@ -0,0 +1,490 @@
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Persistence
{
public class SqliteNotificationsRepository : INotificationsRepository
{
private readonly IDbConnection _connection;
private readonly ILogger _logger;
private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
public SqliteNotificationsRepository(IDbConnection connection, ILogManager logManager)
{
_connection = connection;
_logger = logManager.GetLogger(GetType().Name);
}
public event EventHandler<NotificationUpdateEventArgs> NotificationAdded;
public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead;
public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
private IDbCommand _replaceNotificationCommand;
private IDbCommand _markReadCommand;
public void Initialize()
{
string[] queries = {
"create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))",
"create index if not exists idx_Notifications on Notifications(Id, UserId)",
//pragmas
"pragma temp_store = memory"
};
_connection.RunQueries(queries, _logger);
PrepareStatements();
}
private void PrepareStatements()
{
_replaceNotificationCommand = _connection.CreateCommand();
_replaceNotificationCommand.CommandText = "replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)";
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Date");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Name");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Description");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Url");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Level");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Category");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@RelatedId");
_markReadCommand = _connection.CreateCommand();
_markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId";
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
}
/// <summary>
/// Gets the notifications.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>NotificationResult.</returns>
public NotificationResult GetNotifications(NotificationQuery query)
{
var whereClause = string.Empty;
var result = new NotificationResult();
using (var cmd = _connection.CreateCommand())
{
if (query.IsRead.HasValue || query.UserId.HasValue)
{
var clauses = new List<string>();
if (query.IsRead.HasValue)
{
clauses.Add("IsRead=@IsRead");
cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = query.IsRead.Value;
}
if (query.UserId.HasValue)
{
clauses.Add("UserId=@UserId");
cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = query.UserId.Value;
}
whereClause = " where " + string.Join(" And ", clauses.ToArray());
}
cmd.CommandText = string.Format("select count(Id) from Notifications{0};select Id,UserId,Date,Name,Description,Url,Level,IsRead,Category,RelatedId from Notifications{0} order by IsRead asc, Date desc", whereClause);
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (reader.Read())
{
result.TotalRecordCount = reader.GetInt32(0);
}
if (reader.NextResult())
{
var notifications = GetNotifications(reader);
if (query.StartIndex.HasValue)
{
notifications = notifications.Skip(query.StartIndex.Value);
}
if (query.Limit.HasValue)
{
notifications = notifications.Take(query.Limit.Value);
}
result.Notifications = notifications.ToArray();
}
}
return result;
}
}
public NotificationsSummary GetNotificationsSummary(Guid userId)
{
var result = new NotificationsSummary();
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "select Level from Notifications where UserId=@UserId and IsRead=@IsRead";
cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = userId;
cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = false;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
var levels = new List<NotificationLevel>();
while (reader.Read())
{
levels.Add(GetLevel(reader, 0));
}
result.UnreadCount = levels.Count;
if (levels.Count > 0)
{
result.MaxUnreadNotificationLevel = levels.Max();
}
}
return result;
}
}
/// <summary>
/// Gets the notifications.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>IEnumerable{Notification}.</returns>
private IEnumerable<Notification> GetNotifications(IDataReader reader)
{
while (reader.Read())
{
yield return GetNotification(reader);
}
}
private Notification GetNotification(IDataReader reader)
{
var notification = new Notification
{
Id = reader.GetGuid(0),
UserId = reader.GetGuid(1),
Date = reader.GetDateTime(2).ToUniversalTime(),
Name = reader.GetString(3)
};
if (!reader.IsDBNull(4))
{
notification.Description = reader.GetString(4);
}
if (!reader.IsDBNull(5))
{
notification.Url = reader.GetString(5);
}
notification.Level = GetLevel(reader, 6);
notification.IsRead = reader.GetBoolean(7);
notification.Category = reader.GetString(8);
if (!reader.IsDBNull(9))
{
notification.RelatedId = reader.GetString(9);
}
return notification;
}
/// <summary>
/// Gets the notification.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Notification.</returns>
/// <exception cref="System.ArgumentNullException">
/// id
/// or
/// userId
/// </exception>
public Notification GetNotification(Guid id, Guid userId)
{
if (id == Guid.Empty)
{
throw new ArgumentNullException("id");
}
if (userId == Guid.Empty)
{
throw new ArgumentNullException("userId");
}
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "select Id,UserId,Date,Name,Description,Url,Level,IsRead,Category,RelatedId where Id=@Id And UserId = @UserId";
cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = id;
cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = userId;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
if (reader.Read())
{
return GetNotification(reader);
}
}
return null;
}
}
/// <summary>
/// Gets the level.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="index">The index.</param>
/// <returns>NotificationLevel.</returns>
private NotificationLevel GetLevel(IDataReader reader, int index)
{
NotificationLevel level;
var val = reader.GetString(index);
Enum.TryParse(val, true, out level);
return level;
}
/// <summary>
/// Adds the notification.
/// </summary>
/// <param name="notification">The notification.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task AddNotification(Notification notification, CancellationToken cancellationToken)
{
await ReplaceNotification(notification, cancellationToken).ConfigureAwait(false);
if (NotificationAdded != null)
{
try
{
NotificationAdded(this, new NotificationUpdateEventArgs
{
Notification = notification
});
}
catch (Exception ex)
{
_logger.ErrorException("Error in NotificationAdded event handler", ex);
}
}
}
/// <summary>
/// Updates the notification.
/// </summary>
/// <param name="notification">The notification.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task UpdateNotification(Notification notification, CancellationToken cancellationToken)
{
await ReplaceNotification(notification, cancellationToken).ConfigureAwait(false);
if (NotificationUpdated != null)
{
try
{
NotificationUpdated(this, new NotificationUpdateEventArgs
{
Notification = notification
});
}
catch (Exception ex)
{
_logger.ErrorException("Error in NotificationUpdated event handler", ex);
}
}
}
/// <summary>
/// Replaces the notification.
/// </summary>
/// <param name="notification">The notification.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task ReplaceNotification(Notification notification, CancellationToken cancellationToken)
{
if (notification.Id == Guid.Empty)
{
throw new ArgumentException("The notification must have an id");
}
if (notification.UserId == Guid.Empty)
{
throw new ArgumentException("The notification must have a user id");
}
cancellationToken.ThrowIfCancellationRequested();
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
IDbTransaction transaction = null;
try
{
transaction = _connection.BeginTransaction();
_replaceNotificationCommand.GetParameter(0).Value = notification.Id;
_replaceNotificationCommand.GetParameter(1).Value = notification.UserId;
_replaceNotificationCommand.GetParameter(2).Value = notification.Date.ToUniversalTime();
_replaceNotificationCommand.GetParameter(3).Value = notification.Name;
_replaceNotificationCommand.GetParameter(4).Value = notification.Description;
_replaceNotificationCommand.GetParameter(5).Value = notification.Url;
_replaceNotificationCommand.GetParameter(6).Value = notification.Level.ToString();
_replaceNotificationCommand.GetParameter(7).Value = notification.IsRead;
_replaceNotificationCommand.GetParameter(8).Value = notification.Category;
_replaceNotificationCommand.GetParameter(9).Value = notification.RelatedId;
_replaceNotificationCommand.Transaction = transaction;
_replaceNotificationCommand.ExecuteNonQuery();
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
_logger.ErrorException("Failed to save notification:", e);
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
_writeLock.Release();
}
}
/// <summary>
/// Marks the read.
/// </summary>
/// <param name="notificationIdList">The notification id list.</param>
/// <param name="userId">The user id.</param>
/// <param name="isRead">if set to <c>true</c> [is read].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task MarkRead(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken)
{
var idArray = notificationIdList.ToArray();
await MarkReadInternal(idArray, userId, isRead, cancellationToken).ConfigureAwait(false);
if (NotificationsMarkedRead != null)
{
try
{
NotificationsMarkedRead(this, new NotificationReadEventArgs
{
IdList = idArray.ToArray(),
IsRead = isRead,
UserId = userId
});
}
catch (Exception ex)
{
_logger.ErrorException("Error in NotificationsMarkedRead event handler", ex);
}
}
}
private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
IDbTransaction transaction = null;
try
{
cancellationToken.ThrowIfCancellationRequested();
transaction = _connection.BeginTransaction();
_markReadCommand.GetParameter(0).Value = userId;
_markReadCommand.GetParameter(1).Value = isRead;
foreach (var id in notificationIdList)
{
_markReadCommand.GetParameter(2).Value = id;
_markReadCommand.Transaction = transaction;
_markReadCommand.ExecuteNonQuery();
}
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
_logger.ErrorException("Failed to save notification:", e);
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
_writeLock.Release();
}
}
}
}

View File

@ -1,6 +1,5 @@
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
using System;
@ -46,7 +45,9 @@ namespace MediaBrowser.Server.Implementations.ScheduledTasks
// 1:30am
new DailyTrigger { TimeOfDay = TimeSpan.FromHours(1.5) },
new IntervalTrigger { Interval = TimeSpan.FromHours(2)}
new IntervalTrigger { Interval = TimeSpan.FromHours(3)},
new StartupTrigger()
};
}

View File

@ -16,6 +16,7 @@ using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Localization;
using MediaBrowser.Controller.MediaInfo;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
@ -44,6 +45,7 @@ using MediaBrowser.ServerApplication.Implementations;
using MediaBrowser.WebDashboard.Api;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
@ -166,6 +168,7 @@ namespace MediaBrowser.ServerApplication
private IUserRepository UserRepository { get; set; }
internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
private IItemRepository ItemRepository { get; set; }
private INotificationsRepository NotificationsRepository { get; set; }
/// <summary>
/// The full path to our startmenu shortcut
@ -284,6 +287,8 @@ namespace MediaBrowser.ServerApplication
var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
var userTask = Task.Run(async () => await ConfigureUserRepositories().ConfigureAwait(false));
await ConfigureNotificationsRepository().ConfigureAwait(false);
await Task.WhenAll(itemsTask, userTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
SetKernelProperties();
@ -304,6 +309,25 @@ namespace MediaBrowser.ServerApplication
);
}
/// <summary>
/// Configures the repositories.
/// </summary>
/// <returns>Task.</returns>
private async Task ConfigureNotificationsRepository()
{
var dbFile = Path.Combine(ApplicationPaths.DataPath, "notifications.db");
var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
var repo = new SqliteNotificationsRepository(connection, LogManager);
repo.Initialize();
NotificationsRepository = repo;
RegisterSingleInstance(NotificationsRepository);
}
/// <summary>
/// Configures the repositories.
/// </summary>
@ -344,6 +368,35 @@ namespace MediaBrowser.ServerApplication
((UserManager)UserManager).UserRepository = UserRepository;
}
/// <summary>
/// Connects to db.
/// </summary>
/// <param name="dbPath">The db path.</param>
/// <returns>Task{IDbConnection}.</returns>
/// <exception cref="System.ArgumentNullException">dbPath</exception>
private static async Task<SQLiteConnection> ConnectToDb(string dbPath)
{
if (string.IsNullOrEmpty(dbPath))
{
throw new ArgumentNullException("dbPath");
}
var connectionstr = new SQLiteConnectionStringBuilder
{
PageSize = 4096,
CacheSize = 4096,
SyncMode = SynchronizationModes.Off,
DataSource = dbPath,
JournalMode = SQLiteJournalModeEnum.Wal
};
var connection = new SQLiteConnection(connectionstr.ConnectionString);
await connection.OpenAsync().ConfigureAwait(false);
return connection;
}
/// <summary>
/// Dirty hacks
/// </summary>

View File

@ -172,6 +172,13 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Data.SQLite, Version=1.0.86.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\System.Data.SQLite.x86.1.0.86.0\lib\net45\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Data.SQLite.Linq">
<HintPath>..\packages\System.Data.SQLite.x86.1.0.86.0\lib\net45\System.Data.SQLite.Linq.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Net" />
<Reference Include="System.Runtime.Remoting" />

View File

@ -12,4 +12,5 @@
<package id="ServiceStack.Redis" version="3.9.44" targetFramework="net45" />
<package id="ServiceStack.Text" version="3.9.54" targetFramework="net45" />
<package id="SimpleInjector" version="2.2.3" targetFramework="net45" />
<package id="System.Data.SQLite.x86" version="1.0.86.0" targetFramework="net45" />
</packages>

View File

@ -468,6 +468,7 @@ namespace MediaBrowser.WebDashboard.Api
"musicgenres.js",
"musicrecommended.js",
"musicvideos.js",
"notifications.js",
"playlist.js",
"plugincatalogpage.js",
"pluginspage.js",
@ -524,6 +525,7 @@ namespace MediaBrowser.WebDashboard.Api
"detailtable.css",
"posteritem.css",
"tileitem.css",
"notifications.css",
"search.css",
"pluginupdates.css",
"remotecontrol.css",

View File

@ -243,6 +243,61 @@ MediaBrowser.ApiClient = function ($, navigator, JSON, WebSocket, setTimeout) {
});
};
self.getNotificationSummary = function (userId) {
if (!userId) {
throw new Error("null userId");
}
var url = self.getUrl("Notifications/" + userId + "/Summary");
return self.ajax({
type: "GET",
url: url,
dataType: "json"
});
};
self.getNotifications = function (userId, options) {
if (!userId) {
throw new Error("null userId");
}
var url = self.getUrl("Notifications/" + userId, options || {});
return self.ajax({
type: "GET",
url: url,
dataType: "json"
});
};
self.markNotificationsRead = function (userId, idList, isRead) {
if (!userId) {
throw new Error("null userId");
}
if (!idList || !idList.length) {
throw new Error("null idList");
}
var suffix = isRead ? "Read" : "Unread";
var params = {
UserId: userId,
Ids: idList.join(',')
};
var url = self.getUrl("Notifications/" + userId + "/" + suffix, params);
return self.ajax({
type: "POST",
url: url
});
};
/**
* Gets the current server status
*/

View File

@ -84,6 +84,9 @@
<Content Include="dashboard-ui\boxsets.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\css\notifications.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\edititempeople.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@ -354,6 +357,9 @@
<Content Include="dashboard-ui\scripts\alphapicker.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\scripts\directorybrowser.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\scripts\edititempeople.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@ -375,6 +381,9 @@
<Content Include="dashboard-ui\scripts\musicvideos.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\scripts\notifications.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="dashboard-ui\scripts\remotecontrol.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MediaBrowser.ApiClient.Javascript" version="3.0.131" targetFramework="net45" />
<package id="MediaBrowser.ApiClient.Javascript" version="3.0.135" targetFramework="net45" />
<package id="ServiceStack.Common" version="3.9.54" targetFramework="net45" />
<package id="ServiceStack.Text" version="3.9.54" targetFramework="net45" />
</packages>