rework notifications infrastructure

This commit is contained in:
Luke Pulverenti
2014-04-25 16:15:50 -04:00
parent eda8159b44
commit 547291f048
34 changed files with 455 additions and 323 deletions

View File

@@ -556,44 +556,6 @@ namespace MediaBrowser.Server.Implementations.Dto
return dto;
}
/// <summary>
/// Gets a BaseItem based upon it's client-side item id
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>BaseItem.</returns>
public BaseItem GetItemByDtoId(string id, Guid? userId = null)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
BaseItem item = null;
if (userId.HasValue)
{
item = _libraryManager.GetItemById(new Guid(id));
}
// If we still don't find it, look within individual user views
if (item == null && !userId.HasValue)
{
foreach (var user in _userManager.Users)
{
item = GetItemByDtoId(id, user.Id);
if (item != null)
{
break;
}
}
}
return item;
}
/// <summary>
/// Sets simple property values on a DTOBaseItem
/// </summary>

View File

@@ -20,20 +20,20 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
/// </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;
private readonly INotificationManager _notificationManager;
public Notifications(IInstallationManager installationManager, INotificationsRepository notificationsRepo, IUserManager userManager, ILogger logger, ITaskManager taskManager)
public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager)
{
_installationManager = installationManager;
_notificationsRepo = notificationsRepo;
_userManager = userManager;
_logger = logger;
_taskManager = taskManager;
_notificationManager = notificationManager;
}
public void Run()
@@ -49,21 +49,25 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
async void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
{
var notification = new Notification
var userIds = _userManager
.Users
.Select(i => i.Id.ToString("N"))
.ToList();
var notification = new NotificationRequest
{
UserId = e.Argument.Id,
Category = "UserCreated",
UserIds = userIds,
Name = "Welcome to Media Browser!",
Description = "Check back here for more notifications."
};
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
_logger.ErrorException("Error sending notification", ex);
}
}
@@ -73,29 +77,27 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
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
};
var userIds = _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.Select(i => i.Id.ToString("N"))
.ToList();
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
var notification = new NotificationRequest
{
UserIds = userIds,
Name = result.Name + " failed",
Description = result.ErrorMessage,
Level = NotificationLevel.Error
};
try
{
await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending notification", ex);
}
}
}
@@ -104,27 +106,25 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
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()
};
var userIds = _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.Select(i => i.Id.ToString("N"))
.ToList();
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
var notification = new NotificationRequest
{
UserIds = userIds,
Name = plugin.Name + " has been uninstalled"
};
try
{
await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending notification", ex);
}
}
@@ -132,28 +132,26 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
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
};
var userIds = _userManager
.Users
.Where(i => i.Configuration.IsAdministrator)
.Select(i => i.Id.ToString("N"))
.ToList();
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
var notification = new NotificationRequest
{
UserIds = userIds,
Name = installationInfo.Name + " " + installationInfo.Version + " was installed",
Description = e.PackageVersionInfo.description
};
try
{
await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending notification", ex);
}
}
@@ -161,29 +159,27 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
var installationInfo = e.InstallationInfo;
foreach (var user in _userManager
var userIds = _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
};
.Select(i => i.Id.ToString("N"))
.ToList();
try
{
await _notificationsRepo.AddNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error adding notification", ex);
}
var notification = new NotificationRequest
{
UserIds = userIds,
Level = NotificationLevel.Error,
Name = installationInfo.Name + " " + installationInfo.Version + " installation failed",
Description = e.Exception.Message
};
try
{
await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending notification", ex);
}
}

View File

