diff options
Diffstat (limited to 'Emby.Server.Core')
| -rw-r--r-- | Emby.Server.Core/Activity/ActivityRepository.cs | 252 | ||||
| -rw-r--r-- | Emby.Server.Core/ApplicationHost.cs | 56 | ||||
| -rw-r--r-- | Emby.Server.Core/Data/SqliteDisplayPreferencesRepository.cs | 312 | ||||
| -rw-r--r-- | Emby.Server.Core/Devices/DeviceRepository.cs | 208 | ||||
| -rw-r--r-- | Emby.Server.Core/Migrations/DbMigration.cs | 3 | ||||
| -rw-r--r-- | Emby.Server.Core/Migrations/IVersionMigration.cs | 9 | ||||
| -rw-r--r-- | Emby.Server.Core/Migrations/UpdateLevelMigration.cs | 1 | ||||
| -rw-r--r-- | Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs | 470 | ||||
| -rw-r--r-- | Emby.Server.Core/Security/AuthenticationRepository.cs | 315 | ||||
| -rw-r--r-- | Emby.Server.Core/Social/SharingRepository.cs | 158 |
10 files changed, 30 insertions, 1754 deletions
diff --git a/Emby.Server.Core/Activity/ActivityRepository.cs b/Emby.Server.Core/Activity/ActivityRepository.cs deleted file mode 100644 index c11dcf723..000000000 --- a/Emby.Server.Core/Activity/ActivityRepository.cs +++ /dev/null @@ -1,252 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.IO; -using System.Threading.Tasks; -using Emby.Server.Core.Data; -using MediaBrowser.Controller; -using MediaBrowser.Model.Activity; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Querying; - -namespace Emby.Server.Core.Activity -{ - public class ActivityRepository : BaseSqliteRepository, IActivityRepository - { - private readonly CultureInfo _usCulture = new CultureInfo("en-US"); - - public ActivityRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector connector) - : base(logManager, connector) - { - DbFilePath = Path.Combine(appPaths.DataPath, "activitylog.db"); - } - - public async Task Initialize() - { - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - string[] queries = { - - "create table if not exists ActivityLogEntries (Id GUID PRIMARY KEY, Name TEXT, Overview TEXT, ShortOverview TEXT, Type TEXT, ItemId TEXT, UserId TEXT, DateCreated DATETIME, LogSeverity TEXT)", - "create index if not exists idx_ActivityLogEntries on ActivityLogEntries(Id)" - }; - - connection.RunQueries(queries, Logger); - } - } - - private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLogEntries"; - - public Task Create(ActivityLogEntry entry) - { - return Update(entry); - } - - public async Task Update(ActivityLogEntry entry) - { - if (entry == null) - { - throw new ArgumentNullException("entry"); - } - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var saveActivityCommand = connection.CreateCommand()) - { - saveActivityCommand.CommandText = "replace into ActivityLogEntries (Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Id, @Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"; - - saveActivityCommand.Parameters.Add(saveActivityCommand, "@Id"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@Name"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@Overview"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@ShortOverview"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@Type"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@ItemId"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@UserId"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@DateCreated"); - saveActivityCommand.Parameters.Add(saveActivityCommand, "@LogSeverity"); - - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - var index = 0; - - saveActivityCommand.GetParameter(index++).Value = new Guid(entry.Id); - saveActivityCommand.GetParameter(index++).Value = entry.Name; - saveActivityCommand.GetParameter(index++).Value = entry.Overview; - saveActivityCommand.GetParameter(index++).Value = entry.ShortOverview; - saveActivityCommand.GetParameter(index++).Value = entry.Type; - saveActivityCommand.GetParameter(index++).Value = entry.ItemId; - saveActivityCommand.GetParameter(index++).Value = entry.UserId; - saveActivityCommand.GetParameter(index++).Value = entry.Date; - saveActivityCommand.GetParameter(index++).Value = entry.Severity.ToString(); - - saveActivityCommand.Transaction = transaction; - - saveActivityCommand.ExecuteNonQuery(); - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save record:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - - public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit) - { - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = BaseActivitySelectText; - - var whereClauses = new List<string>(); - - if (minDate.HasValue) - { - whereClauses.Add("DateCreated>=@DateCreated"); - cmd.Parameters.Add(cmd, "@DateCreated", DbType.Date).Value = minDate.Value; - } - - 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 ActivityLogEntries {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()); - - cmd.CommandText += whereText; - - cmd.CommandText += " ORDER BY DateCreated DESC"; - - if (limit.HasValue) - { - cmd.CommandText += " LIMIT " + limit.Value.ToString(_usCulture); - } - - cmd.CommandText += "; select count (Id) from ActivityLogEntries" + whereTextWithoutPaging; - - var list = new List<ActivityLogEntry>(); - var count = 0; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) - { - while (reader.Read()) - { - list.Add(GetEntry(reader)); - } - - if (reader.NextResult() && reader.Read()) - { - count = reader.GetInt32(0); - } - } - - return new QueryResult<ActivityLogEntry>() - { - Items = list.ToArray(), - TotalRecordCount = count - }; - } - } - } - - private ActivityLogEntry GetEntry(IDataReader reader) - { - var index = 0; - - var info = new ActivityLogEntry - { - Id = reader.GetGuid(index).ToString("N") - }; - - index++; - if (!reader.IsDBNull(index)) - { - info.Name = reader.GetString(index); - } - - index++; - if (!reader.IsDBNull(index)) - { - info.Overview = reader.GetString(index); - } - - index++; - if (!reader.IsDBNull(index)) - { - info.ShortOverview = reader.GetString(index); - } - - index++; - if (!reader.IsDBNull(index)) - { - info.Type = reader.GetString(index); - } - - index++; - if (!reader.IsDBNull(index)) - { - info.ItemId = reader.GetString(index); - } - - index++; - if (!reader.IsDBNull(index)) - { - info.UserId = reader.GetString(index); - } - - index++; - info.Date = reader.GetDateTime(index).ToUniversalTime(); - - index++; - if (!reader.IsDBNull(index)) - { - info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader.GetString(index), true); - } - - return info; - } - } -} diff --git a/Emby.Server.Core/ApplicationHost.cs b/Emby.Server.Core/ApplicationHost.cs index d3d292ca5..8a62a9b27 100644 --- a/Emby.Server.Core/ApplicationHost.cs +++ b/Emby.Server.Core/ApplicationHost.cs @@ -83,23 +83,20 @@ using Emby.Dlna.Main; using Emby.Dlna.MediaReceiverRegistrar; using Emby.Dlna.Ssdp; using Emby.Server.Core; -using Emby.Server.Core.Activity; +using Emby.Server.Implementations.Activity; using Emby.Server.Core.Configuration; using Emby.Server.Core.Data; -using Emby.Server.Core.Devices; +using Emby.Server.Implementations.Devices; using Emby.Server.Core.FFMpeg; using Emby.Server.Core.IO; using Emby.Server.Core.Localization; using Emby.Server.Core.Migrations; -using Emby.Server.Core.Notifications; -using Emby.Server.Core.Security; -using Emby.Server.Core.Social; +using Emby.Server.Implementations.Security; +using Emby.Server.Implementations.Social; using Emby.Server.Core.Sync; -using Emby.Server.Implementations.Activity; using Emby.Server.Implementations.Channels; using Emby.Server.Implementations.Collections; using Emby.Server.Implementations.Connect; -using Emby.Server.Implementations.Devices; using Emby.Server.Implementations.Dto; using Emby.Server.Implementations.EntryPoints; using Emby.Server.Implementations.FileOrganization; @@ -110,7 +107,7 @@ using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; using Emby.Server.Implementations.MediaEncoder; using Emby.Server.Implementations.Notifications; -using Emby.Server.Implementations.Persistence; +using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.Security; using Emby.Server.Implementations.ServerManager; @@ -136,6 +133,7 @@ using ServiceStack; using SocketHttpListener.Primitives; using StringExtensions = MediaBrowser.Controller.Extensions.StringExtensions; using Emby.Drawing; +using Emby.Server.Implementations.Migrations; namespace Emby.Server.Core { @@ -282,12 +280,12 @@ namespace Emby.Server.Core INetworkManager networkManager, Action<string, string> certificateGenerator, Func<string> defaultUsernameFactory) - : base(applicationPaths, - logManager, - fileSystem, - environmentInfo, - systemEvents, - memoryStreamFactory, + : base(applicationPaths, + logManager, + fileSystem, + environmentInfo, + systemEvents, + memoryStreamFactory, networkManager) { StartupOptions = options; @@ -556,7 +554,7 @@ namespace Emby.Server.Core UserRepository = await GetUserRepository().ConfigureAwait(false); - var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager, JsonSerializer, ApplicationPaths, GetDbConnector(), MemoryStreamFactory); + var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager.GetLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, MemoryStreamFactory); DisplayPreferencesRepository = displayPreferencesRepo; RegisterSingleInstance(DisplayPreferencesRepository); @@ -683,11 +681,11 @@ namespace Emby.Server.Core EncodingManager = new EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager); RegisterSingleInstance(EncodingManager); - var sharingRepo = new SharingRepository(LogManager, ApplicationPaths, GetDbConnector()); - await sharingRepo.Initialize().ConfigureAwait(false); + var sharingRepo = new SharingRepository(LogManager.GetLogger("SharingRepository"), ApplicationPaths); + sharingRepo.Initialize(); RegisterSingleInstance<ISharingManager>(new SharingManager(sharingRepo, ServerConfigurationManager, LibraryManager, this)); - var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false); + var activityLogRepo = GetActivityLogRepository(); RegisterSingleInstance(activityLogRepo); RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager)); @@ -701,14 +699,14 @@ namespace Emby.Server.Core SubtitleEncoder = new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, MemoryStreamFactory, ProcessFactory, textEncoding); RegisterSingleInstance(SubtitleEncoder); - await displayPreferencesRepo.Initialize().ConfigureAwait(false); + displayPreferencesRepo.Initialize(); var userDataRepo = new SqliteUserDataRepository(LogManager, ApplicationPaths, GetDbConnector()); ((UserDataManager)UserDataManager).Repository = userDataRepo; await itemRepo.Initialize(userDataRepo).ConfigureAwait(false); ((LibraryManager)LibraryManager).ItemRepository = ItemRepository; - await ConfigureNotificationsRepository().ConfigureAwait(false); + ConfigureNotificationsRepository(); progress.Report(100); SetStaticProperties(); @@ -792,7 +790,7 @@ namespace Emby.Server.Core () => SubtitleEncoder, () => MediaSourceManager, HttpClient, - ZipClient, + ZipClient, MemoryStreamFactory, ProcessFactory, (Environment.ProcessorCount > 2 ? 14000 : 40000), @@ -830,18 +828,18 @@ namespace Emby.Server.Core private async Task<IAuthenticationRepository> GetAuthenticationRepository() { - var repo = new AuthenticationRepository(LogManager, ServerConfigurationManager.ApplicationPaths, GetDbConnector()); + var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths); - await repo.Initialize().ConfigureAwait(false); + repo.Initialize(); return repo; } - private async Task<IActivityRepository> GetActivityLogRepository() + private IActivityRepository GetActivityLogRepository() { - var repo = new ActivityRepository(LogManager, ServerConfigurationManager.ApplicationPaths, GetDbConnector()); + var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths); - await repo.Initialize().ConfigureAwait(false); + repo.Initialize(); return repo; } @@ -858,11 +856,11 @@ namespace Emby.Server.Core /// <summary> /// Configures the repositories. /// </summary> - private async Task ConfigureNotificationsRepository() + private void ConfigureNotificationsRepository() { - var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths, GetDbConnector()); + var repo = new SqliteNotificationsRepository(LogManager.GetLogger("SqliteNotificationsRepository"), ServerConfigurationManager.ApplicationPaths); - await repo.Initialize().ConfigureAwait(false); + repo.Initialize(); NotificationsRepository = repo; diff --git a/Emby.Server.Core/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Core/Data/SqliteDisplayPreferencesRepository.cs deleted file mode 100644 index a9e63a11d..000000000 --- a/Emby.Server.Core/Data/SqliteDisplayPreferencesRepository.cs +++ /dev/null @@ -1,312 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; - -namespace Emby.Server.Core.Data -{ - /// <summary> - /// Class SQLiteDisplayPreferencesRepository - /// </summary> - public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository - { - private readonly IMemoryStreamFactory _memoryStreamProvider; - - public SqliteDisplayPreferencesRepository(ILogManager logManager, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IDbConnector dbConnector, IMemoryStreamFactory memoryStreamProvider) - : base(logManager, dbConnector) - { - _jsonSerializer = jsonSerializer; - _memoryStreamProvider = memoryStreamProvider; - DbFilePath = Path.Combine(appPaths.DataPath, "displaypreferences.db"); - } - - /// <summary> - /// Gets the name of the repository - /// </summary> - /// <value>The name.</value> - public string Name - { - get - { - return "SQLite"; - } - } - - /// <summary> - /// The _json serializer - /// </summary> - private readonly IJsonSerializer _jsonSerializer; - - /// <summary> - /// Opens the connection to the database - /// </summary> - /// <returns>Task.</returns> - public async Task Initialize() - { - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - string[] queries = { - - "create table if not exists userdisplaypreferences (id GUID, userId GUID, client text, data BLOB)", - "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)" - }; - - connection.RunQueries(queries, Logger); - } - } - - /// <summary> - /// Save the display preferences associated with an item in the repo - /// </summary> - /// <param name="displayPreferences">The display preferences.</param> - /// <param name="userId">The user id.</param> - /// <param name="client">The client.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>Task.</returns> - /// <exception cref="System.ArgumentNullException">item</exception> - public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken) - { - if (displayPreferences == null) - { - throw new ArgumentNullException("displayPreferences"); - } - if (string.IsNullOrWhiteSpace(displayPreferences.Id)) - { - throw new ArgumentNullException("displayPreferences.Id"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var serialized = _jsonSerializer.SerializeToBytes(displayPreferences, _memoryStreamProvider); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)"; - - cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = new Guid(displayPreferences.Id); - cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId; - cmd.Parameters.Add(cmd, "@3", DbType.String).Value = client; - cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized; - - cmd.Transaction = transaction; - - cmd.ExecuteNonQuery(); - } - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save display preferences:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - - /// <summary> - /// Save all display preferences associated with a user in the repo - /// </summary> - /// <param name="displayPreferences">The display preferences.</param> - /// <param name="userId">The user id.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>Task.</returns> - /// <exception cref="System.ArgumentNullException">item</exception> - public async Task SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId, CancellationToken cancellationToken) - { - if (displayPreferences == null) - { - throw new ArgumentNullException("displayPreferences"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - foreach (var displayPreference in displayPreferences) - { - - var serialized = _jsonSerializer.SerializeToBytes(displayPreference, _memoryStreamProvider); - - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)"; - - cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = new Guid(displayPreference.Id); - cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId; - cmd.Parameters.Add(cmd, "@3", DbType.String).Value = displayPreference.Client; - cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized; - - cmd.Transaction = transaction; - - cmd.ExecuteNonQuery(); - } - } - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save display preferences:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - - /// <summary> - /// Gets the display preferences. - /// </summary> - /// <param name="displayPreferencesId">The display preferences id.</param> - /// <param name="userId">The user id.</param> - /// <param name="client">The client.</param> - /// <returns>Task{DisplayPreferences}.</returns> - /// <exception cref="System.ArgumentNullException">item</exception> - public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, Guid userId, string client) - { - if (string.IsNullOrWhiteSpace(displayPreferencesId)) - { - throw new ArgumentNullException("displayPreferencesId"); - } - - var guidId = displayPreferencesId.GetMD5(); - - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client"; - - cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = guidId; - cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId; - cmd.Parameters.Add(cmd, "@client", DbType.String).Value = client; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow)) - { - if (reader.Read()) - { - using (var stream = reader.GetMemoryStream(0, _memoryStreamProvider)) - { - return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream); - } - } - } - - return new DisplayPreferences - { - Id = guidId.ToString("N") - }; - } - } - } - - /// <summary> - /// Gets all display preferences for the given user. - /// </summary> - /// <param name="userId">The user id.</param> - /// <returns>Task{DisplayPreferences}.</returns> - /// <exception cref="System.ArgumentNullException">item</exception> - public IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId) - { - var list = new List<DisplayPreferences>(); - - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "select data from userdisplaypreferences where userId=@userId"; - - cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) - { - while (reader.Read()) - { - using (var stream = reader.GetMemoryStream(0, _memoryStreamProvider)) - { - list.Add(_jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream)); - } - } - } - } - } - - return list; - } - - public Task SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken) - { - return SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken); - } - - public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client) - { - return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client); - } - } -}
\ No newline at end of file diff --git a/Emby.Server.Core/Devices/DeviceRepository.cs b/Emby.Server.Core/Devices/DeviceRepository.cs deleted file mode 100644 index 63aa7b67a..000000000 --- a/Emby.Server.Core/Devices/DeviceRepository.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Devices; -using MediaBrowser.Model.Devices; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.Session; - -namespace Emby.Server.Core.Devices -{ - public class DeviceRepository : IDeviceRepository - { - private readonly object _syncLock = new object(); - - private readonly IApplicationPaths _appPaths; - private readonly IJsonSerializer _json; - private readonly ILogger _logger; - private readonly IFileSystem _fileSystem; - - private Dictionary<string, DeviceInfo> _devices; - - public DeviceRepository(IApplicationPaths appPaths, IJsonSerializer json, ILogger logger, IFileSystem fileSystem) - { - _appPaths = appPaths; - _json = json; - _logger = logger; - _fileSystem = fileSystem; - } - - private string GetDevicesPath() - { - return Path.Combine(_appPaths.DataPath, "devices"); - } - - private string GetDevicePath(string id) - { - return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N")); - } - - public Task SaveDevice(DeviceInfo device) - { - var path = Path.Combine(GetDevicePath(device.Id), "device.json"); - _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); - - lock (_syncLock) - { - _json.SerializeToFile(device, path); - _devices[device.Id] = device; - } - return Task.FromResult(true); - } - - public Task SaveCapabilities(string reportedId, ClientCapabilities capabilities) - { - var device = GetDevice(reportedId); - - if (device == null) - { - throw new ArgumentException("No device has been registed with id " + reportedId); - } - - device.Capabilities = capabilities; - SaveDevice(device); - - return Task.FromResult(true); - } - - public ClientCapabilities GetCapabilities(string reportedId) - { - var device = GetDevice(reportedId); - - return device == null ? null : device.Capabilities; - } - - public DeviceInfo GetDevice(string id) - { - if (string.IsNullOrWhiteSpace(id)) - { - throw new ArgumentNullException("id"); - } - - return GetDevices() - .FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase)); - } - - public IEnumerable<DeviceInfo> GetDevices() - { - lock (_syncLock) - { - if (_devices == null) - { - _devices = new Dictionary<string, DeviceInfo>(StringComparer.OrdinalIgnoreCase); - - var devices = LoadDevices().ToList(); - foreach (var device in devices) - { - _devices[device.Id] = device; - } - } - return _devices.Values.ToList(); - } - } - - private IEnumerable<DeviceInfo> LoadDevices() - { - var path = GetDevicesPath(); - - try - { - return _fileSystem - .GetFilePaths(path, true) - .Where(i => string.Equals(Path.GetFileName(i), "device.json", StringComparison.OrdinalIgnoreCase)) - .ToList() - .Select(i => - { - try - { - return _json.DeserializeFromFile<DeviceInfo>(i); - } - catch (Exception ex) - { - _logger.ErrorException("Error reading {0}", ex, i); - return null; - } - }) - .Where(i => i != null); - } - catch (IOException) - { - return new List<DeviceInfo>(); - } - } - - public Task DeleteDevice(string id) - { - var path = GetDevicePath(id); - - lock (_syncLock) - { - try - { - _fileSystem.DeleteDirectory(path, true); - } - catch (DirectoryNotFoundException) - { - } - - _devices = null; - } - - return Task.FromResult(true); - } - - public ContentUploadHistory GetCameraUploadHistory(string deviceId) - { - var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json"); - - lock (_syncLock) - { - try - { - return _json.DeserializeFromFile<ContentUploadHistory>(path); - } - catch (IOException) - { - return new ContentUploadHistory - { - DeviceId = deviceId - }; - } - } - } - - public void AddCameraUpload(string deviceId, LocalFileInfo file) - { - var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json"); - _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); - - lock (_syncLock) - { - ContentUploadHistory history; - - try - { - history = _json.DeserializeFromFile<ContentUploadHistory>(path); - } - catch (IOException) - { - history = new ContentUploadHistory - { - DeviceId = deviceId - }; - } - - history.DeviceId = deviceId; - history.FilesUploaded.Add(file); - - _json.SerializeToFile(history, path); - } - } - } -} diff --git a/Emby.Server.Core/Migrations/DbMigration.cs b/Emby.Server.Core/Migrations/DbMigration.cs index 17e086093..5d652770f 100644 --- a/Emby.Server.Core/Migrations/DbMigration.cs +++ b/Emby.Server.Core/Migrations/DbMigration.cs @@ -1,8 +1,9 @@ using System.Threading.Tasks; -using Emby.Server.Implementations.Persistence; +using Emby.Server.Implementations.Data; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Tasks; using Emby.Server.Core.Data; +using Emby.Server.Implementations.Migrations; namespace Emby.Server.Core.Migrations { diff --git a/Emby.Server.Core/Migrations/IVersionMigration.cs b/Emby.Server.Core/Migrations/IVersionMigration.cs deleted file mode 100644 index 0190e289a..000000000 --- a/Emby.Server.Core/Migrations/IVersionMigration.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Threading.Tasks; - -namespace Emby.Server.Core.Migrations -{ - public interface IVersionMigration - { - Task Run(); - } -} diff --git a/Emby.Server.Core/Migrations/UpdateLevelMigration.cs b/Emby.Server.Core/Migrations/UpdateLevelMigration.cs index bbedd7b63..c79dbabea 100644 --- a/Emby.Server.Core/Migrations/UpdateLevelMigration.cs +++ b/Emby.Server.Core/Migrations/UpdateLevelMigration.cs @@ -9,6 +9,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; +using Emby.Server.Implementations.Migrations; namespace Emby.Server.Core.Migrations { diff --git a/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs b/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs deleted file mode 100644 index cd4ac28dc..000000000 --- a/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs +++ /dev/null @@ -1,470 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Emby.Server.Core.Data; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Notifications; - -namespace Emby.Server.Core.Notifications -{ - public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository - { - public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector dbConnector) : base(logManager, dbConnector) - { - DbFilePath = Path.Combine(appPaths.DataPath, "notifications.db"); - } - - public event EventHandler<NotificationUpdateEventArgs> NotificationAdded; - public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead; - ////public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated; - - public async Task Initialize() - { - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - string[] queries = { - - "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT NULL, Url TEXT NULL, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT NULL, PRIMARY KEY (Id, UserId))", - "create index if not exists idx_Notifications1 on Notifications(Id)", - "create index if not exists idx_Notifications2 on Notifications(UserId)" - }; - - connection.RunQueries(queries, Logger); - } - } - - /// <summary> - /// Gets the notifications. - /// </summary> - /// <param name="query">The query.</param> - /// <returns>NotificationResult.</returns> - public NotificationResult GetNotifications(NotificationQuery query) - { - var result = new NotificationResult(); - - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - var clauses = new List<string>(); - - if (query.IsRead.HasValue) - { - clauses.Add("IsRead=@IsRead"); - cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = query.IsRead.Value; - } - - clauses.Add("UserId=@UserId"); - cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = new Guid(query.UserId); - - var whereClause = " where " + string.Join(" And ", clauses.ToArray()); - - cmd.CommandText = string.Format("select count(Id) from Notifications{0};select Id,UserId,Date,Name,Description,Url,Level,IsRead,Category,RelatedId from Notifications{0} order by IsRead asc, Date desc", whereClause); - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) - { - if (reader.Read()) - { - result.TotalRecordCount = reader.GetInt32(0); - } - - if (reader.NextResult()) - { - var notifications = GetNotifications(reader); - - if (query.StartIndex.HasValue) - { - notifications = notifications.Skip(query.StartIndex.Value); - } - - if (query.Limit.HasValue) - { - notifications = notifications.Take(query.Limit.Value); - } - - result.Notifications = notifications.ToArray(); - } - } - - return result; - } - } - } - - public NotificationsSummary GetNotificationsSummary(string userId) - { - var result = new NotificationsSummary(); - - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "select Level from Notifications where UserId=@UserId and IsRead=@IsRead"; - - cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = new Guid(userId); - cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = false; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) - { - var levels = new List<NotificationLevel>(); - - while (reader.Read()) - { - levels.Add(GetLevel(reader, 0)); - } - - result.UnreadCount = levels.Count; - - if (levels.Count > 0) - { - result.MaxUnreadNotificationLevel = levels.Max(); - } - } - - return result; - } - } - } - - /// <summary> - /// Gets the notifications. - /// </summary> - /// <param name="reader">The reader.</param> - /// <returns>IEnumerable{Notification}.</returns> - private IEnumerable<Notification> GetNotifications(IDataReader reader) - { - var list = new List<Notification>(); - - while (reader.Read()) - { - list.Add(GetNotification(reader)); - } - - return list; - } - - private Notification GetNotification(IDataReader reader) - { - var notification = new Notification - { - Id = reader.GetGuid(0).ToString("N"), - UserId = reader.GetGuid(1).ToString("N"), - Date = reader.GetDateTime(2).ToUniversalTime(), - Name = reader.GetString(3) - }; - - if (!reader.IsDBNull(4)) - { - notification.Description = reader.GetString(4); - } - - if (!reader.IsDBNull(5)) - { - notification.Url = reader.GetString(5); - } - - notification.Level = GetLevel(reader, 6); - notification.IsRead = reader.GetBoolean(7); - - return notification; - } - - /// <summary> - /// Gets the level. - /// </summary> - /// <param name="reader">The reader.</param> - /// <param name="index">The index.</param> - /// <returns>NotificationLevel.</returns> - private NotificationLevel GetLevel(IDataReader reader, int index) - { - NotificationLevel level; - - var val = reader.GetString(index); - - Enum.TryParse(val, true, out level); - - return level; - } - - /// <summary> - /// Adds the notification. - /// </summary> - /// <param name="notification">The notification.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>Task.</returns> - public async Task AddNotification(Notification notification, CancellationToken cancellationToken) - { - await ReplaceNotification(notification, cancellationToken).ConfigureAwait(false); - - if (NotificationAdded != null) - { - try - { - NotificationAdded(this, new NotificationUpdateEventArgs - { - Notification = notification - }); - } - catch (Exception ex) - { - Logger.ErrorException("Error in NotificationAdded event handler", ex); - } - } - } - - /// <summary> - /// Replaces the notification. - /// </summary> - /// <param name="notification">The notification.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>Task.</returns> - private async Task ReplaceNotification(Notification notification, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(notification.Id)) - { - notification.Id = Guid.NewGuid().ToString("N"); - } - if (string.IsNullOrEmpty(notification.UserId)) - { - throw new ArgumentException("The notification must have a user id"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var replaceNotificationCommand = connection.CreateCommand()) - { - replaceNotificationCommand.CommandText = "replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)"; - - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Id"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@UserId"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Date"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Name"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Description"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Url"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Level"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@IsRead"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Category"); - replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@RelatedId"); - - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - replaceNotificationCommand.GetParameter("@Id").Value = new Guid(notification.Id); - replaceNotificationCommand.GetParameter("@UserId").Value = new Guid(notification.UserId); - replaceNotificationCommand.GetParameter("@Date").Value = notification.Date.ToUniversalTime(); - replaceNotificationCommand.GetParameter("@Name").Value = notification.Name; - replaceNotificationCommand.GetParameter("@Description").Value = notification.Description; - replaceNotificationCommand.GetParameter("@Url").Value = notification.Url; - replaceNotificationCommand.GetParameter("@Level").Value = notification.Level.ToString(); - replaceNotificationCommand.GetParameter("@IsRead").Value = notification.IsRead; - replaceNotificationCommand.GetParameter("@Category").Value = string.Empty; - replaceNotificationCommand.GetParameter("@RelatedId").Value = string.Empty; - - replaceNotificationCommand.Transaction = transaction; - - replaceNotificationCommand.ExecuteNonQuery(); - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save notification:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - - /// <summary> - /// Marks the read. - /// </summary> - /// <param name="notificationIdList">The notification id list.</param> - /// <param name="userId">The user id.</param> - /// <param name="isRead">if set to <c>true</c> [is read].</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>Task.</returns> - public async Task MarkRead(IEnumerable<string> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken) - { - var list = notificationIdList.ToList(); - var idArray = list.Select(i => new Guid(i)).ToArray(); - - await MarkReadInternal(idArray, userId, isRead, cancellationToken).ConfigureAwait(false); - - if (NotificationsMarkedRead != null) - { - try - { - NotificationsMarkedRead(this, new NotificationReadEventArgs - { - IdList = list.ToArray(), - IsRead = isRead, - UserId = userId - }); - } - catch (Exception ex) - { - Logger.ErrorException("Error in NotificationsMarkedRead event handler", ex); - } - } - } - - public async Task MarkAllRead(string userId, bool isRead, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var markAllReadCommand = connection.CreateCommand()) - { - markAllReadCommand.CommandText = "update Notifications set IsRead=@IsRead where UserId=@UserId"; - - markAllReadCommand.Parameters.Add(markAllReadCommand, "@UserId"); - markAllReadCommand.Parameters.Add(markAllReadCommand, "@IsRead"); - - IDbTransaction transaction = null; - - try - { - cancellationToken.ThrowIfCancellationRequested(); - - transaction = connection.BeginTransaction(); - - markAllReadCommand.GetParameter(0).Value = new Guid(userId); - markAllReadCommand.GetParameter(1).Value = isRead; - - markAllReadCommand.ExecuteNonQuery(); - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save notification:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - - private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, string userId, bool isRead, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var markReadCommand = connection.CreateCommand()) - { - markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId"; - - markReadCommand.Parameters.Add(markReadCommand, "@UserId"); - markReadCommand.Parameters.Add(markReadCommand, "@IsRead"); - markReadCommand.Parameters.Add(markReadCommand, "@Id"); - - IDbTransaction transaction = null; - - try - { - cancellationToken.ThrowIfCancellationRequested(); - - transaction = connection.BeginTransaction(); - - markReadCommand.GetParameter(0).Value = new Guid(userId); - markReadCommand.GetParameter(1).Value = isRead; - - foreach (var id in notificationIdList) - { - markReadCommand.GetParameter(2).Value = id; - - markReadCommand.Transaction = transaction; - - markReadCommand.ExecuteNonQuery(); - } - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save notification:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - } -} diff --git a/Emby.Server.Core/Security/AuthenticationRepository.cs b/Emby.Server.Core/Security/AuthenticationRepository.cs deleted file mode 100644 index 548585375..000000000 --- a/Emby.Server.Core/Security/AuthenticationRepository.cs +++ /dev/null @@ -1,315 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Emby.Server.Core.Data; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Security; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Querying; - -namespace Emby.Server.Core.Security -{ - public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository - { - private readonly IServerApplicationPaths _appPaths; - private readonly CultureInfo _usCulture = new CultureInfo("en-US"); - - public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector connector) - : base(logManager, connector) - { - _appPaths = appPaths; - DbFilePath = Path.Combine(appPaths.DataPath, "authentication.db"); - } - - public async Task Initialize() - { - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - string[] queries = { - - "create table if not exists AccessTokens (Id GUID PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT, AppName TEXT, AppVersion TEXT, DeviceName TEXT, UserId TEXT, IsActive BIT, DateCreated DATETIME NOT NULL, DateRevoked DATETIME)", - "create index if not exists idx_AccessTokens on AccessTokens(Id)" - }; - - connection.RunQueries(queries, Logger); - - connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT"); - } - } - - public Task Create(AuthenticationInfo info, CancellationToken cancellationToken) - { - info.Id = Guid.NewGuid().ToString("N"); - - return Update(info, cancellationToken); - } - - public async Task Update(AuthenticationInfo info, CancellationToken cancellationToken) - { - if (info == null) - { - throw new ArgumentNullException("info"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var saveInfoCommand = connection.CreateCommand()) - { - saveInfoCommand.CommandText = "replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)"; - - saveInfoCommand.Parameters.Add(saveInfoCommand, "@Id"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@AccessToken"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceId"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppName"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppVersion"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceName"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@UserId"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@IsActive"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateCreated"); - saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateRevoked"); - - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - saveInfoCommand.GetParameter("@Id").Value = new Guid(info.Id); - saveInfoCommand.GetParameter("@AccessToken").Value = info.AccessToken; - saveInfoCommand.GetParameter("@DeviceId").Value = info.DeviceId; - saveInfoCommand.GetParameter("@AppName").Value = info.AppName; - saveInfoCommand.GetParameter("@AppVersion").Value = info.AppVersion; - saveInfoCommand.GetParameter("@DeviceName").Value = info.DeviceName; - saveInfoCommand.GetParameter("@UserId").Value = info.UserId; - saveInfoCommand.GetParameter("@IsActive").Value = info.IsActive; - saveInfoCommand.GetParameter("@DateCreated").Value = info.DateCreated; - saveInfoCommand.GetParameter("@DateRevoked").Value = info.DateRevoked; - - saveInfoCommand.Transaction = transaction; - - saveInfoCommand.ExecuteNonQuery(); - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save record:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - - private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens"; - - public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query) - { - if (query == null) - { - throw new ArgumentNullException("query"); - } - - using (var connection = CreateConnection(true).Result) - { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = BaseSelectText; - - var whereClauses = new List<string>(); - - var startIndex = query.StartIndex ?? 0; - - if (!string.IsNullOrWhiteSpace(query.AccessToken)) - { - whereClauses.Add("AccessToken=@AccessToken"); - cmd.Parameters.Add(cmd, "@AccessToken", DbType.String).Value = query.AccessToken; - } - - if (!string.IsNullOrWhiteSpace(query.UserId)) - { - whereClauses.Add("UserId=@UserId"); - cmd.Parameters.Add(cmd, "@UserId", DbType.String).Value = query.UserId; - } - - if (!string.IsNullOrWhiteSpace(query.DeviceId)) - { - whereClauses.Add("DeviceId=@DeviceId"); - cmd.Parameters.Add(cmd, "@DeviceId", DbType.String).Value = query.DeviceId; - } - - if (query.IsActive.HasValue) - { - whereClauses.Add("IsActive=@IsActive"); - cmd.Parameters.Add(cmd, "@IsActive", DbType.Boolean).Value = query.IsActive.Value; - } - - if (query.HasUser.HasValue) - { - if (query.HasUser.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 > 0) - { - var pagingWhereText = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray()); - - whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM AccessTokens {0} ORDER BY DateCreated LIMIT {1})", - pagingWhereText, - startIndex.ToString(_usCulture))); - } - - var whereText = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray()); - - cmd.CommandText += whereText; - - cmd.CommandText += " ORDER BY DateCreated"; - - if (query.Limit.HasValue) - { - cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(_usCulture); - } - - cmd.CommandText += "; select count (Id) from AccessTokens" + whereTextWithoutPaging; - - var list = new List<AuthenticationInfo>(); - var count = 0; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) - { - while (reader.Read()) - { - list.Add(Get(reader)); - } - - if (reader.NextResult() && reader.Read()) - { - count = reader.GetInt32(0); - } - } - - return new QueryResult<AuthenticationInfo>() - { - Items = list.ToArray(), - TotalRecordCount = count - }; - } - } - } - - public AuthenticationInfo Get(string id) - { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentNullException("id"); - } - - using (var connection = CreateConnection(true).Result) - { - var guid = new Guid(id); - - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = BaseSelectText + " where Id=@Id"; - - cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = guid; - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow)) - { - if (reader.Read()) - { - return Get(reader); - } - } - } - - return null; - } - } - - private AuthenticationInfo Get(IDataReader reader) - { - var info = new AuthenticationInfo - { - Id = reader.GetGuid(0).ToString("N"), - AccessToken = reader.GetString(1) - }; - - if (!reader.IsDBNull(2)) - { - info.DeviceId = reader.GetString(2); - } - - if (!reader.IsDBNull(3)) - { - info.AppName = reader.GetString(3); - } - - if (!reader.IsDBNull(4)) - { - info.AppVersion = reader.GetString(4); - } - - if (!reader.IsDBNull(5)) - { - info.DeviceName = reader.GetString(5); - } - - if (!reader.IsDBNull(6)) - { - info.UserId = reader.GetString(6); - } - - info.IsActive = reader.GetBoolean(7); - info.DateCreated = reader.GetDateTime(8).ToUniversalTime(); - - if (!reader.IsDBNull(9)) - { - info.DateRevoked = reader.GetDateTime(9).ToUniversalTime(); - } - - return info; - } - } -} diff --git a/Emby.Server.Core/Social/SharingRepository.cs b/Emby.Server.Core/Social/SharingRepository.cs deleted file mode 100644 index 5503b7ab3..000000000 --- a/Emby.Server.Core/Social/SharingRepository.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Data; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Emby.Server.Core.Data; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Social; - -namespace Emby.Server.Core.Social -{ - public class SharingRepository : BaseSqliteRepository, ISharingRepository - { - public SharingRepository(ILogManager logManager, IApplicationPaths appPaths, IDbConnector dbConnector) - : base(logManager, dbConnector) - { - DbFilePath = Path.Combine(appPaths.DataPath, "shares.db"); - } - - /// <summary> - /// Opens the connection to the database - /// </summary> - /// <returns>Task.</returns> - public async Task Initialize() - { - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - string[] queries = { - - "create table if not exists Shares (Id GUID, ItemId TEXT, UserId TEXT, ExpirationDate DateTime, PRIMARY KEY (Id))", - "create index if not exists idx_Shares on Shares(Id)", - - "pragma shrink_memory" - }; - - connection.RunQueries(queries, Logger); - } - } - - public async Task CreateShare(SocialShareInfo info) - { - if (info == null) - { - throw new ArgumentNullException("info"); - } - if (string.IsNullOrWhiteSpace(info.Id)) - { - throw new ArgumentNullException("info.Id"); - } - - var cancellationToken = CancellationToken.None; - - cancellationToken.ThrowIfCancellationRequested(); - - using (var connection = await CreateConnection().ConfigureAwait(false)) - { - using (var saveShareCommand = connection.CreateCommand()) - { - saveShareCommand.CommandText = "replace into Shares (Id, ItemId, UserId, ExpirationDate) values (@Id, @ItemId, @UserId, @ExpirationDate)"; - - saveShareCommand.Parameters.Add(saveShareCommand, "@Id"); - saveShareCommand.Parameters.Add(saveShareCommand, "@ItemId"); - saveShareCommand.Parameters.Add(saveShareCommand, "@UserId"); - saveShareCommand.Parameters.Add(saveShareCommand, "@ExpirationDate"); - - IDbTransaction transaction = null; - - try - { - transaction = connection.BeginTransaction(); - - saveShareCommand.GetParameter(0).Value = new Guid(info.Id); - saveShareCommand.GetParameter(1).Value = info.ItemId; - saveShareCommand.GetParameter(2).Value = info.UserId; - saveShareCommand.GetParameter(3).Value = info.ExpirationDate; - - saveShareCommand.Transaction = transaction; - - saveShareCommand.ExecuteNonQuery(); - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - Logger.ErrorException("Failed to save share:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - } - } - } - } - - public SocialShareInfo GetShareInfo(string id) - { - if (string.IsNullOrWhiteSpace(id)) - { - throw new ArgumentNullException("id"); - } - - using (var connection = CreateConnection(true).Result) - { - var cmd = connection.CreateCommand(); - cmd.CommandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = @id"; - - cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = new Guid(id); - - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow)) - { - if (reader.Read()) - { - return GetSocialShareInfo(reader); - } - } - - return null; - } - } - - private SocialShareInfo GetSocialShareInfo(IDataReader reader) - { - var info = new SocialShareInfo(); - - info.Id = reader.GetGuid(0).ToString("N"); - info.ItemId = reader.GetString(1); - info.UserId = reader.GetString(2); - info.ExpirationDate = reader.GetDateTime(3).ToUniversalTime(); - - return info; - } - - public async Task DeleteShare(string id) - { - - } - } -} |
