aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Notifications
diff options
context:
space:
mode:
Diffstat (limited to 'MediaBrowser.Server.Implementations/Notifications')
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/CoreNotificationTypes.cs198
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/IConfigurableNotificationService.cs8
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/InternalNotificationService.cs61
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/NotificationConfigurationFactory.cs21
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/NotificationManager.cs296
-rw-r--r--MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs470
6 files changed, 0 insertions, 1054 deletions
diff --git a/MediaBrowser.Server.Implementations/Notifications/CoreNotificationTypes.cs b/MediaBrowser.Server.Implementations/Notifications/CoreNotificationTypes.cs
deleted file mode 100644
index 8ca667739..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/CoreNotificationTypes.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Localization;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Model.Notifications;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace MediaBrowser.Server.Implementations.Notifications
-{
- public class CoreNotificationTypes : INotificationTypeFactory
- {
- private readonly ILocalizationManager _localization;
- private readonly IServerApplicationHost _appHost;
-
- public CoreNotificationTypes(ILocalizationManager localization, IServerApplicationHost appHost)
- {
- _localization = localization;
- _appHost = appHost;
- }
-
- public IEnumerable<NotificationTypeInfo> GetNotificationTypes()
- {
- var knownTypes = new List<NotificationTypeInfo>
- {
- new NotificationTypeInfo
- {
- Type = NotificationType.ApplicationUpdateInstalled.ToString(),
- DefaultDescription = "{ReleaseNotes}",
- DefaultTitle = "A new version of Emby Server has been installed.",
- Variables = new List<string>{"Version"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.InstallationFailed.ToString(),
- DefaultTitle = "{Name} installation failed.",
- Variables = new List<string>{"Name", "Version"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.PluginInstalled.ToString(),
- DefaultTitle = "{Name} was installed.",
- Variables = new List<string>{"Name", "Version"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.PluginError.ToString(),
- DefaultTitle = "{Name} has encountered an error.",
- DefaultDescription = "{ErrorMessage}",
- Variables = new List<string>{"Name", "ErrorMessage"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.PluginUninstalled.ToString(),
- DefaultTitle = "{Name} was uninstalled.",
- Variables = new List<string>{"Name", "Version"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.PluginUpdateInstalled.ToString(),
- DefaultTitle = "{Name} was updated.",
- DefaultDescription = "{ReleaseNotes}",
- Variables = new List<string>{"Name", "ReleaseNotes", "Version"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.ServerRestartRequired.ToString(),
- DefaultTitle = "Please restart Emby Server to finish updating."
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.TaskFailed.ToString(),
- DefaultTitle = "{Name} failed.",
- DefaultDescription = "{ErrorMessage}",
- Variables = new List<string>{"Name", "ErrorMessage"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.NewLibraryContent.ToString(),
- DefaultTitle = "{Name} has been added to your media library.",
- Variables = new List<string>{"Name"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.AudioPlayback.ToString(),
- DefaultTitle = "{UserName} is playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.GamePlayback.ToString(),
- DefaultTitle = "{UserName} is playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.VideoPlayback.ToString(),
- DefaultTitle = "{UserName} is playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.AudioPlaybackStopped.ToString(),
- DefaultTitle = "{UserName} has finished playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.GamePlaybackStopped.ToString(),
- DefaultTitle = "{UserName} has finished playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.VideoPlaybackStopped.ToString(),
- DefaultTitle = "{UserName} has finished playing {ItemName} on {DeviceName}.",
- Variables = new List<string>{"UserName", "ItemName", "DeviceName", "AppName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.CameraImageUploaded.ToString(),
- DefaultTitle = "A new camera image has been uploaded from {DeviceName}.",
- Variables = new List<string>{"DeviceName"}
- },
-
- new NotificationTypeInfo
- {
- Type = NotificationType.UserLockedOut.ToString(),
- DefaultTitle = "{UserName} has been locked out.",
- Variables = new List<string>{"UserName"}
- }
- };
-
- if (!_appHost.CanSelfUpdate)
- {
- knownTypes.Add(new NotificationTypeInfo
- {
- Type = NotificationType.ApplicationUpdateAvailable.ToString(),
- DefaultTitle = "A new version of Emby Server is available for download."
- });
- }
-
- foreach (var type in knownTypes)
- {
- Update(type);
- }
-
- var systemName = _localization.GetLocalizedString("CategorySystem");
-
- return knownTypes.OrderByDescending(i => string.Equals(i.Category, systemName, StringComparison.OrdinalIgnoreCase))
- .ThenBy(i => i.Category)
- .ThenBy(i => i.Name);
- }
-
- private void Update(NotificationTypeInfo note)
- {
- note.Name = _localization.GetLocalizedString("NotificationOption" + note.Type) ?? note.Type;
-
- note.IsBasedOnUserEvent = note.Type.IndexOf("Playback", StringComparison.OrdinalIgnoreCase) != -1;
-
- if (note.Type.IndexOf("Playback", StringComparison.OrdinalIgnoreCase) != -1)
- {
- note.Category = _localization.GetLocalizedString("CategoryUser");
- }
- else if (note.Type.IndexOf("Plugin", StringComparison.OrdinalIgnoreCase) != -1)
- {
- note.Category = _localization.GetLocalizedString("CategoryPlugin");
- }
- else if (note.Type.IndexOf("CameraImageUploaded", StringComparison.OrdinalIgnoreCase) != -1)
- {
- note.Category = _localization.GetLocalizedString("CategorySync");
- }
- else if (note.Type.IndexOf("UserLockedOut", StringComparison.OrdinalIgnoreCase) != -1)
- {
- note.Category = _localization.GetLocalizedString("CategoryUser");
- }
- else
- {
- note.Category = _localization.GetLocalizedString("CategorySystem");
- }
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/Notifications/IConfigurableNotificationService.cs b/MediaBrowser.Server.Implementations/Notifications/IConfigurableNotificationService.cs
deleted file mode 100644
index cdfd0f640..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/IConfigurableNotificationService.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace MediaBrowser.Server.Implementations.Notifications
-{
- public interface IConfigurableNotificationService
- {
- bool IsHidden { get; }
- bool IsEnabled(string notificationType);
- }
-}
diff --git a/MediaBrowser.Server.Implementations/Notifications/InternalNotificationService.cs b/MediaBrowser.Server.Implementations/Notifications/InternalNotificationService.cs
deleted file mode 100644
index 4a625f0fb..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/InternalNotificationService.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Model.Notifications;
-using System.Threading;
-using System.Threading.Tasks;
-using System;
-
-namespace MediaBrowser.Server.Implementations.Notifications
-{
- public class InternalNotificationService : INotificationService, IConfigurableNotificationService
- {
- 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 user.Policy.IsAdministrator;
- }
-
- public bool IsHidden
- {
- get { return true; }
- }
-
- public bool IsEnabled(string notificationType)
- {
- if (notificationType.IndexOf("playback", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return false;
- }
- if (notificationType.IndexOf("newlibrarycontent", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return false;
- }
- return true;
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/Notifications/NotificationConfigurationFactory.cs b/MediaBrowser.Server.Implementations/Notifications/NotificationConfigurationFactory.cs
deleted file mode 100644
index a336eba0e..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/NotificationConfigurationFactory.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Notifications;
-using System.Collections.Generic;
-
-namespace MediaBrowser.Server.Implementations.Notifications
-{
- public class NotificationConfigurationFactory : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new List<ConfigurationStore>
- {
- new ConfigurationStore
- {
- Key = "notifications",
- ConfigurationType = typeof (NotificationOptions)
- }
- };
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/Notifications/NotificationManager.cs b/MediaBrowser.Server.Implementations/Notifications/NotificationManager.cs
deleted file mode 100644
index f19ff8a5f..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/NotificationManager.cs
+++ /dev/null
@@ -1,296 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Configuration;
-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;
-using MediaBrowser.Model.Extensions;
-
-namespace MediaBrowser.Server.Implementations.Notifications
-{
- public class NotificationManager : INotificationManager
- {
- private readonly ILogger _logger;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
-
- private INotificationService[] _services;
- private INotificationTypeFactory[] _typeFactories;
-
- public NotificationManager(ILogManager logManager, IUserManager userManager, IServerConfigurationManager config)
- {
- _userManager = userManager;
- _config = config;
- _logger = logManager.GetLogger(GetType().Name);
- }
-
- private NotificationOptions GetConfiguration()
- {
- return _config.GetConfiguration<NotificationOptions>("notifications");
- }
-
- public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken)
- {
- var notificationType = request.NotificationType;
-
- var options = string.IsNullOrWhiteSpace(notificationType) ?
- null :
- GetConfiguration().GetOptions(notificationType);
-
- var users = GetUserIds(request, options)
- .Select(i => _userManager.GetUserById(i));
-
- var title = GetTitle(request, options);
- var description = GetDescription(request, options);
-
- var tasks = _services.Where(i => IsEnabled(i, notificationType))
- .Select(i => SendNotification(request, i, users, title, description, cancellationToken));
-
- return Task.WhenAll(tasks);
- }
-
- private Task SendNotification(NotificationRequest request,
- INotificationService service,
- IEnumerable<User> users,
- string title,
- string description,
- CancellationToken cancellationToken)
- {
- users = users.Where(i => IsEnabledForUser(service, i))
- .ToList();
-
- var tasks = users.Select(i => SendNotification(request, service, title, description, i, cancellationToken));
-
- return Task.WhenAll(tasks);
-
- }
-
- private IEnumerable<string> GetUserIds(NotificationRequest request, NotificationOption options)
- {
- if (request.SendToUserMode.HasValue)
- {
- switch (request.SendToUserMode.Value)
- {
- case SendToUserType.Admins:
- return _userManager.Users.Where(i => i.Policy.IsAdministrator)
- .Select(i => i.Id.ToString("N"));
- case SendToUserType.All:
- return _userManager.Users.Select(i => i.Id.ToString("N"));
- case SendToUserType.Custom:
- return request.UserIds;
- default:
- throw new ArgumentException("Unrecognized SendToUserMode: " + request.SendToUserMode.Value);
- }
- }
-
- if (options != null && !string.IsNullOrWhiteSpace(request.NotificationType))
- {
- var config = GetConfiguration();
-
- return _userManager.Users
- .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N"), i.Policy))
- .Select(i => i.Id.ToString("N"));
- }
-
- return request.UserIds;
- }
-
- private async Task SendNotification(NotificationRequest request,
- INotificationService service,
- string title,
- string description,
- User user,
- CancellationToken cancellationToken)
- {
- var notification = new UserNotification
- {
- Date = request.Date,
- Description = description,
- Level = request.Level,
- Name = title,
- 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 string GetTitle(NotificationRequest request, NotificationOption options)
- {
- var title = request.Name;
-
- // If empty, grab from options
- if (string.IsNullOrEmpty(title))
- {
- if (!string.IsNullOrEmpty(request.NotificationType))
- {
- if (options != null)
- {
- title = options.Title;
- }
- }
- }
-
- // If still empty, grab default
- if (string.IsNullOrEmpty(title))
- {
- if (!string.IsNullOrEmpty(request.NotificationType))
- {
- var info = GetNotificationTypes().FirstOrDefault(i => string.Equals(i.Type, request.NotificationType, StringComparison.OrdinalIgnoreCase));
-
- if (info != null)
- {
- title = info.DefaultTitle;
- }
- }
- }
-
- title = title ?? string.Empty;
-
- foreach (var pair in request.Variables)
- {
- var token = "{" + pair.Key + "}";
-
- title = title.Replace(token, pair.Value, StringComparison.OrdinalIgnoreCase);
- }
-
- return title;
- }
-
- private string GetDescription(NotificationRequest request, NotificationOption options)
- {
- var text = request.Description;
-
- // If empty, grab from options
- if (string.IsNullOrEmpty(text))
- {
- if (!string.IsNullOrEmpty(request.NotificationType))
- {
- if (options != null)
- {
- text = options.Description;
- }
- }
- }
-
- // If still empty, grab default
- if (string.IsNullOrEmpty(text))
- {
- if (!string.IsNullOrEmpty(request.NotificationType))
- {
- var info = GetNotificationTypes().FirstOrDefault(i => string.Equals(i.Type, request.NotificationType, StringComparison.OrdinalIgnoreCase));
-
- if (info != null)
- {
- text = info.DefaultDescription;
- }
- }
- }
-
- text = text ?? string.Empty;
-
- foreach (var pair in request.Variables)
- {
- var token = "{" + pair.Key + "}";
-
- text = text.Replace(token, pair.Value, StringComparison.OrdinalIgnoreCase);
- }
-
- return text;
- }
-
- private bool IsEnabledForUser(INotificationService service, User user)
- {
- try
- {
- return service.IsEnabledForUser(user);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error in IsEnabledForUser", ex);
- return false;
- }
- }
-
- private bool IsEnabled(INotificationService service, string notificationType)
- {
- if (string.IsNullOrEmpty(notificationType))
- {
- return true;
- }
-
- var configurable = service as IConfigurableNotificationService;
-
- if (configurable != null)
- {
- return configurable.IsEnabled(notificationType);
- }
-
- return GetConfiguration().IsServiceEnabled(service.Name, notificationType);
- }
-
- public void AddParts(IEnumerable<INotificationService> services, IEnumerable<INotificationTypeFactory> notificationTypeFactories)
- {
- _services = services.ToArray();
- _typeFactories = notificationTypeFactories.ToArray();
- }
-
- public IEnumerable<NotificationTypeInfo> GetNotificationTypes()
- {
- var list = _typeFactories.Select(i =>
- {
- try
- {
- return i.GetNotificationTypes().ToList();
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error in GetNotificationTypes", ex);
- return new List<NotificationTypeInfo>();
- }
-
- }).SelectMany(i => i).ToList();
-
- var config = GetConfiguration();
-
- foreach (var i in list)
- {
- i.Enabled = config.IsEnabled(i.Type);
- }
-
- return list;
- }
-
- public IEnumerable<NotificationServiceInfo> GetNotificationServices()
- {
- return _services.Where(i =>
- {
- var configurable = i as IConfigurableNotificationService;
-
- return configurable == null || !configurable.IsHidden;
-
- }).Select(i => new NotificationServiceInfo
- {
- Name = i.Name,
- Id = i.Name.GetMD5().ToString("N")
-
- }).OrderBy(i => i.Name);
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs b/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs
deleted file mode 100644
index f30ba3e54..000000000
--- a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs
+++ /dev/null
@@ -1,470 +0,0 @@
-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.Notifications
-{
- public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository
- {
- public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector dbConnector) : base(logManager, dbConnector)
- {
- DbFilePath = Path.Combine(appPaths.DataPath, "notifications.db");
- }
-
- public event EventHandler<NotificationUpdateEventArgs> NotificationAdded;
- public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead;
- ////public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
-
- public async Task Initialize()
- {
- using (var connection = await CreateConnection().ConfigureAwait(false))
- {
- 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_Notifications1 on Notifications(Id)",
- "create index if not exists idx_Notifications2 on Notifications(UserId)"
- };
-
- connection.RunQueries(queries, Logger);
- }
- }
-
- /// <summary>
- /// Gets the notifications.
- /// </summary>
- /// <param name="query">The query.</param>
- /// <returns>NotificationResult.</returns>
- public NotificationResult GetNotifications(NotificationQuery query)
- {
- var result = new NotificationResult();
-
- using (var connection = CreateConnection(true).Result)
- {
- using (var cmd = connection.CreateCommand())
- {
- var clauses = new List<string>();
-
- if (query.IsRead.HasValue)
- {
- clauses.Add("IsRead=@IsRead");
- cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = query.IsRead.Value;
- }
-
- clauses.Add("UserId=@UserId");
- cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = new Guid(query.UserId);
-
- var 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(string userId)
- {
- var result = new NotificationsSummary();
-
- using (var connection = CreateConnection(true).Result)
- {
- 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 = new Guid(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)
- {
- var list = new List<Notification>();
-
- while (reader.Read())
- {
- list.Add(GetNotification(reader));
- }
-
- return list;
- }
-
- private Notification GetNotification(IDataReader reader)
- {
- var notification = new Notification
- {
- Id = reader.GetGuid(0).ToString("N"),
- UserId = reader.GetGuid(1).ToString("N"),
- 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);
-
- return notification;
- }
-
- /// <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>
- /// 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 (string.IsNullOrEmpty(notification.Id))
- {
- notification.Id = Guid.NewGuid().ToString("N");
- }
- if (string.IsNullOrEmpty(notification.UserId))
- {
- throw new ArgumentException("The notification must have a user id");
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using (var connection = await CreateConnection().ConfigureAwait(false))
- {
- using (var 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");
-
- IDbTransaction transaction = null;
-
- try
- {
- transaction = connection.BeginTransaction();
-
- 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 = string.Empty;
- replaceNotificationCommand.GetParameter(9).Value = string.Empty;
-
- 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();
- }
- }
- }
- }
- }
-
- /// <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<string> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken)
- {
- var list = notificationIdList.ToList();
- var idArray = list.Select(i => new Guid(i)).ToArray();
-
- await MarkReadInternal(idArray, userId, isRead, cancellationToken).ConfigureAwait(false);
-
- if (NotificationsMarkedRead != null)
- {
- try
- {
- NotificationsMarkedRead(this, new NotificationReadEventArgs
- {
- IdList = list.ToArray(),
- IsRead = isRead,
- UserId = userId
- });
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error in NotificationsMarkedRead event handler", ex);
- }
- }
- }
-
- public async Task MarkAllRead(string userId, bool isRead, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- using (var connection = await CreateConnection().ConfigureAwait(false))
- {
- using (var markAllReadCommand = connection.CreateCommand())
- {
- markAllReadCommand.CommandText = "update Notifications set IsRead=@IsRead where UserId=@UserId";
-
- markAllReadCommand.Parameters.Add(markAllReadCommand, "@UserId");
- markAllReadCommand.Parameters.Add(markAllReadCommand, "@IsRead");
-
- IDbTransaction transaction = null;
-
- try
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- transaction = connection.BeginTransaction();
-
- markAllReadCommand.GetParameter(0).Value = new Guid(userId);
- markAllReadCommand.GetParameter(1).Value = isRead;
-
- markAllReadCommand.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();
- }
- }
- }
- }
- }
-
- private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- using (var connection = await CreateConnection().ConfigureAwait(false))
- {
- using (var markReadCommand = connection.CreateCommand())
- {
- markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId";
-
- markReadCommand.Parameters.Add(markReadCommand, "@UserId");
- markReadCommand.Parameters.Add(markReadCommand, "@IsRead");
- markReadCommand.Parameters.Add(markReadCommand, "@Id");
-
- IDbTransaction transaction = null;
-
- try
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- transaction = connection.BeginTransaction();
-
- markReadCommand.GetParameter(0).Value = new Guid(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();
- }
- }
- }
- }
- }
- }
-}