ActivityLogEntryPoint.cs 23 KB

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