ActivityLogEntryPoint.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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;
  10. using MediaBrowser.Controller.Authentication;
  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 ILogger _logger;
  31. private readonly IInstallationManager _installationManager;
  32. private readonly ISessionManager _sessionManager;
  33. private readonly ITaskManager _taskManager;
  34. private readonly IActivityManager _activityManager;
  35. private readonly ILocalizationManager _localization;
  36. private readonly ISubtitleManager _subManager;
  37. private readonly IUserManager _userManager;
  38. private readonly IServerApplicationHost _appHost;
  39. private readonly IDeviceManager _deviceManager;
  40. public ActivityLogEntryPoint(
  41. ILogger<ActivityLogEntryPoint> logger,
  42. ISessionManager sessionManager,
  43. IDeviceManager deviceManager,
  44. ITaskManager taskManager,
  45. IActivityManager activityManager,
  46. ILocalizationManager localization,
  47. IInstallationManager installationManager,
  48. ISubtitleManager subManager,
  49. IUserManager userManager,
  50. IServerApplicationHost appHost)
  51. {
  52. _logger = logger;
  53. _sessionManager = sessionManager;
  54. _deviceManager = deviceManager;
  55. _taskManager = taskManager;
  56. _activityManager = activityManager;
  57. _localization = localization;
  58. _installationManager = installationManager;
  59. _subManager = subManager;
  60. _userManager = userManager;
  61. _appHost = appHost;
  62. }
  63. public Task RunAsync()
  64. {
  65. _taskManager.TaskCompleted += OnTaskCompleted;
  66. _installationManager.PluginInstalled += OnPluginInstalled;
  67. _installationManager.PluginUninstalled += OnPluginUninstalled;
  68. _installationManager.PluginUpdated += OnPluginUpdated;
  69. _installationManager.PackageInstallationFailed += OnPackageInstallationFailed;
  70. _sessionManager.SessionStarted += OnSessionStarted;
  71. _sessionManager.AuthenticationFailed += OnAuthenticationFailed;
  72. _sessionManager.AuthenticationSucceeded += OnAuthenticationSucceeded;
  73. _sessionManager.SessionEnded += OnSessionEnded;
  74. _sessionManager.PlaybackStart += OnPlaybackStart;
  75. _sessionManager.PlaybackStopped += OnPlaybackStopped;
  76. _subManager.SubtitleDownloadFailure += OnSubtitleDownloadFailure;
  77. _userManager.UserCreated += OnUserCreated;
  78. _userManager.UserPasswordChanged += OnUserPasswordChanged;
  79. _userManager.UserDeleted += OnUserDeleted;
  80. _userManager.UserPolicyUpdated += OnUserPolicyUpdated;
  81. _userManager.UserLockedOut += OnUserLockedOut;
  82. _deviceManager.CameraImageUploaded += OnCameraImageUploaded;
  83. return Task.CompletedTask;
  84. }
  85. private void OnCameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
  86. {
  87. CreateLogEntry(new ActivityLogEntry
  88. {
  89. Name = string.Format(_localization.GetLocalizedString("CameraImageUploadedFrom"), e.Argument.Device.Name),
  90. Type = NotificationType.CameraImageUploaded.ToString()
  91. });
  92. }
  93. private void OnUserLockedOut(object sender, GenericEventArgs<User> e)
  94. {
  95. CreateLogEntry(new ActivityLogEntry
  96. {
  97. Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name),
  98. Type = NotificationType.UserLockedOut.ToString(),
  99. UserId = e.Argument.Id
  100. });
  101. }
  102. private void OnSubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
  103. {
  104. CreateLogEntry(new ActivityLogEntry
  105. {
  106. Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, Notifications.Notifications.GetItemName(e.Item)),
  107. Type = "SubtitleDownloadFailure",
  108. ItemId = e.Item.Id.ToString("N", CultureInfo.InvariantCulture),
  109. ShortOverview = e.Exception.Message
  110. });
  111. }
  112. private void OnPlaybackStopped(object sender, PlaybackStopEventArgs e)
  113. {
  114. var item = e.MediaInfo;
  115. if (item == null)
  116. {
  117. _logger.LogWarning("PlaybackStopped reported with null media info.");
  118. return;
  119. }
  120. if (e.Item != null && e.Item.IsThemeMedia)
  121. {
  122. // Don't report theme song or local trailer playback
  123. return;
  124. }
  125. if (e.Users.Count == 0)
  126. {
  127. return;
  128. }
  129. var user = e.Users[0];
  130. CreateLogEntry(new ActivityLogEntry
  131. {
  132. Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
  133. Type = GetPlaybackStoppedNotificationType(item.MediaType),
  134. UserId = user.Id
  135. });
  136. }
  137. private void OnPlaybackStart(object sender, PlaybackProgressEventArgs e)
  138. {
  139. var item = e.MediaInfo;
  140. if (item == null)
  141. {
  142. _logger.LogWarning("PlaybackStart reported with null media info.");
  143. return;
  144. }
  145. if (e.Item != null && e.Item.IsThemeMedia)
  146. {
  147. // Don't report theme song or local trailer playback
  148. return;
  149. }
  150. if (e.Users.Count == 0)
  151. {
  152. return;
  153. }
  154. var user = e.Users.First();
  155. CreateLogEntry(new ActivityLogEntry
  156. {
  157. Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
  158. Type = GetPlaybackNotificationType(item.MediaType),
  159. UserId = user.Id
  160. });
  161. }
  162. private static string GetItemName(BaseItemDto item)
  163. {
  164. var name = item.Name;
  165. if (!string.IsNullOrEmpty(item.SeriesName))
  166. {
  167. name = item.SeriesName + " - " + name;
  168. }
  169. if (item.Artists != null && item.Artists.Length > 0)
  170. {
  171. name = item.Artists[0] + " - " + name;
  172. }
  173. return name;
  174. }
  175. private static string GetPlaybackNotificationType(string mediaType)
  176. {
  177. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  178. {
  179. return NotificationType.AudioPlayback.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.Video, StringComparison.OrdinalIgnoreCase))
  194. {
  195. return NotificationType.VideoPlaybackStopped.ToString();
  196. }
  197. return null;
  198. }
  199. private void OnSessionEnded(object sender, SessionEventArgs e)
  200. {
  201. string name;
  202. var session = e.SessionInfo;
  203. if (string.IsNullOrEmpty(session.UserName))
  204. {
  205. name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
  206. // Causing too much spam for now
  207. return;
  208. }
  209. else
  210. {
  211. name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
  212. }
  213. CreateLogEntry(new ActivityLogEntry
  214. {
  215. Name = name,
  216. Type = "SessionEnded",
  217. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
  218. UserId = session.UserId
  219. });
  220. }
  221. private void OnAuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
  222. {
  223. var user = e.Argument.User;
  224. CreateLogEntry(new ActivityLogEntry
  225. {
  226. Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), user.Name),
  227. Type = "AuthenticationSucceeded",
  228. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.SessionInfo.RemoteEndPoint),
  229. UserId = user.Id
  230. });
  231. }
  232. private void OnAuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
  233. {
  234. CreateLogEntry(new ActivityLogEntry
  235. {
  236. Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
  237. Type = "AuthenticationFailed",
  238. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
  239. Severity = LogLevel.Error
  240. });
  241. }
  242. private void OnUserPolicyUpdated(object sender, GenericEventArgs<User> e)
  243. {
  244. CreateLogEntry(new ActivityLogEntry
  245. {
  246. Name = string.Format(_localization.GetLocalizedString("UserPolicyUpdatedWithName"), e.Argument.Name),
  247. Type = "UserPolicyUpdated",
  248. UserId = e.Argument.Id
  249. });
  250. }
  251. private void OnUserDeleted(object sender, GenericEventArgs<User> e)
  252. {
  253. CreateLogEntry(new ActivityLogEntry
  254. {
  255. Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
  256. Type = "UserDeleted"
  257. });
  258. }
  259. private void OnUserPasswordChanged(object sender, GenericEventArgs<User> e)
  260. {
  261. CreateLogEntry(new ActivityLogEntry
  262. {
  263. Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
  264. Type = "UserPasswordChanged",
  265. UserId = e.Argument.Id
  266. });
  267. }
  268. private void OnUserCreated(object sender, GenericEventArgs<User> e)
  269. {
  270. CreateLogEntry(new ActivityLogEntry
  271. {
  272. Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
  273. Type = "UserCreated",
  274. UserId = e.Argument.Id
  275. });
  276. }
  277. private void OnSessionStarted(object sender, SessionEventArgs e)
  278. {
  279. string name;
  280. var session = e.SessionInfo;
  281. if (string.IsNullOrEmpty(session.UserName))
  282. {
  283. name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
  284. // Causing too much spam for now
  285. return;
  286. }
  287. else
  288. {
  289. name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
  290. }
  291. CreateLogEntry(new ActivityLogEntry
  292. {
  293. Name = name,
  294. Type = "SessionStarted",
  295. ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
  296. UserId = session.UserId
  297. });
  298. }
  299. private void OnPluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
  300. {
  301. CreateLogEntry(new ActivityLogEntry
  302. {
  303. Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
  304. Type = NotificationType.PluginUpdateInstalled.ToString(),
  305. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
  306. Overview = e.Argument.Item2.description
  307. });
  308. }
  309. private void OnPluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  310. {
  311. CreateLogEntry(new ActivityLogEntry
  312. {
  313. Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
  314. Type = NotificationType.PluginUninstalled.ToString()
  315. });
  316. }
  317. private void OnPluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
  318. {
  319. CreateLogEntry(new ActivityLogEntry
  320. {
  321. Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
  322. Type = NotificationType.PluginInstalled.ToString(),
  323. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
  324. });
  325. }
  326. private void OnPackageInstallationFailed(object sender, InstallationFailedEventArgs e)
  327. {
  328. var installationInfo = e.InstallationInfo;
  329. CreateLogEntry(new ActivityLogEntry
  330. {
  331. Name = string.Format(_localization.GetLocalizedString("NameInstallFailed"), installationInfo.Name),
  332. Type = NotificationType.InstallationFailed.ToString(),
  333. ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), installationInfo.Version),
  334. Overview = e.Exception.Message
  335. });
  336. }
  337. private void OnTaskCompleted(object sender, TaskCompletionEventArgs e)
  338. {
  339. var result = e.Result;
  340. var task = e.Task;
  341. var activityTask = task.ScheduledTask as IConfigurableScheduledTask;
  342. if (activityTask != null && !activityTask.IsLogged)
  343. {
  344. return;
  345. }
  346. var time = result.EndTimeUtc - result.StartTimeUtc;
  347. var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
  348. if (result.Status == TaskCompletionStatus.Failed)
  349. {
  350. var vals = new List<string>();
  351. if (!string.IsNullOrEmpty(e.Result.ErrorMessage))
  352. {
  353. vals.Add(e.Result.ErrorMessage);
  354. }
  355. if (!string.IsNullOrEmpty(e.Result.LongErrorMessage))
  356. {
  357. vals.Add(e.Result.LongErrorMessage);
  358. }
  359. CreateLogEntry(new ActivityLogEntry
  360. {
  361. Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
  362. Type = NotificationType.TaskFailed.ToString(),
  363. Overview = string.Join(Environment.NewLine, vals),
  364. ShortOverview = runningTime,
  365. Severity = LogLevel.Error
  366. });
  367. }
  368. }
  369. private void CreateLogEntry(ActivityLogEntry entry)
  370. => _activityManager.Create(entry);
  371. public void Dispose()
  372. {
  373. _taskManager.TaskCompleted -= OnTaskCompleted;
  374. _installationManager.PluginInstalled -= OnPluginInstalled;
  375. _installationManager.PluginUninstalled -= OnPluginUninstalled;
  376. _installationManager.PluginUpdated -= OnPluginUpdated;
  377. _installationManager.PackageInstallationFailed -= OnPackageInstallationFailed;
  378. _sessionManager.SessionStarted -= OnSessionStarted;
  379. _sessionManager.AuthenticationFailed -= OnAuthenticationFailed;
  380. _sessionManager.AuthenticationSucceeded -= OnAuthenticationSucceeded;
  381. _sessionManager.SessionEnded -= OnSessionEnded;
  382. _sessionManager.PlaybackStart -= OnPlaybackStart;
  383. _sessionManager.PlaybackStopped -= OnPlaybackStopped;
  384. _subManager.SubtitleDownloadFailure -= OnSubtitleDownloadFailure;
  385. _userManager.UserCreated -= OnUserCreated;
  386. _userManager.UserPasswordChanged -= OnUserPasswordChanged;
  387. _userManager.UserDeleted -= OnUserDeleted;
  388. _userManager.UserPolicyUpdated -= OnUserPolicyUpdated;
  389. _userManager.UserLockedOut -= OnUserLockedOut;
  390. _deviceManager.CameraImageUploaded -= OnCameraImageUploaded;
  391. }
  392. /// <summary>
  393. /// Constructs a user-friendly string for this TimeSpan instance.
  394. /// </summary>
  395. public static string ToUserFriendlyString(TimeSpan span)
  396. {
  397. const int DaysInYear = 365;
  398. const int DaysInMonth = 30;
  399. // Get each non-zero value from TimeSpan component
  400. var values = new List<string>();
  401. // Number of years
  402. int days = span.Days;
  403. if (days >= DaysInYear)
  404. {
  405. int years = days / DaysInYear;
  406. values.Add(CreateValueString(years, "year"));
  407. days = days % DaysInYear;
  408. }
  409. // Number of months
  410. if (days >= DaysInMonth)
  411. {
  412. int months = days / DaysInMonth;
  413. values.Add(CreateValueString(months, "month"));
  414. days = days % DaysInMonth;
  415. }
  416. // Number of days
  417. if (days >= 1)
  418. {
  419. values.Add(CreateValueString(days, "day"));
  420. }
  421. // Number of hours
  422. if (span.Hours >= 1)
  423. {
  424. values.Add(CreateValueString(span.Hours, "hour"));
  425. }
  426. // Number of minutes
  427. if (span.Minutes >= 1)
  428. {
  429. values.Add(CreateValueString(span.Minutes, "minute"));
  430. }
  431. // Number of seconds (include when 0 if no other components included)
  432. if (span.Seconds >= 1 || values.Count == 0)
  433. {
  434. values.Add(CreateValueString(span.Seconds, "second"));
  435. }
  436. // Combine values into string
  437. var builder = new StringBuilder();
  438. for (int i = 0; i < values.Count; i++)
  439. {
  440. if (builder.Length > 0)
  441. {
  442. builder.Append(i == values.Count - 1 ? " and " : ", ");
  443. }
  444. builder.Append(values[i]);
  445. }
  446. // Return result
  447. return builder.ToString();
  448. }
  449. /// <summary>
  450. /// Constructs a string description of a time-span value.
  451. /// </summary>
  452. /// <param name="value">The value of this item</param>
  453. /// <param name="description">The name of this item (singular form)</param>
  454. private static string CreateValueString(int value, string description)
  455. {
  456. return string.Format("{0:#,##0} {1}",
  457. value, value == 1 ? description : string.Format("{0}s", description));
  458. }
  459. }
  460. }