ActivityLogEntryPoint.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. if (e.Users.Count == 0)
  103. {
  104. return;
  105. }
  106. var username = e.Users.First().Name;
  107. CreateLogEntry(new ActivityLogEntry
  108. {
  109. Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), username, item.Name),
  110. Type = "PlaybackStopped",
  111. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
  112. });
  113. }
  114. void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  115. {
  116. var item = e.MediaInfo;
  117. if (item == null)
  118. {
  119. //_logger.Warn("PlaybackStart reported with null media info.");
  120. return;
  121. }
  122. if (e.Users.Count == 0)
  123. {
  124. return;
  125. }
  126. var username = e.Users.First().Name;
  127. CreateLogEntry(new ActivityLogEntry
  128. {
  129. Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), username, item.Name),
  130. Type = "PlaybackStart",
  131. ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), e.ClientName, e.DeviceName)
  132. });
  133. }
  134. void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
  135. {
  136. string name;
  137. var session = e.SessionInfo;
  138. if (string.IsNullOrWhiteSpace(session.UserName))
  139. {
  140. name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
  141. // Causing too much spam for now
  142. return;
  143. }
  144. else
  145. {
  146. name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
  147. }
  148. CreateLogEntry(new ActivityLogEntry
  149. {
  150. Name = name,
  151. Type = "SessionEnded",
  152. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint)
  153. });
  154. }
  155. void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationRequest> e)
  156. {
  157. CreateLogEntry(new ActivityLogEntry
  158. {
  159. Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), e.Argument.Username),
  160. Type = "AuthenticationSucceeded",
  161. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint)
  162. });
  163. }
  164. void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
  165. {
  166. CreateLogEntry(new ActivityLogEntry
  167. {
  168. Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
  169. Type = "AuthenticationFailed",
  170. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
  171. Severity = LogSeverity.Error
  172. });
  173. }
  174. void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
  175. {
  176. CreateLogEntry(new ActivityLogEntry
  177. {
  178. Name = _localization.GetLocalizedString("MessageApplicationUpdated"),
  179. Type = "ApplicationUpdated",
  180. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr),
  181. Overview = e.Argument.description
  182. });
  183. }
  184. void _logManager_LoggerLoaded(object sender, EventArgs e)
  185. {
  186. }
  187. void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  188. {
  189. CreateLogEntry(new ActivityLogEntry
  190. {
  191. Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
  192. Type = "NamedConfigurationUpdated"
  193. });
  194. }
  195. void _config_ConfigurationUpdated(object sender, EventArgs e)
  196. {
  197. CreateLogEntry(new ActivityLogEntry
  198. {
  199. Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
  200. Type = "ServerConfigurationUpdated"
  201. });
  202. }
  203. void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
  204. {
  205. CreateLogEntry(new ActivityLogEntry
  206. {
  207. Name = string.Format(_localization.GetLocalizedString("UserConfigurationUpdatedWithName"), e.Argument.Name),
  208. Type = "UserConfigurationUpdated"
  209. });
  210. }
  211. void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
  212. {
  213. CreateLogEntry(new ActivityLogEntry
  214. {
  215. Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
  216. Type = "UserDeleted"
  217. });
  218. }
  219. void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
  220. {
  221. CreateLogEntry(new ActivityLogEntry
  222. {
  223. Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
  224. Type = "UserPasswordChanged"
  225. });
  226. }
  227. void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
  228. {
  229. CreateLogEntry(new ActivityLogEntry
  230. {
  231. Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
  232. Type = "UserCreated"
  233. });
  234. }
  235. void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
  236. {
  237. CreateLogEntry(new ActivityLogEntry
  238. {
  239. Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
  240. Type = "SubtitlesDownloaded",
  241. ItemId = e.Item.Id.ToString("N"),
  242. ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
  243. });
  244. }
  245. void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
  246. {
  247. string name;
  248. var session = e.SessionInfo;
  249. if (string.IsNullOrWhiteSpace(session.UserName))
  250. {
  251. name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
  252. // Causing too much spam for now
  253. return;
  254. }
  255. else
  256. {
  257. name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
  258. }
  259. CreateLogEntry(new ActivityLogEntry
  260. {
  261. Name = name,
  262. Type = "SessionStarted",
  263. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint)
  264. });
  265. }
  266. void _libraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  267. {
  268. if (e.Item is LiveTvProgram || e.Item is IChannelItem)
  269. {
  270. return;
  271. }
  272. CreateLogEntry(new ActivityLogEntry
  273. {
  274. Name = string.Format(_localization.GetLocalizedString("ItemRemovedWithName"), Notifications.Notifications.GetItemName(e.Item)),
  275. Type = "ItemRemoved"
  276. });
  277. }
  278. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  279. {
  280. if (e.Item is LiveTvProgram || e.Item is IChannelItem)
  281. {
  282. return;
  283. }
  284. CreateLogEntry(new ActivityLogEntry
  285. {
  286. Name = string.Format(_localization.GetLocalizedString("ItemAddedWithName"), Notifications.Notifications.GetItemName(e.Item)),
  287. Type = "ItemAdded",
  288. ItemId = e.Item.Id.ToString("N")
  289. });
  290. }
  291. void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
  292. {
  293. CreateLogEntry(new ActivityLogEntry
  294. {
  295. Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
  296. Type = "PluginUpdated",
  297. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
  298. Overview = e.Argument.Item2.description
  299. });
  300. }
  301. void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  302. {
  303. CreateLogEntry(new ActivityLogEntry
  304. {
  305. Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
  306. Type = "PluginUninstalled"
  307. });
  308. }
  309. void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
  310. {
  311. CreateLogEntry(new ActivityLogEntry
  312. {
  313. Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
  314. Type = "PluginInstalled",
  315. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
  316. });
  317. }
  318. void _taskManager_TaskExecuting(object sender, GenericEventArgs<IScheduledTaskWorker> e)
  319. {
  320. var task = e.Argument;
  321. var activityTask = task.ScheduledTask as IScheduledTaskActivityLog;
  322. if (activityTask != null && !activityTask.IsActivityLogged)
  323. {
  324. return;
  325. }
  326. CreateLogEntry(new ActivityLogEntry
  327. {
  328. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskStartedWithName"), task.Name),
  329. Type = "ScheduledTaskStarted"
  330. });
  331. }
  332. void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
  333. {
  334. var result = e.Result;
  335. var task = e.Task;
  336. var activityTask = task.ScheduledTask as IScheduledTaskActivityLog;
  337. if (activityTask != null && !activityTask.IsActivityLogged)
  338. {
  339. return;
  340. }
  341. var time = result.EndTimeUtc - result.StartTimeUtc;
  342. var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
  343. if (result.Status == TaskCompletionStatus.Cancelled)
  344. {
  345. return;
  346. CreateLogEntry(new ActivityLogEntry
  347. {
  348. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCancelledWithName"), task.Name),
  349. Type = "ScheduledTaskCancelled",
  350. ShortOverview = runningTime
  351. });
  352. }
  353. else if (result.Status == TaskCompletionStatus.Completed)
  354. {
  355. return;
  356. CreateLogEntry(new ActivityLogEntry
  357. {
  358. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskCompletedWithName"), task.Name),
  359. Type = "ScheduledTaskCompleted",
  360. ShortOverview = runningTime
  361. });
  362. }
  363. else 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()),
  379. ShortOverview = runningTime,
  380. Severity = LogSeverity.Error
  381. });
  382. }
  383. }
  384. private async void CreateLogEntry(ActivityLogEntry entry)
  385. {
  386. try
  387. {
  388. await _activityManager.Create(entry).ConfigureAwait(false);
  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. _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. }