ActivityLogEntryPoint.cs 23 KB

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