ActivityLogEntryPoint.cs 22 KB

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