ActivityLogEntryPoint.cs 23 KB

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