ActivityLogEntryPoint.cs 23 KB

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