ActivityLogEntryPoint.cs 23 KB

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