@@ -1,7 +1,6 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
@@ -26,22 +25,23 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
private readonly IApplicationPaths _appPaths;
private readonly ILogger _logger;
private readonly IJsonSerializer _json;
private readonly INotificationsRepository _notificationsRepo;
private readonly IUserManager _userManager;
private readonly IFileSystem _fileSystem;
private readonly TimeSpan _frequency = TimeSpan.FromHours(6);
private readonly TimeSpan _maxAge = TimeSpan.FromDays(31);
public RemoteNotifications(IApplicationPaths appPaths, ILogger logger, IHttpClient httpClient, IJsonSerializer json, INotificationsRepository notificationsRepo, IUserManager userManager, IFileSystem fileSystem)
private readonly INotificationManager _notificationManager;
public RemoteNotifications(IApplicationPaths appPaths, ILogger logger, IHttpClient httpClient, IJsonSerializer json, IUserManager userManager, IFileSystem fileSystem, INotificationManager notificationManager)
{
_appPaths = appPaths;
_logger = logger;
_httpClient = httpClient;
_json = json;
_notificationsRepo = notificationsRepo;
_userManager = userManager;
_fileSystem = fileSystem;
_notificationManager = notificationManager;
}
/// <summary>
@@ -107,21 +107,19 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
.Where(i => string.Equals(i.active, "1") && i.date.ToUniversalTime() > lastRunTime && (DateTime.UtcNow - i.date.ToUniversalTime()) <= _maxAge)
.ToList();
foreach (var user in _userManager.Users.ToList())
{
foreach (var notification in notificationList)
{
await _notificationsRepo.AddNotification(new Notification
{
Category = notification.category,
Date = notification.date,
Name = notification.name,
Description = notification.description,
Url = notification.url,
UserId = user.Id
var userIds = _userManager.Users.Select(i => i.Id.ToString("N")).ToList();
}, CancellationToken.None).ConfigureAwait(false);
}
foreach (var notification in notificationList)
{
await _notificationManager.SendNotification(new NotificationRequest
{
Date = notification.date,
Name = notification.name,
Description = notification.description,
Url = notification.url,
UserIds = userIds
}, CancellationToken.None).ConfigureAwait(false);
}
}

View File

