ActivityLogEntryPoint.cs 21 KB

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