aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/EntryPoints
diff options
context:
space:
mode:
authorLuke Pulverenti <luke.pulverenti@gmail.com>2016-11-03 03:14:14 -0400
committerLuke Pulverenti <luke.pulverenti@gmail.com>2016-11-03 03:14:14 -0400
commitb76a1abda578b8ff64bad2997b036b0fc43e264f (patch)
tree7b73000abcf71e90c290b6107525969cb904ed2d /MediaBrowser.Server.Implementations/EntryPoints
parent3eb4091808735858b01855d298226d239be464af (diff)
move classes to portable server lib
Diffstat (limited to 'MediaBrowser.Server.Implementations/EntryPoints')
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs561
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs544
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs54
3 files changed, 0 insertions, 1159 deletions
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs
deleted file mode 100644
index 51f5f57b3..000000000
--- a/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs
+++ /dev/null
@@ -1,561 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Tasks;
-using MediaBrowser.Model.Updates;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using MediaBrowser.Model.Globalization;
-
-namespace MediaBrowser.Server.Implementations.EntryPoints
-{
- public class ActivityLogEntryPoint : IServerEntryPoint
- {
- private readonly IInstallationManager _installationManager;
-
- //private readonly ILogManager _logManager;
- //private readonly ILogger _logger;
- private readonly ISessionManager _sessionManager;
- private readonly ITaskManager _taskManager;
- private readonly IActivityManager _activityManager;
- private readonly ILocalizationManager _localization;
-
- private readonly ILibraryManager _libraryManager;
- private readonly ISubtitleManager _subManager;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
- private readonly IServerApplicationHost _appHost;
-
- public ActivityLogEntryPoint(ISessionManager sessionManager, ITaskManager taskManager, IActivityManager activityManager, ILocalizationManager localization, IInstallationManager installationManager, ILibraryManager libraryManager, ISubtitleManager subManager, IUserManager userManager, IServerConfigurationManager config, IServerApplicationHost appHost)
- {
- //_logger = _logManager.GetLogger("ActivityLogEntryPoint");
- _sessionManager = sessionManager;
- _taskManager = taskManager;
- _activityManager = activityManager;
- _localization = localization;
- _installationManager = installationManager;
- _libraryManager = libraryManager;
- _subManager = subManager;
- _userManager = userManager;
- _config = config;
- //_logManager = logManager;
- _appHost = appHost;
- }
-
- public void Run()
- {
- //_taskManager.TaskExecuting += _taskManager_TaskExecuting;
- //_taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
- //_installationManager.PluginInstalled += _installationManager_PluginInstalled;
- //_installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
- //_installationManager.PluginUpdated += _installationManager_PluginUpdated;
-
- //_libraryManager.ItemAdded += _libraryManager_ItemAdded;
- //_libraryManager.ItemRemoved += _libraryManager_ItemRemoved;
-
- _sessionManager.SessionStarted += _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded += _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
-
- //_subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
- _subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated += _userManager_UserCreated;
- _userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
- _userManager.UserDeleted += _userManager_UserDeleted;
- _userManager.UserConfigurationUpdated += _userManager_UserConfigurationUpdated;
- _userManager.UserLockedOut += _userManager_UserLockedOut;
-
- //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
- //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
-
- //_logManager.LoggerLoaded += _logManager_LoggerLoaded;
-
- _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
- }
-
- void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name),
- Type = "UserLockedOut",
- UserId = e.Argument.Id.ToString("N")
- });
- }
-
- void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureForItem"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitleDownloadFailure",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider),
- Overview = LogHelper.GetLogMessage(e.Exception).ToString()
- });
- }
-
- void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.Warn("PlaybackStopped reported with null media info.");
- return;
- }
-
- if (item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, item.Name),
- Type = "PlaybackStopped",
- ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName),
- UserId = user.Id.ToString("N")
- });
- }
-
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.Warn("PlaybackStart reported with null media info.");
- return;
- }
-
- if (item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, item.Name),
- Type = "PlaybackStart",
- ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName),
- UserId = user.Id.ToString("N")
- });
- }
-
- void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrWhiteSpace(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionEnded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId.HasValue ? session.UserId.Value.ToString("N") : null
- });
- }
-
- void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationRequest> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), e.Argument.Username),
- Type = "AuthenticationSucceeded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint)
- });
- }
-
- void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
- Type = "AuthenticationFailed",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
- Severity = LogSeverity.Error
- });
- }
-
- void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = _localization.GetLocalizedString("MessageApplicationUpdated"),
- Type = "ApplicationUpdated",
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr),
- Overview = e.Argument.description
- });
- }
-
- void _logManager_LoggerLoaded(object sender, EventArgs e)
- {
- }
-
- void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
- Type = "NamedConfigurationUpdated"
- });
- }
-
- void _config_ConfigurationUpdated(object sender, EventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
- Type = "ServerConfigurationUpdated"
- });
- }
-
- void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserConfigurationUpdatedWithName"), e.Argument.Name),
- Type = "UserConfigurationUpdated",
- UserId = e.Argument.Id.ToString("N")
- });
- }
-
- void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
- Type = "UserDeleted"
- });
- }
-
- void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
- Type = "UserPasswordChanged",
- UserId = e.Argument.Id.ToString("N")
- });
- }
-
- void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
- Type = "UserCreated",
- UserId = e.Argument.Id.ToString("N")
- });
- }
-
- void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitlesDownloaded",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
- });
- }
-
- void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrWhiteSpace(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionStarted",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId.HasValue ? session.UserId.Value.ToString("N") : null
- });
- }
-
- void _libraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
- {
- if (e.Item.SourceType != SourceType.Library)
- {
- return;
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ItemRemovedWithName"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "ItemRemoved"
- });
- }
-
- void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
- {
- if (e.Item.SourceType != SourceType.Library)
- {
- return;
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ItemAddedWithName"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "ItemAdded",
- ItemId = e.Item.Id.ToString("N")
- });
- }
-
- void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
- Type = "PluginUpdated",
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
- Overview = e.Argument.Item2.description
- });
- }
-
- void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
- Type = "PluginUninstalled"
- });
- }
-
- void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
- Type = "PluginInstalled",
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
- });
- }
-
- void _taskManager_TaskExecuting(object sender, GenericEventArgs<IScheduledTaskWorker> e)
- {
- var task = e.Argument;
-
- var activityTask = task.ScheduledTask as IConfigurableScheduledTask;
- if (activityTask != null && !activityTask.IsLogged)
- {
- return;
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ScheduledTaskStartedWithName"), task.Name),
- Type = "ScheduledTaskStarted"
- });
- }
-
- void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- var result = e.Result;
- var task = e.Task;
-
- var activityTask = task.ScheduledTask as IConfigurableScheduledTask;
- if (activityTask != null && !activityTask.IsLogged)
- {
- return;
- }
-
- var time = result.EndTimeUtc - result.StartTimeUtc;
- var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
-
- if (result.Status == TaskCompletionStatus.Failed)
- {
- var vals = new List<string>();
-
- if (!string.IsNullOrWhiteSpace(e.Result.ErrorMessage))
- {
- vals.Add(e.Result.ErrorMessage);
- }
- if (!string.IsNullOrWhiteSpace(e.Result.LongErrorMessage))
- {
- vals.Add(e.Result.LongErrorMessage);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
- Type = "ScheduledTaskFailed",
- Overview = string.Join(Environment.NewLine, vals.ToArray()),
- ShortOverview = runningTime,
- Severity = LogSeverity.Error
- });
- }
- }
-
- private async void CreateLogEntry(ActivityLogEntry entry)
- {
- try
- {
- await _activityManager.Create(entry).ConfigureAwait(false);
- }
- catch
- {
- // Logged at lower levels
- }
- }
-
- public void Dispose()
- {
- _taskManager.TaskExecuting -= _taskManager_TaskExecuting;
- _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
-
- _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
- _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
- _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
-
- _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
- _libraryManager.ItemRemoved -= _libraryManager_ItemRemoved;
-
- _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
-
- _subManager.SubtitlesDownloaded -= _subManager_SubtitlesDownloaded;
- _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated -= _userManager_UserCreated;
- _userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
- _userManager.UserDeleted -= _userManager_UserDeleted;
- _userManager.UserConfigurationUpdated -= _userManager_UserConfigurationUpdated;
- _userManager.UserLockedOut -= _userManager_UserLockedOut;
-
- _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
- _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
-
- //_logManager.LoggerLoaded -= _logManager_LoggerLoaded;
-
- _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
- }
-
- /// <summary>
- /// Constructs a user-friendly string for this TimeSpan instance.
- /// </summary>
- public static string ToUserFriendlyString(TimeSpan span)
- {
- const int DaysInYear = 365;
- const int DaysInMonth = 30;
-
- // Get each non-zero value from TimeSpan component
- List<string> values = new List<string>();
-
- // Number of years
- int days = span.Days;
- if (days >= DaysInYear)
- {
- int years = days / DaysInYear;
- values.Add(CreateValueString(years, "year"));
- days = days % DaysInYear;
- }
- // Number of months
- if (days >= DaysInMonth)
- {
- int months = days / DaysInMonth;
- values.Add(CreateValueString(months, "month"));
- days = days % DaysInMonth;
- }
- // Number of days
- if (days >= 1)
- values.Add(CreateValueString(days, "day"));
- // Number of hours
- if (span.Hours >= 1)
- values.Add(CreateValueString(span.Hours, "hour"));
- // Number of minutes
- if (span.Minutes >= 1)
- values.Add(CreateValueString(span.Minutes, "minute"));
- // Number of seconds (include when 0 if no other components included)
- if (span.Seconds >= 1 || values.Count == 0)
- values.Add(CreateValueString(span.Seconds, "second"));
-
- // Combine values into string
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < values.Count; i++)
- {
- if (builder.Length > 0)
- builder.Append(i == values.Count - 1 ? " and " : ", ");
- builder.Append(values[i]);
- }
- // Return result
- return builder.ToString();
- }
-
- /// <summary>
- /// Constructs a string description of a time-span value.
- /// </summary>
- /// <param name="value">The value of this item</param>
- /// <param name="description">The name of this item (singular form)</param>
- private static string CreateValueString(int value, string description)
- {
- return String.Format("{0:#,##0} {1}",
- value, value == 1 ? description : String.Format("{0}s", description));
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs
deleted file mode 100644
index f3d1dc8f9..000000000
--- a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs
+++ /dev/null
@@ -1,544 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Notifications;
-using MediaBrowser.Model.Tasks;
-using MediaBrowser.Model.Updates;
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities.TV;
-
-namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
-{
- /// <summary>
- /// Creates notifications for various system events
- /// </summary>
- public class Notifications : IServerEntryPoint
- {
- private readonly IInstallationManager _installationManager;
- private readonly IUserManager _userManager;
- private readonly ILogger _logger;
-
- private readonly ITaskManager _taskManager;
- private readonly INotificationManager _notificationManager;
-
- private readonly ILibraryManager _libraryManager;
- private readonly ISessionManager _sessionManager;
- private readonly IServerApplicationHost _appHost;
-
- private Timer LibraryUpdateTimer { get; set; }
- private readonly object _libraryChangedSyncLock = new object();
-
- private readonly IConfigurationManager _config;
- private readonly IDeviceManager _deviceManager;
-
- public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager, ILibraryManager libraryManager, ISessionManager sessionManager, IServerApplicationHost appHost, IConfigurationManager config, IDeviceManager deviceManager)
- {
- _installationManager = installationManager;
- _userManager = userManager;
- _logger = logger;
- _taskManager = taskManager;
- _notificationManager = notificationManager;
- _libraryManager = libraryManager;
- _sessionManager = sessionManager;
- _appHost = appHost;
- _config = config;
- _deviceManager = deviceManager;
- }
-
- public void Run()
- {
- _installationManager.PluginInstalled += _installationManager_PluginInstalled;
- _installationManager.PluginUpdated += _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
- _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
-
- _taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
- _userManager.UserCreated += _userManager_UserCreated;
- _libraryManager.ItemAdded += _libraryManager_ItemAdded;
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
- _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
- _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged;
- _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
- _deviceManager.CameraImageUploaded += _deviceManager_CameraImageUploaded;
-
- _userManager.UserLockedOut += _userManager_UserLockedOut;
- }
-
- async void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
- {
- var type = NotificationType.UserLockedOut.ToString();
-
- var notification = new NotificationRequest
- {
- NotificationType = type
- };
-
- notification.Variables["UserName"] = e.Argument.Name;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
- {
- var type = NotificationType.CameraImageUploaded.ToString();
-
- var notification = new NotificationRequest
- {
- NotificationType = type
- };
-
- notification.Variables["DeviceName"] = e.Argument.Device.Name;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- var type = NotificationType.ApplicationUpdateInstalled.ToString();
-
- var notification = new NotificationRequest
- {
- NotificationType = type,
- Url = e.Argument.infoUrl
- };
-
- notification.Variables["Version"] = e.Argument.versionStr;
- notification.Variables["ReleaseNotes"] = e.Argument.description;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
- {
- var type = NotificationType.PluginUpdateInstalled.ToString();
-
- var installationInfo = e.Argument.Item1;
-
- var notification = new NotificationRequest
- {
- Description = e.Argument.Item2.description,
- NotificationType = type
- };
-
- notification.Variables["Name"] = installationInfo.Name;
- notification.Variables["Version"] = installationInfo.Version.ToString();
- notification.Variables["ReleaseNotes"] = e.Argument.Item2.description;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- var type = NotificationType.PluginInstalled.ToString();
-
- var installationInfo = e.Argument;
-
- var notification = new NotificationRequest
- {
- Description = installationInfo.description,
- NotificationType = type
- };
-
- notification.Variables["Name"] = installationInfo.name;
- notification.Variables["Version"] = installationInfo.versionStr;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e)
- {
- // This notification is for users who can't auto-update (aka running as service)
- if (!_appHost.HasUpdateAvailable || _appHost.CanSelfUpdate)
- {
- return;
- }
-
- var type = NotificationType.ApplicationUpdateAvailable.ToString();
-
- var notification = new NotificationRequest
- {
- Description = "Please see emby.media for details.",
- NotificationType = type
- };
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
- {
- if (!_appHost.HasPendingRestart)
- {
- return;
- }
-
- var type = NotificationType.ServerRestartRequired.ToString();
-
- var notification = new NotificationRequest
- {
- NotificationType = type
- };
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- private NotificationOptions GetOptions()
- {
- return _config.GetConfiguration<NotificationOptions>("notifications");
- }
-
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- _logger.Warn("PlaybackStart reported with null media info.");
- return;
- }
-
- var video = e.Item as Video;
- if (video != null && video.IsThemeMedia)
- {
- return;
- }
-
- var type = GetPlaybackNotificationType(item.MediaType);
-
- SendPlaybackNotification(type, e);
- }
-
- void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- _logger.Warn("PlaybackStopped reported with null media info.");
- return;
- }
-
- var video = e.Item as Video;
- if (video != null && video.IsThemeMedia)
- {
- return;
- }
-
- var type = GetPlaybackStoppedNotificationType(item.MediaType);
-
- SendPlaybackNotification(type, e);
- }
-
- private async void SendPlaybackNotification(string type, PlaybackProgressEventArgs e)
- {
- var user = e.Users.FirstOrDefault();
-
- if (user != null && !GetOptions().IsEnabledToMonitorUser(type, user.Id.ToString("N")))
- {
- return;
- }
-
- var item = e.MediaInfo;
-
- if ( item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- var notification = new NotificationRequest
- {
- NotificationType = type
- };
-
- if (e.Item != null)
- {
- notification.Variables["ItemName"] = GetItemName(e.Item);
- }
- else
- {
- notification.Variables["ItemName"] = item.Name;
- }
-
- notification.Variables["UserName"] = user == null ? "Unknown user" : user.Name;
- notification.Variables["AppName"] = e.ClientName;
- notification.Variables["DeviceName"] = e.DeviceName;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- private string GetPlaybackNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlayback.ToString();
- }
- if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.GamePlayback.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlayback.ToString();
- }
-
- return null;
- }
-
- private string GetPlaybackStoppedNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlaybackStopped.ToString();
- }
- if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.GamePlaybackStopped.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlaybackStopped.ToString();
- }
-
- return null;
- }
-
- private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
- void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
- {
- if (!FilterItem(e.Item))
- {
- return;
- }
-
- lock (_libraryChangedSyncLock)
- {
- if (LibraryUpdateTimer == null)
- {
- LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000,
- Timeout.Infinite);
- }
- else
- {
- LibraryUpdateTimer.Change(5000, Timeout.Infinite);
- }
-
- _itemsAdded.Add(e.Item);
- }
- }
-
- private bool FilterItem(BaseItem item)
- {
- if (item.IsFolder)
- {
- return false;
- }
-
- if (item.LocationType == LocationType.Virtual)
- {
- return false;
- }
-
- if (item is IItemByName)
- {
- return false;
- }
-
- return item.SourceType == SourceType.Library;
- }
-
- private async void LibraryUpdateTimerCallback(object state)
- {
- List<BaseItem> items;
-
- lock (_libraryChangedSyncLock)
- {
- items = _itemsAdded.ToList();
- _itemsAdded.Clear();
- DisposeLibraryUpdateTimer();
- }
-
- items = items.Take(10).ToList();
-
- foreach (var item in items)
- {
- var notification = new NotificationRequest
- {
- NotificationType = NotificationType.NewLibraryContent.ToString()
- };
-
- notification.Variables["Name"] = GetItemName(item);
-
- await SendNotification(notification).ConfigureAwait(false);
- }
- }
-
- public static string GetItemName(BaseItem item)
- {
- var name = item.Name;
- var episode = item as Episode;
- if (episode != null)
- {
- if (episode.IndexNumber.HasValue)
- {
- name = string.Format("Ep{0} - {1}", episode.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
- }
- if (episode.ParentIndexNumber.HasValue)
- {
- name = string.Format("S{0}, {1}", episode.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
- }
- }
-
- var hasSeries = item as IHasSeries;
-
- if (hasSeries != null)
- {
- name = hasSeries.SeriesName + " - " + name;
- }
-
- var hasArtist = item as IHasArtist;
- if (hasArtist != null)
- {
- var artists = hasArtist.AllArtists;
-
- if (artists.Count > 0)
- {
- name = hasArtist.AllArtists[0] + " - " + name;
- }
- }
-
- return name;
- }
-
- async void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
- {
- var notification = new NotificationRequest
- {
- UserIds = new List<string> { e.Argument.Id.ToString("N") },
- Name = "Welcome to Emby!",
- Description = "Check back here for more notifications."
- };
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- var result = e.Result;
-
- if (result.Status == TaskCompletionStatus.Failed)
- {
- var type = NotificationType.TaskFailed.ToString();
-
- var notification = new NotificationRequest
- {
- Description = result.ErrorMessage,
- Level = NotificationLevel.Error,
- NotificationType = type
- };
-
- notification.Variables["Name"] = result.Name;
- notification.Variables["ErrorMessage"] = result.ErrorMessage;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
- }
-
- async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
- {
- var type = NotificationType.PluginUninstalled.ToString();
-
- var plugin = e.Argument;
-
- var notification = new NotificationRequest
- {
- NotificationType = type
- };
-
- notification.Variables["Name"] = plugin.Name;
- notification.Variables["Version"] = plugin.Version.ToString();
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
- {
- var installationInfo = e.InstallationInfo;
-
- var type = NotificationType.InstallationFailed.ToString();
-
- var notification = new NotificationRequest
- {
- Level = NotificationLevel.Error,
- Description = e.Exception.Message,
- NotificationType = type
- };
-
- notification.Variables["Name"] = installationInfo.Name;
- notification.Variables["Version"] = installationInfo.Version;
-
- await SendNotification(notification).ConfigureAwait(false);
- }
-
- private async Task SendNotification(NotificationRequest notification)
- {
- try
- {
- await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error sending notification", ex);
- }
- }
-
- public void Dispose()
- {
- DisposeLibraryUpdateTimer();
-
- _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
- _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
- _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
-
- _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
-
- _userManager.UserCreated -= _userManager_UserCreated;
- _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
-
- _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
- _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
- _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
-
- _deviceManager.CameraImageUploaded -= _deviceManager_CameraImageUploaded;
- _userManager.UserLockedOut -= _userManager_UserLockedOut;
- }
-
- private void DisposeLibraryUpdateTimer()
- {
- if (LibraryUpdateTimer != null)
- {
- LibraryUpdateTimer.Dispose();
- LibraryUpdateTimer = null;
- }
- }
- }
-}
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs
deleted file mode 100644
index 916b4a622..000000000
--- a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Controller.Plugins;
-using System.Linq;
-
-namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
-{
- /// <summary>
- /// Notifies clients 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.NotificationsMarkedRead += _notificationsRepo_NotificationsMarkedRead;
- }
-
- void _notificationsRepo_NotificationsMarkedRead(object sender, NotificationReadEventArgs e)
- {
- var list = e.IdList.ToList();
-
- list.Add(e.UserId);
- list.Add(e.IsRead.ToString().ToLower());
-
- var msg = string.Join("|", list.ToArray());
-
- _serverManager.SendWebSocketMessage("NotificationsMarkedRead", 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;
- }
- }
-}