ActivityLogEntryPoint.cs 22 KB

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