aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/EntryPoints
diff options
context:
space:
mode:
author7illusions <z@7illusions.com>2014-08-30 19:06:58 +0200
committer7illusions <z@7illusions.com>2014-08-30 19:06:58 +0200
commit66ad1699e22029b605e17735e8d9450285d8748a (patch)
treeffc92c88d24850b2f82b6b3a8bdd904a2ccc77a5 /MediaBrowser.Server.Implementations/EntryPoints
parent34bc54263e886aae777a3537dc50a6535b51330a (diff)
parent9d36f518182bc075c19d78084870f5115fa62d1e (diff)
Merge pull request #1 from MediaBrowser/master
Update to latest
Diffstat (limited to 'MediaBrowser.Server.Implementations/EntryPoints')
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs569
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs55
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs55
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs9
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/ServerEventNotifier.cs6
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs28
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs1
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs45
8 files changed, 694 insertions, 74 deletions
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs
new file mode 100644
index 000000000..fb1010f1b
--- /dev/null
+++ b/MediaBrowser.Server.Implementations/EntryPoints/ActivityLogEntryPoint.cs
@@ -0,0 +1,569 @@
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Implementations.Logging;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Common.ScheduledTasks;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Activity;
+using MediaBrowser.Controller.Channels;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Localization;
+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;
+
+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;
+
+ //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
+ //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
+
+ //_logManager.LoggerLoaded += _logManager_LoggerLoaded;
+
+ _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
+ }
+
+ 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;
+ }
+
+ var themeMedia = item as IThemeMedia;
+ if (themeMedia != null && themeMedia.IsThemeMedia)
+ {
+ // Don't report theme song or local trailer playback
+ return;
+ }
+
+ if (e.Users.Count == 0)
+ {
+ return;
+ }
+
+ var username = e.Users.First().Name;
+
+ CreateLogEntry(new ActivityLogEntry
+ {
+ Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), username, item.Name),
+ Type = "PlaybackStopped",
+ ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
+ });
+ }
+
+ void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
+ {
+ var item = e.MediaInfo;
+
+ if (item == null)
+ {
+ //_logger.Warn("PlaybackStart reported with null media info.");
+ return;
+ }
+
+ var themeMedia = item as IThemeMedia;
+ if (themeMedia != null && themeMedia.IsThemeMedia)
+ {
+ // Don't report theme song or local trailer playback
+ return;
+ }
+
+ if (e.Users.Count == 0)
+ {
+ return;
+ }
+
+ var username = e.Users.First().Name;
+
+ CreateLogEntry(new ActivityLogEntry
+ {
+ Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), username, item.Name),
+ Type = "PlaybackStart",
+ ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
+ });
+ }
+
+ 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)
+ });
+ }
+
+ 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"
+ });
+ }
+
+ 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"
+ });
+ }
+
+ void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
+ {
+ CreateLogEntry(new ActivityLogEntry
+ {
+ Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
+ Type = "UserCreated"
+ });
+ }
+
+ 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)
+ });
+ }
+
+ void _libraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
+ {
+ if (e.Item is LiveTvProgram || e.Item is IChannelItem)
+ {
+ 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 is LiveTvProgram || e.Item is IChannelItem)
+ {
+ 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 IScheduledTaskActivityLog;
+ if (activityTask != null && !activityTask.IsActivityLogged)
+ {
+ 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 IScheduledTaskActivityLog;
+ if (activityTask != null && !activityTask.IsActivityLogged)
+ {
+ return;
+ }
+
+ var time = result.EndTimeUtc - result.StartTimeUtc;
+ var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
+
+ if (result.Status == TaskCompletionStatus.Cancelled)
+ {
+ return;
+ CreateLogEntry(new ActivityLogEntry
+ {
+ Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCancelledWithName"), task.Name),
+ Type = "ScheduledTaskCancelled",
+ ShortOverview = runningTime
+ });
+ }
+ else if (result.Status == TaskCompletionStatus.Completed)
+ {
+ return;
+ CreateLogEntry(new ActivityLogEntry
+ {
+ Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCompletedWithName"), task.Name),
+ Type = "ScheduledTaskCompleted",
+ ShortOverview = runningTime
+ });
+ }
+ else 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;
+
+ _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/ExternalPortForwarding.cs b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index 04ddb4c4b..2d050d4a7 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -4,8 +4,10 @@ using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using Mono.Nat;
using System;
+using System.Collections.Generic;
using System.IO;
using System.Text;
+using System.Threading;
namespace MediaBrowser.Server.Implementations.EntryPoints
{
@@ -17,6 +19,8 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
private bool _isStarted;
+ private Timer _timer;
+
public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config)
{
_logger = logmanager.GetLogger("PortMapper");
@@ -43,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
public void Run()
{
//NatUtility.Logger = new LogWriter(_logger);
-
+
Reload();
}
@@ -52,13 +56,22 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
if (_config.Configuration.EnableUPnP)
{
_logger.Debug("Starting NAT discovery");
-
+
NatUtility.DeviceFound += NatUtility_DeviceFound;
+
+ // Mono.Nat does never rise this event. The event is there however it is useless.
+ // You could remove it with no risk.
NatUtility.DeviceLost += NatUtility_DeviceLost;
+
+
+ // it is hard to say what one should do when an unhandled exception is raised
+ // because there isn't anything one can do about it. Probably save a log or ignored it.
NatUtility.UnhandledException += NatUtility_UnhandledException;
NatUtility.StartDiscovery();
_isStarted = true;
+
+ _timer = new Timer(s => _createdRules = new List<string>(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
}
}
@@ -88,19 +101,32 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
}
catch (Exception)
{
+ // I think it could be a good idea to log the exception because
+ // you are using permanent portmapping here (never expire) and that means that next time
+ // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
+ // on the router's upnp implementation (specs says it should fail however some routers don't do it)
+ // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
+ // and those errors (upnp errors) could be useful for diagnosting.
+
//_logger.ErrorException("Error creating port forwarding rules", ex);
}
}
+ private List<string> _createdRules = new List<string>();
private void CreateRules(INatDevice device)
{
- var info = _appHost.GetSystemInfo();
+ // On some systems the device discovered event seems to fire repeatedly
+ // This check will help ensure we're not trying to port map the same device over and over
- CreatePortMap(device, info.HttpServerPortNumber);
+ var address = device.LocalAddress.ToString();
- if (info.WebSocketPortNumber != info.HttpServerPortNumber)
+ if (!_createdRules.Contains(address))
{
- CreatePortMap(device, info.WebSocketPortNumber);
+ _createdRules.Add(address);
+
+ var info = _appHost.GetSystemInfo();
+
+ CreatePortMap(device, info.HttpServerPortNumber);
}
}
@@ -114,6 +140,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
});
}
+ // As I said before, this method will be never invoked. You can remove it.
void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
{
var device = e.Device;
@@ -129,13 +156,27 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
{
_logger.Debug("Stopping NAT discovery");
+ if (_timer != null)
+ {
+ _timer.Dispose();
+ _timer = null;
+ }
+
try
{
+ // This is not a significant improvement
+ NatUtility.StopDiscovery();
NatUtility.DeviceFound -= NatUtility_DeviceFound;
NatUtility.DeviceLost -= NatUtility_DeviceLost;
NatUtility.UnhandledException -= NatUtility_UnhandledException;
- NatUtility.StopDiscovery();
}
+ // Statements in try-block will no fail because StopDiscovery is a one-line
+ // method that was no chances to fail.
+ // public static void StopDiscovery ()
+ // {
+ // searching.Reset();
+ // }
+ // IMO you could remove the catch-block
catch (Exception ex)
{
_logger.ErrorException("Error stopping NAT Discovery", ex);
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs
index b10b64c3e..2d824f36c 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/Notifications.cs
@@ -1,15 +1,14 @@
-using MediaBrowser.Common.Plugins;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
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.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Logging;
@@ -37,7 +36,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
private readonly ITaskManager _taskManager;
private readonly INotificationManager _notificationManager;
- private readonly IServerConfigurationManager _config;
private readonly ILibraryManager _libraryManager;
private readonly ISessionManager _sessionManager;
private readonly IServerApplicationHost _appHost;
@@ -45,17 +43,19 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
private Timer LibraryUpdateTimer { get; set; }
private readonly object _libraryChangedSyncLock = new object();
- public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager, IServerConfigurationManager config, ILibraryManager libraryManager, ISessionManager sessionManager, IServerApplicationHost appHost)
+ private readonly IConfigurationManager _config;
+
+ public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager, ILibraryManager libraryManager, ISessionManager sessionManager, IServerApplicationHost appHost, IConfigurationManager config)
{
_installationManager = installationManager;
_userManager = userManager;
_logger = logger;
_taskManager = taskManager;
_notificationManager = notificationManager;
- _config = config;
_libraryManager = libraryManager;
_sessionManager = sessionManager;
_appHost = appHost;
+ _config = config;
}
public void Run()
@@ -164,20 +164,25 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
await SendNotification(notification).ConfigureAwait(false);
}
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- var item = e.MediaInfo;
+ private NotificationOptions GetOptions()
+ {
+ return _config.GetConfiguration<NotificationOptions>("notifications");
+ }
- if (item == null)
- {
- _logger.Warn("PlaybackStart reported with null media info.");
- return;
- }
+ void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
+ {
+ var item = e.MediaInfo;
- var type = GetPlaybackNotificationType(item.MediaType);
+ if (item == null)
+ {
+ _logger.Warn("PlaybackStart reported with null media info.");
+ return;
+ }
- SendPlaybackNotification(type, e);
- }
+ var type = GetPlaybackNotificationType(item.MediaType);
+
+ SendPlaybackNotification(type, e);
+ }
void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
{
@@ -198,20 +203,24 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
var user = e.Users.FirstOrDefault();
+ if (user != null && !GetOptions().IsEnabledToMonitorUser(type, user.Id.ToString("N")))
+ {
+ return;
+ }
+
var item = e.MediaInfo;
+ var themeMedia = item as IThemeMedia;
- if (e.Item != null && e.Item.Parent == null)
+ if (themeMedia != null && themeMedia.IsThemeMedia)
{
// Don't report theme song or local trailer playback
- // TODO: This will also cause movie specials to not be reported
return;
}
+
var notification = new NotificationRequest
{
- NotificationType = type,
-
- ExcludeUserIds = e.Users.Select(i => i.Id.ToString("N")).ToList()
+ NotificationType = type
};
notification.Variables["ItemName"] = item.Name;
@@ -317,7 +326,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
}
}
- private string GetItemName(BaseItem item)
+ public static string GetItemName(BaseItem item)
{
var name = item.Name;
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs
index 42aadf62e..5f1db03c6 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/WebSocketNotifier.cs
@@ -23,7 +23,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
public void Run()
{
_notificationsRepo.NotificationAdded += _notificationsRepo_NotificationAdded;
- _notificationsRepo.NotificationUpdated += _notificationsRepo_NotificationUpdated;
_notificationsRepo.NotificationsMarkedRead += _notificationsRepo_NotificationsMarkedRead;
}
@@ -40,13 +39,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
_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;
@@ -57,7 +49,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
public void Dispose()
{
_notificationsRepo.NotificationAdded -= _notificationsRepo_NotificationAdded;
- _notificationsRepo.NotificationUpdated -= _notificationsRepo_NotificationUpdated;
}
}
}
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/MediaBrowser.Server.Implementations/EntryPoints/ServerEventNotifier.cs
index 305f2800f..1b29971da 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/ServerEventNotifier.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/ServerEventNotifier.cs
@@ -88,7 +88,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
{
- var dto = _dtoService.GetUserDto(e.Argument);
+ var dto = _userManager.GetUserDto(e.Argument);
_serverManager.SendWebSocketMessage("UserConfigurationUpdated", dto);
}
@@ -145,8 +145,8 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
/// <param name="e">The e.</param>
void userManager_UserUpdated(object sender, GenericEventArgs<User> e)
{
- var dto = _dtoService.GetUserDto(e.Argument);
-
+ var dto = _userManager.GetUserDto(e.Argument);
+
_serverManager.SendWebSocketMessage("UserUpdated", dto);
}
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
index 7e5d5d3d8..386c16513 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
@@ -1,8 +1,8 @@
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
+using MediaBrowser.Model.Serialization;
using MediaBrowser.Server.Implementations.Udp;
using System.Net.Sockets;
@@ -27,30 +27,24 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
/// The _network manager
/// </summary>
private readonly INetworkManager _networkManager;
- /// <summary>
- /// The _server configuration manager
- /// </summary>
- private readonly IServerConfigurationManager _serverConfigurationManager;
- /// <summary>
- /// The _HTTP server
- /// </summary>
- private readonly IHttpServer _httpServer;
+ private readonly IServerApplicationHost _appHost;
+ private readonly IJsonSerializer _json;
public const int PortNumber = 7359;
/// <summary>
- /// Initializes a new instance of the <see cref="UdpServerEntryPoint"/> class.
+ /// Initializes a new instance of the <see cref="UdpServerEntryPoint" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="networkManager">The network manager.</param>
- /// <param name="serverConfigurationManager">The server configuration manager.</param>
- /// <param name="httpServer">The HTTP server.</param>
- public UdpServerEntryPoint(ILogger logger, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager, IHttpServer httpServer)
+ /// <param name="appHost">The application host.</param>
+ /// <param name="json">The json.</param>
+ public UdpServerEntryPoint(ILogger logger, INetworkManager networkManager, IServerApplicationHost appHost, IJsonSerializer json)
{
_logger = logger;
_networkManager = networkManager;
- _serverConfigurationManager = serverConfigurationManager;
- _httpServer = httpServer;
+ _appHost = appHost;
+ _json = json;
}
/// <summary>
@@ -58,7 +52,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
/// </summary>
public void Run()
{
- var udpServer = new UdpServer(_logger, _networkManager, _serverConfigurationManager, _httpServer);
+ var udpServer = new UdpServer(_logger, _networkManager, _appHost, _json);
try
{
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
index af3fde34b..de53201c9 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
@@ -26,7 +26,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
private Timer _timer;
private readonly TimeSpan _frequency = TimeSpan.FromHours(24);
- private const string DefaultDeviceVersion = "Unknown version";
private readonly ConcurrentDictionary<Guid, ClientInfo> _apps = new ConcurrentDictionary<Guid, ClientInfo>();
public UsageEntryPoint(ILogger logger, IApplicationHost applicationHost, INetworkManager networkManager, IHttpClient httpClient, ISessionManager sessionManager)
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index d7186aa21..c31f46215 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -1,10 +1,11 @@
-using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Session;
+using MoreLinq;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -17,21 +18,21 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
{
private readonly ISessionManager _sessionManager;
private readonly ILogger _logger;
- private readonly IDtoService _dtoService;
private readonly IUserDataManager _userDataManager;
+ private readonly IUserManager _userManager;
private readonly object _syncLock = new object();
private Timer UpdateTimer { get; set; }
private const int UpdateDuration = 500;
- private readonly Dictionary<Guid, List<string>> _changedKeys = new Dictionary<Guid, List<string>>();
+ private readonly Dictionary<Guid, List<IHasUserData>> _changedItems = new Dictionary<Guid, List<IHasUserData>>();
- public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IDtoService dtoService, ILogger logger)
+ public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, ILogger logger, IUserManager userManager)
{
_userDataManager = userDataManager;
_sessionManager = sessionManager;
- _dtoService = dtoService;
_logger = logger;
+ _userManager = userManager;
}
public void Run()
@@ -58,15 +59,28 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
UpdateTimer.Change(UpdateDuration, Timeout.Infinite);
}
- List<string> keys;
+ List<IHasUserData> keys;
- if (!_changedKeys.TryGetValue(e.UserId, out keys))
+ if (!_changedItems.TryGetValue(e.UserId, out keys))
{
- keys = new List<string>();
- _changedKeys[e.UserId] = keys;
+ keys = new List<IHasUserData>();
+ _changedItems[e.UserId] = keys;
}
- keys.Add(e.Key);
+ keys.Add(e.Item);
+
+ var baseItem = e.Item as BaseItem;
+
+ // Go up one level for indicators
+ if (baseItem != null)
+ {
+ var parent = baseItem.Parent;
+
+ if (parent != null)
+ {
+ keys.Add(parent);
+ }
+ }
}
}
@@ -75,8 +89,8 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
lock (_syncLock)
{
// Remove dupes in case some were saved multiple times
- var changes = _changedKeys.ToList();
- _changedKeys.Clear();
+ var changes = _changedItems.ToList();
+ _changedItems.Clear();
SendNotifications(changes, CancellationToken.None);
@@ -88,7 +102,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
}
}
- private async Task SendNotifications(IEnumerable<KeyValuePair<Guid, List<string>>> changes, CancellationToken cancellationToken)
+ private async Task SendNotifications(IEnumerable<KeyValuePair<Guid, List<IHasUserData>>> changes, CancellationToken cancellationToken)
{
foreach (var pair in changes)
{
@@ -99,8 +113,11 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
if (userSessions.Count > 0)
{
+ var user = _userManager.GetUserById(userId);
+
var dtoList = pair.Value
- .Select(i => _dtoService.GetUserItemDataDto(_userDataManager.GetUserData(userId, i)))
+ .DistinctBy(i => i.Id)
+ .Select(i => _userDataManager.GetUserDataDto(i, user))
.ToList();
var info = new UserDataChangeInfo