ActivityLogEntryPoint.cs 22 KB

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