@@ -30,9 +30,9 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
void _notificationsRepo_NotificationsMarkedRead(object sender, NotificationReadEventArgs e)
{
var list = e.IdList.Select(i => i.ToString("N")).ToList();
var list = e.IdList.ToList();
list.Add(e.UserId.ToString("N"));
list.Add(e.UserId);
list.Add(e.IsRead.ToString().ToLower());
var msg = string.Join("|", list.ToArray());

View File

@@ -117,7 +117,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio
/// </summary>
/// <param name="list">The list.</param>
/// <returns><c>true</c> if the specified list contains music; otherwise, <c>false</c>.</returns>
public static bool ContainsMusic(IEnumerable<FileSystemInfo> list)
private static bool ContainsMusic(IEnumerable<FileSystemInfo> list)
{
// If list contains at least 2 audio files or at least one and no video files consider it to contain music
var foundAudio = 0;

View File

@@ -185,11 +185,13 @@
<Compile Include="MediaEncoder\EncodingManager.cs" />
<Compile Include="News\NewsEntryPoint.cs" />
<Compile Include="News\NewsService.cs" />
<Compile Include="Notifications\InternalNotificationService.cs" />
<Compile Include="Notifications\NotificationManager.cs" />
<Compile Include="Persistence\SqliteChapterRepository.cs" />
<Compile Include="Persistence\SqliteExtensions.cs" />
<Compile Include="Persistence\SqliteFileOrganizationRepository.cs" />
<Compile Include="Persistence\SqliteMediaStreamsRepository.cs" />
<Compile Include="Persistence\SqliteNotificationsRepository.cs" />
<Compile Include="Notifications\SqliteNotificationsRepository.cs" />
<Compile Include="Persistence\SqliteProviderInfoRepository.cs" />
<Compile Include="Persistence\SqliteShrinkMemoryTimer.cs" />
<Compile Include="Persistence\TypeMapper.cs" />

View File

@@ -0,0 +1,42 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Notifications;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Notifications
{
public class InternalNotificationService : INotificationService
{
private readonly INotificationsRepository _repo;
public InternalNotificationService(INotificationsRepository repo)
{
_repo = repo;
}
public string Name
{
get { return "Dashboard Notifications"; }
}
public Task SendNotification(UserNotification request, CancellationToken cancellationToken)
{
return _repo.AddNotification(new Notification
{
Date = request.Date,
Description = request.Description,
Level = request.Level,
Name = request.Name,
Url = request.Url,
UserId = request.User.Id.ToString("N")
}, cancellationToken);
}
public bool IsEnabledForUser(User user)
{
return true;
}
}
}

View File

@@ -0,0 +1,94 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Notifications
{
public class NotificationManager : INotificationManager
{
private readonly ILogger _logger;
private readonly IUserManager _userManager;
private INotificationService[] _services;
public NotificationManager(ILogManager logManager, IUserManager userManager)
{
_userManager = userManager;
_logger = logManager.GetLogger(GetType().Name);
}
public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken)
{
var users = request.UserIds.Select(i => _userManager.GetUserById(new Guid(i)));
var tasks = _services.Select(i => SendNotification(request, i, users, cancellationToken));
return Task.WhenAll(tasks);
}
public Task SendNotification(NotificationRequest request,
INotificationService service,
IEnumerable<User> users,
CancellationToken cancellationToken)
{
users = users.Where(i => IsEnabledForUser(service, i))
.ToList();
var tasks = users.Select(i => SendNotification(request, service, i, cancellationToken));
return Task.WhenAll(tasks);
}
public async Task SendNotification(NotificationRequest request,
INotificationService service,
User user,
CancellationToken cancellationToken)
{
var notification = new UserNotification
{
Date = request.Date,
Description = request.Description,
Level = request.Level,
Name = request.Name,
Url = request.Url,
User = user
};
_logger.Debug("Sending notification via {0} to user {1}", service.Name, user.Name);
try
{
await service.SendNotification(notification, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending notification to {0}", ex, service.Name);
}
}
private bool IsEnabledForUser(INotificationService service, User user)
{
try
{
return service.IsEnabledForUser(user);
}
catch (Exception ex)
{
_logger.ErrorException("Error in IsEnabledForUser", ex);
return false;
}
}
public void AddParts(IEnumerable<INotificationService> services)
{
_services = services.ToArray();
}
}
}

View File

@@ -1,16 +1,17 @@
using System.IO;
using MediaBrowser.Controller;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using MediaBrowser.Server.Implementations.Persistence;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Persistence
namespace MediaBrowser.Server.Implementations.Notifications
{
public class SqliteNotificationsRepository : INotificationsRepository
{
@@ -134,7 +135,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
}
}
public NotificationsSummary GetNotificationsSummary(Guid userId)
public NotificationsSummary GetNotificationsSummary(string userId)
{
var result = new NotificationsSummary();
@@ -142,7 +143,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{
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, "@UserId", DbType.Guid).Value = new Guid(userId);
cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = false;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
@@ -183,8 +184,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
{
var notification = new Notification
{
Id = reader.GetGuid(0),
UserId = reader.GetGuid(1),
Id = reader.GetGuid(0).ToString("N"),
UserId = reader.GetGuid(1).ToString("N"),
Date = reader.GetDateTime(2).ToUniversalTime(),
Name = reader.GetString(3)
};
@@ -202,13 +203,6 @@ namespace MediaBrowser.Server.Implementations.Persistence
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;
}
@@ -223,13 +217,13 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// or
/// userId
/// </exception>
public Notification GetNotification(Guid id, Guid userId)
public Notification GetNotification(string id, string userId)
{
if (id == Guid.Empty)
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
if (userId == Guid.Empty)
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
@@ -238,8 +232,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
{
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;
cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = new Guid(id);
cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = new Guid(userId);
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
@@ -329,11 +323,11 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <returns>Task.</returns>
private async Task ReplaceNotification(Notification notification, CancellationToken cancellationToken)
{
if (notification.Id == Guid.Empty)
if (string.IsNullOrEmpty(notification.Id))
{
throw new ArgumentException("The notification must have an id");
notification.Id = Guid.NewGuid().ToString("N");
}
if (notification.UserId == Guid.Empty)
if (string.IsNullOrEmpty(notification.UserId))
{
throw new ArgumentException("The notification must have a user id");
}
@@ -348,16 +342,16 @@ namespace MediaBrowser.Server.Implementations.Persistence
{
transaction = _connection.BeginTransaction();
_replaceNotificationCommand.GetParameter(0).Value = notification.Id;
_replaceNotificationCommand.GetParameter(1).Value = notification.UserId;
_replaceNotificationCommand.GetParameter(0).Value = new Guid(notification.Id);
_replaceNotificationCommand.GetParameter(1).Value = new Guid(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.GetParameter(8).Value = string.Empty;
_replaceNotificationCommand.GetParameter(9).Value = string.Empty;
_replaceNotificationCommand.Transaction = transaction;
@@ -404,9 +398,10 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <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)
public async Task MarkRead(IEnumerable<string> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken)
{
var idArray = notificationIdList.ToArray();
var list = notificationIdList.ToList();
var idArray = list.Select(i => new Guid(i)).ToArray();
await MarkReadInternal(idArray, userId, isRead, cancellationToken).ConfigureAwait(false);
@@ -416,7 +411,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{
NotificationsMarkedRead(this, new NotificationReadEventArgs
{
IdList = idArray.ToArray(),
IdList = list.ToArray(),
IsRead = isRead,
UserId = userId
});
@@ -428,7 +423,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
}
}
private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken)
private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -442,7 +437,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
transaction = _connection.BeginTransaction();
_markReadCommand.GetParameter(0).Value = userId;
_markReadCommand.GetParameter(0).Value = new Guid(userId);
_markReadCommand.GetParameter(1).Value = isRead;
foreach (var id in notificationIdList)