aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Activity
diff options
context:
space:
mode:
authorWWWesten <4700006+WWWesten@users.noreply.github.com>2021-11-01 23:43:29 +0500
committerGitHub <noreply@github.com>2021-11-01 23:43:29 +0500
commit0a14279e2a21bcb9654a06a2d49e1e4f0cc5329c (patch)
treee1b1bd603b011ca98e5793e356326bf4a35a7050 /Emby.Server.Implementations/Activity
parentf2817fef743eeb75a00782ceea363b2d3e7dc9f2 (diff)
parent76eeb8f655424d295e73ced8349c6fefee6ddb12 (diff)
Merge branch 'jellyfin:master' into master
Diffstat (limited to 'Emby.Server.Implementations/Activity')
-rw-r--r--Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs577
-rw-r--r--Emby.Server.Implementations/Activity/ActivityManager.cs61
-rw-r--r--Emby.Server.Implementations/Activity/ActivityRepository.cs310
3 files changed, 0 insertions, 948 deletions
diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
deleted file mode 100644
index 739f68767..000000000
--- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
+++ /dev/null
@@ -1,577 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Notifications;
-using MediaBrowser.Model.Tasks;
-using MediaBrowser.Model.Updates;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityLogEntryPoint : IServerEntryPoint
- {
- private readonly IInstallationManager _installationManager;
-
- //private readonly ILogger _logger;
- private readonly ISessionManager _sessionManager;
- private readonly ITaskManager _taskManager;
- private readonly IActivityManager _activityManager;
- private readonly ILocalizationManager _localization;
-
- private readonly ILibraryManager _libraryManager;
- private readonly ISubtitleManager _subManager;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
- private readonly IServerApplicationHost _appHost;
- private readonly IDeviceManager _deviceManager;
-
- public ActivityLogEntryPoint(ISessionManager sessionManager, IDeviceManager deviceManager, ITaskManager taskManager, IActivityManager activityManager, ILocalizationManager localization, IInstallationManager installationManager, ILibraryManager libraryManager, ISubtitleManager subManager, IUserManager userManager, IServerConfigurationManager config, IServerApplicationHost appHost)
- {
- _sessionManager = sessionManager;
- _taskManager = taskManager;
- _activityManager = activityManager;
- _localization = localization;
- _installationManager = installationManager;
- _libraryManager = libraryManager;
- _subManager = subManager;
- _userManager = userManager;
- _config = config;
- _appHost = appHost;
- _deviceManager = deviceManager;
- }
-
- public Task RunAsync()
- {
- _taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
- _installationManager.PluginInstalled += _installationManager_PluginInstalled;
- _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
- _installationManager.PluginUpdated += _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
-
- _sessionManager.SessionStarted += _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded += _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
-
- //_subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
- _subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated += _userManager_UserCreated;
- _userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
- _userManager.UserDeleted += _userManager_UserDeleted;
- _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
- _userManager.UserLockedOut += _userManager_UserLockedOut;
-
- //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
- //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
-
- _deviceManager.CameraImageUploaded += _deviceManager_CameraImageUploaded;
-
- _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
-
- return Task.CompletedTask;
- }
-
- void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("CameraImageUploadedFrom"), e.Argument.Device.Name),
- Type = NotificationType.CameraImageUploaded.ToString()
- });
- }
-
- void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name),
- Type = NotificationType.UserLockedOut.ToString(),
- UserId = e.Argument.Id
- });
- }
-
- void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitleDownloadFailure",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = e.Exception.Message
- });
- }
-
- void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.LogWarning("PlaybackStopped reported with null media info.");
- return;
- }
-
- if (e.Item != null && e.Item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
- Type = GetPlaybackStoppedNotificationType(item.MediaType),
- UserId = user.Id
- });
- }
-
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.LogWarning("PlaybackStart reported with null media info.");
- return;
- }
-
- if (e.Item != null && e.Item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
- Type = GetPlaybackNotificationType(item.MediaType),
- UserId = user.Id
- });
- }
-
- private static string GetItemName(BaseItemDto item)
- {
- var name = item.Name;
-
- if (!string.IsNullOrEmpty(item.SeriesName))
- {
- name = item.SeriesName + " - " + name;
- }
-
- if (item.Artists != null && item.Artists.Length > 0)
- {
- name = item.Artists[0] + " - " + name;
- }
-
- return name;
- }
-
- private static string GetPlaybackNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlayback.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlayback.ToString();
- }
-
- return null;
- }
-
- private static string GetPlaybackStoppedNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlaybackStopped.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlaybackStopped.ToString();
- }
-
- return null;
- }
-
- void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrEmpty(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionEnded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId
- });
- }
-
- void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
- {
- var user = e.Argument.User;
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), user.Name),
- Type = "AuthenticationSucceeded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.SessionInfo.RemoteEndPoint),
- UserId = user.Id
- });
- }
-
- void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
- Type = "AuthenticationFailed",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
- Severity = LogLevel.Error
- });
- }
-
- void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("MessageApplicationUpdatedTo"), e.Argument.versionStr),
- Type = NotificationType.ApplicationUpdateInstalled.ToString(),
- Overview = e.Argument.description
- });
- }
-
- void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
- Type = "NamedConfigurationUpdated"
- });
- }
-
- void _config_ConfigurationUpdated(object sender, EventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
- Type = "ServerConfigurationUpdated"
- });
- }
-
- void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserPolicyUpdatedWithName"), e.Argument.Name),
- Type = "UserPolicyUpdated",
- UserId = e.Argument.Id
- });
- }
-
- void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
- Type = "UserDeleted"
- });
- }
-
- void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
- Type = "UserPasswordChanged",
- UserId = e.Argument.Id
- });
- }
-
- void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
- Type = "UserCreated",
- UserId = e.Argument.Id
- });
- }
-
- void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitlesDownloaded",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
- });
- }
-
- void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrEmpty(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionStarted",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId
- });
- }
-
- void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
- Type = NotificationType.PluginUpdateInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
- Overview = e.Argument.Item2.description
- });
- }
-
- void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
- Type = NotificationType.PluginUninstalled.ToString()
- });
- }
-
- void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
- Type = NotificationType.PluginInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
- });
- }
-
- void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
- {
- var installationInfo = e.InstallationInfo;
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("NameInstallFailed"), installationInfo.Name),
- Type = NotificationType.InstallationFailed.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), installationInfo.Version),
- Overview = e.Exception.Message
- });
- }
-
- void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- var result = e.Result;
- var task = e.Task;
-
- var activityTask = task.ScheduledTask as IConfigurableScheduledTask;
- if (activityTask != null && !activityTask.IsLogged)
- {
- return;
- }
-
- var time = result.EndTimeUtc - result.StartTimeUtc;
- var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
-
- if (result.Status == TaskCompletionStatus.Failed)
- {
- var vals = new List<string>();
-
- if (!string.IsNullOrEmpty(e.Result.ErrorMessage))
- {
- vals.Add(e.Result.ErrorMessage);
- }
- if (!string.IsNullOrEmpty(e.Result.LongErrorMessage))
- {
- vals.Add(e.Result.LongErrorMessage);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
- Type = NotificationType.TaskFailed.ToString(),
- Overview = string.Join(Environment.NewLine, vals.ToArray()),
- ShortOverview = runningTime,
- Severity = LogLevel.Error
- });
- }
- }
-
- private void CreateLogEntry(ActivityLogEntry entry)
- {
- try
- {
- _activityManager.Create(entry);
- }
- catch
- {
- // Logged at lower levels
- }
- }
-
- public void Dispose()
- {
- _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
-
- _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
- _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
- _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
-
- _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
-
- _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated -= _userManager_UserCreated;
- _userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
- _userManager.UserDeleted -= _userManager_UserDeleted;
- _userManager.UserPolicyUpdated -= _userManager_UserPolicyUpdated;
- _userManager.UserLockedOut -= _userManager_UserLockedOut;
-
- _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
- _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
-
- _deviceManager.CameraImageUploaded -= _deviceManager_CameraImageUploaded;
-
- _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
- }
-
- /// <summary>
- /// Constructs a user-friendly string for this TimeSpan instance.
- /// </summary>
- public static string ToUserFriendlyString(TimeSpan span)
- {
- const int DaysInYear = 365;
- const int DaysInMonth = 30;
-
- // Get each non-zero value from TimeSpan component
- var values = new List<string>();
-
- // Number of years
- int days = span.Days;
- if (days >= DaysInYear)
- {
- int years = days / DaysInYear;
- values.Add(CreateValueString(years, "year"));
- days = days % DaysInYear;
- }
- // Number of months
- if (days >= DaysInMonth)
- {
- int months = days / DaysInMonth;
- values.Add(CreateValueString(months, "month"));
- days = days % DaysInMonth;
- }
- // Number of days
- if (days >= 1)
- values.Add(CreateValueString(days, "day"));
- // Number of hours
- if (span.Hours >= 1)
- values.Add(CreateValueString(span.Hours, "hour"));
- // Number of minutes
- if (span.Minutes >= 1)
- values.Add(CreateValueString(span.Minutes, "minute"));
- // Number of seconds (include when 0 if no other components included)
- if (span.Seconds >= 1 || values.Count == 0)
- values.Add(CreateValueString(span.Seconds, "second"));
-
- // Combine values into string
- var builder = new StringBuilder();
- for (int i = 0; i < values.Count; i++)
- {
- if (builder.Length > 0)
- builder.Append(i == values.Count - 1 ? " and " : ", ");
- builder.Append(values[i]);
- }
- // Return result
- return builder.ToString();
- }
-
- /// <summary>
- /// Constructs a string description of a time-span value.
- /// </summary>
- /// <param name="value">The value of this item</param>
- /// <param name="description">The name of this item (singular form)</param>
- private static string CreateValueString(int value, string description)
- {
- return string.Format("{0:#,##0} {1}",
- value, value == 1 ? description : string.Format("{0}s", description));
- }
- }
-}
diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs
deleted file mode 100644
index 6febcc2f7..000000000
--- a/Emby.Server.Implementations/Activity/ActivityManager.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityManager : IActivityManager
- {
- public event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated;
-
- private readonly IActivityRepository _repo;
- private readonly ILogger _logger;
- private readonly IUserManager _userManager;
-
- public ActivityManager(
- ILoggerFactory loggerFactory,
- IActivityRepository repo,
- IUserManager userManager)
- {
- _logger = loggerFactory.CreateLogger(nameof(ActivityManager));
- _repo = repo;
- _userManager = userManager;
- }
-
- public void Create(ActivityLogEntry entry)
- {
- entry.Date = DateTime.UtcNow;
-
- _repo.Create(entry);
-
- EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(entry));
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
- {
- var result = _repo.GetActivityLogEntries(minDate, hasUserId, startIndex, limit);
-
- foreach (var item in result.Items.Where(i => !i.UserId.Equals(Guid.Empty)))
- {
- var user = _userManager.GetUserById(item.UserId);
-
- if (user != null)
- {
- var dto = _userManager.GetUserDto(user);
- item.UserPrimaryImageTag = dto.PrimaryImageTag;
- }
- }
-
- return result;
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit)
- {
- return GetActivityLogEntries(minDate, null, startIndex, limit);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs
deleted file mode 100644
index aeed8b6f1..000000000
--- a/Emby.Server.Implementations/Activity/ActivityRepository.cs
+++ /dev/null
@@ -1,310 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Emby.Server.Implementations.Data;
-using MediaBrowser.Controller;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-using SQLitePCL.pretty;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityRepository : BaseSqliteRepository, IActivityRepository
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- protected IFileSystem FileSystem { get; private set; }
-
- public ActivityRepository(ILoggerFactory loggerFactory, IServerApplicationPaths appPaths, IFileSystem fileSystem)
- : base(loggerFactory.CreateLogger(nameof(ActivityRepository)))
- {
- DbFilePath = Path.Combine(appPaths.DataPath, "activitylog.db");
- FileSystem = fileSystem;
- }
-
- public void Initialize()
- {
- try
- {
- InitializeInternal();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error loading database file. Will reset and retry.");
-
- FileSystem.DeleteFile(DbFilePath);
-
- InitializeInternal();
- }
- }
-
- private void InitializeInternal()
- {
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- connection.RunQueries(new[]
- {
- "create table if not exists ActivityLog (Id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Overview TEXT, ShortOverview TEXT, Type TEXT NOT NULL, ItemId TEXT, UserId TEXT, DateCreated DATETIME NOT NULL, LogSeverity TEXT NOT NULL)",
- "drop index if exists idx_ActivityLogEntries"
- });
-
- TryMigrate(connection);
- }
- }
-
- private void TryMigrate(ManagedConnection connection)
- {
- try
- {
- if (TableExists(connection, "ActivityLogEntries"))
- {
- connection.RunQueries(new[]
- {
- "INSERT INTO ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) SELECT Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity FROM ActivityLogEntries",
- "drop table if exists ActivityLogEntries"
- });
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error migrating activity log database");
- }
- }
-
- private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLog";
-
- public void Create(ActivityLogEntry entry)
- {
- if (entry == null)
- {
- throw new ArgumentNullException(nameof(entry));
- }
-
- using (WriteLock.Write())
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"))
- {
- statement.TryBind("@Name", entry.Name);
-
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
-
- public void Update(ActivityLogEntry entry)
- {
- if (entry == null)
- {
- throw new ArgumentNullException(nameof(entry));
- }
-
- using (WriteLock.Write())
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id"))
- {
- statement.TryBind("@Id", entry.Id);
-
- statement.TryBind("@Name", entry.Name);
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
- {
- using (WriteLock.Read())
- using (var connection = CreateConnection(true))
- {
- var commandText = BaseActivitySelectText;
- var whereClauses = new List<string>();
-
- if (minDate.HasValue)
- {
- whereClauses.Add("DateCreated>=@DateCreated");
- }
- if (hasUserId.HasValue)
- {
- if (hasUserId.Value)
- {
- whereClauses.Add("UserId not null");
- }
- else
- {
- whereClauses.Add("UserId is null");
- }
- }
-
- var whereTextWithoutPaging = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- if (startIndex.HasValue && startIndex.Value > 0)
- {
- var pagingWhereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
- pagingWhereText,
- startIndex.Value.ToString(_usCulture)));
- }
-
- var whereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- commandText += whereText;
-
- commandText += " ORDER BY DateCreated DESC";
-
- if (limit.HasValue)
- {
- commandText += " LIMIT " + limit.Value.ToString(_usCulture);
- }
-
- var statementTexts = new List<string>();
- statementTexts.Add(commandText);
- statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
-
- return connection.RunInTransaction(db =>
- {
- var list = new List<ActivityLogEntry>();
- var result = new QueryResult<ActivityLogEntry>();
-
- var statements = PrepareAllSafe(db, statementTexts).ToList();
-
- using (var statement = statements[0])
- {
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetEntry(row));
- }
- }
-
- using (var statement = statements[1])
- {
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
-
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
-
- result.Items = list.ToArray();
- return result;
-
- }, ReadTransactionMode);
- }
- }
-
- private static ActivityLogEntry GetEntry(IReadOnlyList<IResultSetValue> reader)
- {
- var index = 0;
-
- var info = new ActivityLogEntry
- {
- Id = reader[index].ToInt64()
- };
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Name = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Overview = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.ShortOverview = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Type = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.ItemId = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.UserId = new Guid(reader[index].ToString());
- }
-
- index++;
- info.Date = reader[index].ReadDateTime();
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true);
- }
-
- return info;
- }
- }
-}