ActivityLogEntryPoint.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Implementations.Logging;
  3. using MediaBrowser.Common.Plugins;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Common.Updates;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.Activity;
  8. using MediaBrowser.Controller.Channels;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Localization;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Controller.Session;
  16. using MediaBrowser.Controller.Subtitles;
  17. using MediaBrowser.Model.Activity;
  18. using MediaBrowser.Model.Events;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Tasks;
  21. using MediaBrowser.Model.Updates;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Linq;
  25. using System.Text;
  26. namespace MediaBrowser.Server.Implementations.EntryPoints
  27. {
  28. public class ActivityLogEntryPoint : IServerEntryPoint
  29. {
  30. private readonly IInstallationManager _installationManager;
  31. //private readonly ILogManager _logManager;
  32. private readonly ILogger _logger;
  33. private readonly ISessionManager _sessionManager;
  34. private readonly ITaskManager _taskManager;
  35. private readonly IActivityManager _activityManager;
  36. private readonly ILocalizationManager _localization;
  37. private readonly ILibraryManager _libraryManager;
  38. private readonly ISubtitleManager _subManager;
  39. private readonly IUserManager _userManager;
  40. private readonly IServerConfigurationManager _config;
  41. private readonly IServerApplicationHost _appHost;
  42. public ActivityLogEntryPoint(ISessionManager sessionManager, ITaskManager taskManager, IActivityManager activityManager, ILocalizationManager localization, IInstallationManager installationManager, ILibraryManager libraryManager, ISubtitleManager subManager, IUserManager userManager, IServerConfigurationManager config, IServerApplicationHost appHost)
  43. {
  44. //_logger = _logManager.GetLogger("ActivityLogEntryPoint");
  45. _sessionManager = sessionManager;
  46. _taskManager = taskManager;
  47. _activityManager = activityManager;
  48. _localization = localization;
  49. _installationManager = installationManager;
  50. _libraryManager = libraryManager;
  51. _subManager = subManager;
  52. _userManager = userManager;
  53. _config = config;
  54. //_logManager = logManager;
  55. _appHost = appHost;
  56. }
  57. public void Run()
  58. {
  59. _taskManager.TaskExecuting += _taskManager_TaskExecuting;
  60. _taskManager.TaskCompleted += _taskManager_TaskCompleted;
  61. _installationManager.PluginInstalled += _installationManager_PluginInstalled;
  62. _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
  63. _installationManager.PluginUpdated += _installationManager_PluginUpdated;
  64. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  65. _libraryManager.ItemRemoved += _libraryManager_ItemRemoved;
  66. _sessionManager.SessionStarted += _sessionManager_SessionStarted;
  67. _sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
  68. _sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
  69. _sessionManager.SessionEnded += _sessionManager_SessionEnded;
  70. _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
  71. _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
  72. _subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
  73. _subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
  74. _userManager.UserCreated += _userManager_UserCreated;
  75. _userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
  76. _userManager.UserDeleted += _userManager_UserDeleted;
  77. _userManager.UserConfigurationUpdated += _userManager_UserConfigurationUpdated;
  78. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  79. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  80. //_logManager.LoggerLoaded += _logManager_LoggerLoaded;
  81. _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
  82. }
  83. void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
  84. {
  85. CreateLogEntry(new ActivityLogEntry
  86. {
  87. Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureForItem"), Notifications.Notifications.GetItemName(e.Item)),
  88. Type = "SubtitleDownloadFailure",
  89. ItemId = e.Item.Id.ToString("N"),
  90. ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider),
  91. Overview = LogHelper.GetLogMessage(e.Exception).ToString()
  92. });
  93. }
  94. void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
  95. {
  96. var item = e.MediaInfo;
  97. if (item == null)
  98. {
  99. //_logger.Warn("PlaybackStopped reported with null media info.");
  100. return;
  101. }
  102. if (e.Users.Count == 0)
  103. {
  104. return;
  105. }
  106. var username = e.Users.First().Name;
  107. CreateLogEntry(new ActivityLogEntry
  108. {
  109. Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), username, item.Name),
  110. Type = "PlaybackStopped",
  111. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
  112. });
  113. }
  114. void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  115. {
  116. var item = e.MediaInfo;
  117. if (item == null)
  118. {
  119. //_logger.Warn("PlaybackStart reported with null media info.");
  120. return;
  121. }
  122. if (e.Users.Count == 0)
  123. {
  124. return;
  125. }
  126. var username = e.Users.First().Name;
  127. CreateLogEntry(new ActivityLogEntry
  128. {
  129. Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), username, item.Name),
  130. Type = "PlaybackStart",
  131. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
  132. });
  133. }
  134. void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
  135. {
  136. string name;
  137. var session = e.SessionInfo;
  138. if (string.IsNullOrWhiteSpace(session.UserName))
  139. {
  140. name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
  141. }
  142. else
  143. {
  144. name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
  145. }
  146. CreateLogEntry(new ActivityLogEntry
  147. {
  148. Name = name,
  149. Type = "SessionEnded",
  150. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint)
  151. });
  152. }
  153. void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationRequest> e)
  154. {
  155. CreateLogEntry(new ActivityLogEntry
  156. {
  157. Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), e.Argument.Username),
  158. Type = "AuthenticationSucceeded",
  159. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint)
  160. });
  161. }
  162. void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
  163. {
  164. CreateLogEntry(new ActivityLogEntry
  165. {
  166. Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
  167. Type = "AuthenticationFailed",
  168. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
  169. Severity = LogSeverity.Error
  170. });
  171. }
  172. void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
  173. {
  174. CreateLogEntry(new ActivityLogEntry
  175. {
  176. Name = _localization.GetLocalizedString("MessageApplicationUpdated"),
  177. Type = "ApplicationUpdated",
  178. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr),
  179. Overview = e.Argument.description
  180. });
  181. }
  182. void _logManager_LoggerLoaded(object sender, EventArgs e)
  183. {
  184. }
  185. void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  186. {
  187. CreateLogEntry(new ActivityLogEntry
  188. {
  189. Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
  190. Type = "NamedConfigurationUpdated"
  191. });
  192. }
  193. void _config_ConfigurationUpdated(object sender, EventArgs e)
  194. {
  195. CreateLogEntry(new ActivityLogEntry
  196. {
  197. Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
  198. Type = "ServerConfigurationUpdated"
  199. });
  200. }
  201. void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
  202. {
  203. CreateLogEntry(new ActivityLogEntry
  204. {
  205. Name = string.Format(_localization.GetLocalizedString("UserConfigurationUpdatedWithName"), e.Argument.Name),
  206. Type = "UserConfigurationUpdated"
  207. });
  208. }
  209. void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
  210. {
  211. CreateLogEntry(new ActivityLogEntry
  212. {
  213. Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
  214. Type = "UserDeleted"
  215. });
  216. }
  217. void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
  218. {
  219. CreateLogEntry(new ActivityLogEntry
  220. {
  221. Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
  222. Type = "UserPasswordChanged"
  223. });
  224. }
  225. void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
  226. {
  227. CreateLogEntry(new ActivityLogEntry
  228. {
  229. Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
  230. Type = "UserCreated"
  231. });
  232. }
  233. void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
  234. {
  235. CreateLogEntry(new ActivityLogEntry
  236. {
  237. Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
  238. Type = "SubtitlesDownloaded",
  239. ItemId = e.Item.Id.ToString("N"),
  240. ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
  241. });
  242. }
  243. void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
  244. {
  245. string name;
  246. var session = e.SessionInfo;
  247. if (string.IsNullOrWhiteSpace(session.UserName))
  248. {
  249. name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
  250. }
  251. else
  252. {
  253. name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
  254. }
  255. CreateLogEntry(new ActivityLogEntry
  256. {
  257. Name = name,
  258. Type = "SessionStarted",
  259. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint)
  260. });
  261. }
  262. void _libraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  263. {
  264. if (e.Item is LiveTvProgram || e.Item is IChannelItem)
  265. {
  266. return;
  267. }
  268. CreateLogEntry(new ActivityLogEntry
  269. {
  270. Name = string.Format(_localization.GetLocalizedString("ItemRemovedWithName"), Notifications.Notifications.GetItemName(e.Item)),
  271. Type = "ItemRemoved"
  272. });
  273. }
  274. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  275. {
  276. if (e.Item is LiveTvProgram || e.Item is IChannelItem)
  277. {
  278. return;
  279. }
  280. CreateLogEntry(new ActivityLogEntry
  281. {
  282. Name = string.Format(_localization.GetLocalizedString("ItemAddedWithName"), Notifications.Notifications.GetItemName(e.Item)),
  283. Type = "ItemAdded",
  284. ItemId = e.Item.Id.ToString("N")
  285. });
  286. }
  287. void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
  288. {
  289. CreateLogEntry(new ActivityLogEntry
  290. {
  291. Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
  292. Type = "PluginUpdated",
  293. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
  294. Overview = e.Argument.Item2.description
  295. });
  296. }
  297. void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  298. {
  299. CreateLogEntry(new ActivityLogEntry
  300. {
  301. Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
  302. Type = "PluginUninstalled"
  303. });
  304. }
  305. void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
  306. {
  307. CreateLogEntry(new ActivityLogEntry
  308. {
  309. Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
  310. Type = "PluginInstalled",
  311. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
  312. });
  313. }
  314. void _taskManager_TaskExecuting(object sender, GenericEventArgs<IScheduledTaskWorker> e)
  315. {
  316. var task = e.Argument;
  317. var activityTask = task.ScheduledTask as IScheduledTaskActivityLog;
  318. if (activityTask != null && !activityTask.IsActivityLogged)
  319. {
  320. return;
  321. }
  322. CreateLogEntry(new ActivityLogEntry
  323. {
  324. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskStartedWithName"), task.Name),
  325. Type = "ScheduledTaskStarted"
  326. });
  327. }
  328. void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
  329. {
  330. var result = e.Result;
  331. var task = e.Task;
  332. var activityTask = task.ScheduledTask as IScheduledTaskActivityLog;
  333. if (activityTask != null && !activityTask.IsActivityLogged)
  334. {
  335. return;
  336. }
  337. var time = result.EndTimeUtc - result.StartTimeUtc;
  338. var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
  339. if (result.Status == TaskCompletionStatus.Cancelled)
  340. {
  341. CreateLogEntry(new ActivityLogEntry
  342. {
  343. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCancelledWithName"), task.Name),
  344. Type = "ScheduledTaskCancelled",
  345. ShortOverview = runningTime
  346. });
  347. }
  348. else if (result.Status == TaskCompletionStatus.Completed)
  349. {
  350. CreateLogEntry(new ActivityLogEntry
  351. {
  352. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCompletedWithName"), task.Name),
  353. Type = "ScheduledTaskCompleted",
  354. ShortOverview = runningTime
  355. });
  356. }
  357. else if (result.Status == TaskCompletionStatus.Failed)
  358. {
  359. var vals = new List<string>();
  360. if (!string.IsNullOrWhiteSpace(e.Result.ErrorMessage))
  361. {
  362. vals.Add(e.Result.ErrorMessage);
  363. }
  364. if (!string.IsNullOrWhiteSpace(e.Result.LongErrorMessage))
  365. {
  366. vals.Add(e.Result.LongErrorMessage);
  367. }
  368. CreateLogEntry(new ActivityLogEntry
  369. {
  370. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
  371. Type = "ScheduledTaskFailed",
  372. Overview = string.Join(Environment.NewLine, vals.ToArray()),
  373. ShortOverview = runningTime,
  374. Severity = LogSeverity.Error
  375. });
  376. }
  377. }
  378. private async void CreateLogEntry(ActivityLogEntry entry)
  379. {
  380. try
  381. {
  382. await _activityManager.Create(entry).ConfigureAwait(false);
  383. }
  384. catch
  385. {
  386. // Logged at lower levels
  387. }
  388. }
  389. public void Dispose()
  390. {
  391. _taskManager.TaskExecuting -= _taskManager_TaskExecuting;
  392. _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
  393. _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
  394. _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
  395. _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
  396. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  397. _libraryManager.ItemRemoved -= _libraryManager_ItemRemoved;
  398. _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
  399. _sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
  400. _sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
  401. _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
  402. _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
  403. _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
  404. _subManager.SubtitlesDownloaded -= _subManager_SubtitlesDownloaded;
  405. _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
  406. _userManager.UserCreated -= _userManager_UserCreated;
  407. _userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
  408. _userManager.UserDeleted -= _userManager_UserDeleted;
  409. _userManager.UserConfigurationUpdated -= _userManager_UserConfigurationUpdated;
  410. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  411. _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
  412. //_logManager.LoggerLoaded -= _logManager_LoggerLoaded;
  413. _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
  414. }
  415. /// <summary>
  416. /// Constructs a user-friendly string for this TimeSpan instance.
  417. /// </summary>
  418. public static string ToUserFriendlyString(TimeSpan span)
  419. {
  420. const int DaysInYear = 365;
  421. const int DaysInMonth = 30;
  422. // Get each non-zero value from TimeSpan component
  423. List<string> values = new List<string>();
  424. // Number of years
  425. int days = span.Days;
  426. if (days >= DaysInYear)
  427. {
  428. int years = (days / DaysInYear);
  429. values.Add(CreateValueString(years, "year"));
  430. days = (days % DaysInYear);
  431. }
  432. // Number of months
  433. if (days >= DaysInMonth)
  434. {
  435. int months = (days / DaysInMonth);
  436. values.Add(CreateValueString(months, "month"));
  437. days = (days % DaysInMonth);
  438. }
  439. // Number of days
  440. if (days >= 1)
  441. values.Add(CreateValueString(days, "day"));
  442. // Number of hours
  443. if (span.Hours >= 1)
  444. values.Add(CreateValueString(span.Hours, "hour"));
  445. // Number of minutes
  446. if (span.Minutes >= 1)
  447. values.Add(CreateValueString(span.Minutes, "minute"));
  448. // Number of seconds (include when 0 if no other components included)
  449. if (span.Seconds >= 1 || values.Count == 0)
  450. values.Add(CreateValueString(span.Seconds, "second"));
  451. // Combine values into string
  452. StringBuilder builder = new StringBuilder();
  453. for (int i = 0; i < values.Count; i++)
  454. {
  455. if (builder.Length > 0)
  456. builder.Append((i == (values.Count - 1)) ? " and " : ", ");
  457. builder.Append(values[i]);
  458. }
  459. // Return result
  460. return builder.ToString();
  461. }
  462. /// <summary>
  463. /// Constructs a string description of a time-span value.
  464. /// </summary>
  465. /// <param name="value">The value of this item</param>
  466. /// <param name="description">The name of this item (singular form)</param>
  467. private static string CreateValueString(int value, string description)
  468. {
  469. return String.Format("{0:#,##0} {1}",
  470. value, (value == 1) ? description : String.Format("{0}s", description));
  471. }
  472. }
  473. }