ActivityLogEntryPoint.cs 23 KB

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