ActivityLogEntryPoint.cs 23 KB

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