ActivityLogEntryPoint.cs 23 KB

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