ActivityLogEntryPoint.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
  79. //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  80. //_logManager.LoggerLoaded += _logManager_LoggerLoaded;
  81. _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
  82. }
  83. void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
  84. {
  85. CreateLogEntry(new ActivityLogEntry
  86. {
  87. Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureForItem"), Notifications.Notifications.GetItemName(e.Item)),
  88. Type = "SubtitleDownloadFailure",
  89. ItemId = e.Item.Id.ToString("N"),
  90. ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider),
  91. Overview = LogHelper.GetLogMessage(e.Exception).ToString()
  92. });
  93. }
  94. void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
  95. {
  96. var item = e.MediaInfo;
  97. if (item == null)
  98. {
  99. //_logger.Warn("PlaybackStopped reported with null media info.");
  100. return;
  101. }
  102. var themeMedia = item as IThemeMedia;
  103. if (themeMedia != null && themeMedia.IsThemeMedia)
  104. {
  105. // Don't report theme song or local trailer playback
  106. return;
  107. }
  108. if (e.Users.Count == 0)
  109. {
  110. return;
  111. }
  112. var user = e.Users.First();
  113. CreateLogEntry(new ActivityLogEntry
  114. {
  115. Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, item.Name),
  116. Type = "PlaybackStopped",
  117. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName),
  118. UserId = user.Id.ToString("N")
  119. });
  120. }
  121. void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  122. {
  123. var item = e.MediaInfo;
  124. if (item == null)
  125. {
  126. //_logger.Warn("PlaybackStart reported with null media info.");
  127. return;
  128. }
  129. var themeMedia = item as IThemeMedia;
  130. if (themeMedia != null && themeMedia.IsThemeMedia)
  131. {
  132. // Don't report theme song or local trailer playback
  133. return;
  134. }
  135. if (e.Users.Count == 0)
  136. {
  137. return;
  138. }
  139. var user = e.Users.First();
  140. CreateLogEntry(new ActivityLogEntry
  141. {
  142. Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, item.Name),
  143. Type = "PlaybackStart",
  144. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName),
  145. UserId = user.Id.ToString("N")
  146. });
  147. }
  148. void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
  149. {
  150. string name;
  151. var session = e.SessionInfo;
  152. if (string.IsNullOrWhiteSpace(session.UserName))
  153. {
  154. name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
  155. // Causing too much spam for now
  156. return;
  157. }
  158. else
  159. {
  160. name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
  161. }
  162. CreateLogEntry(new ActivityLogEntry
  163. {
  164. Name = name,
  165. Type = "SessionEnded",
  166. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
  167. UserId = (session.UserId.HasValue ? session.UserId.Value.ToString("N") : null)
  168. });
  169. }
  170. void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationRequest> e)
  171. {
  172. CreateLogEntry(new ActivityLogEntry
  173. {
  174. Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), e.Argument.Username),
  175. Type = "AuthenticationSucceeded",
  176. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint)
  177. });
  178. }
  179. void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
  180. {
  181. CreateLogEntry(new ActivityLogEntry
  182. {
  183. Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
  184. Type = "AuthenticationFailed",
  185. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
  186. Severity = LogSeverity.Error
  187. });
  188. }
  189. void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
  190. {
  191. CreateLogEntry(new ActivityLogEntry
  192. {
  193. Name = _localization.GetLocalizedString("MessageApplicationUpdated"),
  194. Type = "ApplicationUpdated",
  195. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr),
  196. Overview = e.Argument.description
  197. });
  198. }
  199. void _logManager_LoggerLoaded(object sender, EventArgs e)
  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 is LiveTvProgram || e.Item is IChannelItem)
  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 is LiveTvProgram || e.Item is IChannelItem)
  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 IScheduledTaskActivityLog;
  341. if (activityTask != null && !activityTask.IsActivityLogged)
  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 IScheduledTaskActivityLog;
  356. if (activityTask != null && !activityTask.IsActivityLogged)
  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. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  416. _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
  417. //_logManager.LoggerLoaded -= _logManager_LoggerLoaded;
  418. _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
  419. }
  420. /// <summary>
  421. /// Constructs a user-friendly string for this TimeSpan instance.
  422. /// </summary>
  423. public static string ToUserFriendlyString(TimeSpan span)
  424. {
  425. const int DaysInYear = 365;
  426. const int DaysInMonth = 30;
  427. // Get each non-zero value from TimeSpan component
  428. List<string> values = new List<string>();
  429. // Number of years
  430. int days = span.Days;
  431. if (days >= DaysInYear)
  432. {
  433. int years = (days / DaysInYear);
  434. values.Add(CreateValueString(years, "year"));
  435. days = (days % DaysInYear);
  436. }
  437. // Number of months
  438. if (days >= DaysInMonth)
  439. {
  440. int months = (days / DaysInMonth);
  441. values.Add(CreateValueString(months, "month"));
  442. days = (days % DaysInMonth);
  443. }
  444. // Number of days
  445. if (days >= 1)
  446. values.Add(CreateValueString(days, "day"));
  447. // Number of hours
  448. if (span.Hours >= 1)
  449. values.Add(CreateValueString(span.Hours, "hour"));
  450. // Number of minutes
  451. if (span.Minutes >= 1)
  452. values.Add(CreateValueString(span.Minutes, "minute"));
  453. // Number of seconds (include when 0 if no other components included)
  454. if (span.Seconds >= 1 || values.Count == 0)
  455. values.Add(CreateValueString(span.Seconds, "second"));
  456. // Combine values into string
  457. StringBuilder builder = new StringBuilder();
  458. for (int i = 0; i < values.Count; i++)
  459. {
  460. if (builder.Length > 0)
  461. builder.Append((i == (values.Count - 1)) ? " and " : ", ");
  462. builder.Append(values[i]);
  463. }
  464. // Return result
  465. return builder.ToString();
  466. }
  467. /// <summary>
  468. /// Constructs a string description of a time-span value.
  469. /// </summary>
  470. /// <param name="value">The value of this item</param>
  471. /// <param name="description">The name of this item (singular form)</param>
  472. private static string CreateValueString(int value, string description)
  473. {
  474. return String.Format("{0:#,##0} {1}",
  475. value, (value == 1) ? description : String.Format("{0}s", description));
  476. }
  477. }
  478. }