ActivityLogEntryPoint.cs 20 KB

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