diff options
| author | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-11-19 00:52:49 -0500 |
|---|---|---|
| committer | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-11-19 00:52:49 -0500 |
| commit | 65a1ef020b205b1676bd7dd70e7261a1fa29b7a2 (patch) | |
| tree | b9130379ceead0c3ca1495a7b41ff97baab14040 /Emby.Server.Implementations | |
| parent | e58e34ceca52914bd2475c76ede5f7ee91964d00 (diff) | |
move sync repository to portable project
Diffstat (limited to 'Emby.Server.Implementations')
12 files changed, 1062 insertions, 162 deletions
diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index ea9e537c9..7bc77402e 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -87,7 +87,7 @@ namespace Emby.Server.Implementations.Activity if (minDate.HasValue) { - whereClauses.Add("DateCreated>=@DateCreated"); + whereClauses.Add("DateCreated>=?"); paramList.Add(minDate.Value.ToDateTimeParamValue()); } diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs new file mode 100644 index 000000000..05cde91e2 --- /dev/null +++ b/Emby.Server.Implementations/Browser/BrowserLauncher.cs @@ -0,0 +1,73 @@ +using MediaBrowser.Controller; +using System; + +namespace Emby.Server.Implementations.Browser +{ + /// <summary> + /// Class BrowserLauncher + /// </summary> + public static class BrowserLauncher + { + /// <summary> + /// Opens the dashboard page. + /// </summary> + /// <param name="page">The page.</param> + /// <param name="appHost">The app host.</param> + public static void OpenDashboardPage(string page, IServerApplicationHost appHost) + { + var url = appHost.GetLocalApiUrl("localhost") + "/web/" + page; + + OpenUrl(appHost, url); + } + + /// <summary> + /// Opens the community. + /// </summary> + public static void OpenCommunity(IServerApplicationHost appHost) + { + OpenUrl(appHost, "http://emby.media/community"); + } + + public static void OpenEmbyPremiere(IServerApplicationHost appHost) + { + OpenDashboardPage("supporterkey.html", appHost); + } + + /// <summary> + /// Opens the web client. + /// </summary> + /// <param name="appHost">The app host.</param> + public static void OpenWebClient(IServerApplicationHost appHost) + { + OpenDashboardPage("index.html", appHost); + } + + /// <summary> + /// Opens the dashboard. + /// </summary> + /// <param name="appHost">The app host.</param> + public static void OpenDashboard(IServerApplicationHost appHost) + { + OpenDashboardPage("dashboard.html", appHost); + } + + /// <summary> + /// Opens the URL. + /// </summary> + /// <param name="url">The URL.</param> + private static void OpenUrl(IServerApplicationHost appHost, string url) + { + try + { + appHost.LaunchUrl(url); + } + catch (NotImplementedException) + { + + } + catch (Exception) + { + } + } + } +} diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 8febe83b2..c47a534d1 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Logging; using SQLitePCL.pretty; +using System.Linq; namespace Emby.Server.Implementations.Data { @@ -120,21 +121,30 @@ namespace Emby.Server.Implementations.Data } - protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type) + protected List<string> GetColumnNames(IDatabaseConnection connection, string table) { + var list = new List<string>(); + foreach (var row in connection.Query("PRAGMA table_info(" + table + ")")) { if (row[1].SQLiteType != SQLiteType.Null) { var name = row[1].ToString(); - if (string.Equals(name, columnName, StringComparison.OrdinalIgnoreCase)) - { - return; - } + list.Add(name); } } + return list; + } + + protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames) + { + if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase)) + { + return; + } + connection.ExecuteAll(string.Join(";", new string[] { "alter table " + table, diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs index dd32e2cbd..3f11b6eb0 100644 --- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs +++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs @@ -1,5 +1,4 @@ using MediaBrowser.Common.Progress; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; @@ -7,20 +6,13 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.IO; using MediaBrowser.Model.IO; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Tasks; -using Emby.Server.Implementations.ScheduledTasks; namespace Emby.Server.Implementations.Data { @@ -29,26 +21,14 @@ namespace Emby.Server.Implementations.Data private readonly ILibraryManager _libraryManager; private readonly IItemRepository _itemRepo; private readonly ILogger _logger; - private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; - private readonly IHttpServer _httpServer; - private readonly ILocalizationManager _localization; - private readonly ITaskManager _taskManager; - public const int MigrationVersion = 23; - public static bool EnableUnavailableMessage = false; - const int LatestSchemaVersion = 109; - - public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager) + public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IFileSystem fileSystem) { _libraryManager = libraryManager; _itemRepo = itemRepo; _logger = logger; - _config = config; _fileSystem = fileSystem; - _httpServer = httpServer; - _localization = localization; - _taskManager = taskManager; } public string Name @@ -68,8 +48,6 @@ namespace Emby.Server.Implementations.Data public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress) { - OnProgress(0); - // Ensure these objects are lazy loaded. // Without this there is a deadlock that will need to be investigated var rootChildren = _libraryManager.RootFolder.Children.ToList(); @@ -78,19 +56,7 @@ namespace Emby.Server.Implementations.Data var innerProgress = new ActionableProgress<double>(); innerProgress.RegisterAction(p => { - double newPercentCommplete = .4 * p; - OnProgress(newPercentCommplete); - - progress.Report(newPercentCommplete); - }); - - await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false); - - innerProgress = new ActionableProgress<double>(); - innerProgress.RegisterAction(p => - { - double newPercentCommplete = 40 + .05 * p; - OnProgress(newPercentCommplete); + double newPercentCommplete = .45 * p; progress.Report(newPercentCommplete); }); await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false); @@ -100,122 +66,12 @@ namespace Emby.Server.Implementations.Data innerProgress.RegisterAction(p => { double newPercentCommplete = 45 + .55 * p; - OnProgress(newPercentCommplete); progress.Report(newPercentCommplete); }); await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false); progress.Report(100); await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false); - - if (_config.Configuration.MigrationVersion < MigrationVersion) - { - _config.Configuration.MigrationVersion = MigrationVersion; - _config.SaveConfiguration(); - } - - if (_config.Configuration.SchemaVersion < LatestSchemaVersion) - { - _config.Configuration.SchemaVersion = LatestSchemaVersion; - _config.SaveConfiguration(); - } - - if (EnableUnavailableMessage) - { - EnableUnavailableMessage = false; - _httpServer.GlobalResponse = null; - _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>(); - } - - _taskManager.SuspendTriggers = false; - } - - private void OnProgress(double newPercentCommplete) - { - if (EnableUnavailableMessage) - { - var html = "<!doctype html><html><head><title>Emby</title></head><body>"; - var text = _localization.GetLocalizedString("DbUpgradeMessage"); - html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture)); - - html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>"; - html += "</body></html>"; - - _httpServer.GlobalResponse = html; - } - } - - private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress) - { - var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery - { - IsCurrentSchema = false, - ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name } - }); - - var numComplete = 0; - var numItems = itemIds.Count; - - _logger.Debug("Upgrading schema for {0} items", numItems); - - var list = new List<BaseItem>(); - - foreach (var itemId in itemIds) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (itemId != Guid.Empty) - { - // Somehow some invalid data got into the db. It probably predates the boundary checking - var item = _libraryManager.GetItemById(itemId); - - if (item != null) - { - list.Add(item); - } - } - - if (list.Count >= 1000) - { - try - { - await _itemRepo.SaveItems(list, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.ErrorException("Error saving item", ex); - } - - list.Clear(); - } - - numComplete++; - double percent = numComplete; - percent /= numItems; - progress.Report(percent * 100); - } - - if (list.Count > 0) - { - try - { - await _itemRepo.SaveItems(list, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.ErrorException("Error saving item", ex); - } - } - - progress.Report(100); } private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 653a6a9c1..973576a0d 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -36,6 +36,7 @@ <Compile Include="Activity\ActivityManager.cs" /> <Compile Include="Activity\ActivityRepository.cs" /> <Compile Include="Branding\BrandingConfigurationFactory.cs" /> + <Compile Include="Browser\BrowserLauncher.cs" /> <Compile Include="Channels\ChannelConfigurations.cs" /> <Compile Include="Channels\ChannelDynamicMediaSourceProvider.cs" /> <Compile Include="Channels\ChannelImageProvider.cs" /> @@ -64,6 +65,7 @@ <Compile Include="EntryPoints\RecordingNotifier.cs" /> <Compile Include="EntryPoints\RefreshUsersMetadata.cs" /> <Compile Include="EntryPoints\ServerEventNotifier.cs" /> + <Compile Include="EntryPoints\StartupWizard.cs" /> <Compile Include="EntryPoints\SystemEvents.cs" /> <Compile Include="EntryPoints\UdpServerEntryPoint.cs" /> <Compile Include="EntryPoints\UsageEntryPoint.cs" /> @@ -174,6 +176,7 @@ <Compile Include="Localization\LocalizationManager.cs" /> <Compile Include="MediaEncoder\EncodingManager.cs" /> <Compile Include="Migrations\IVersionMigration.cs" /> + <Compile Include="Migrations\UpdateLevelMigration.cs" /> <Compile Include="News\NewsEntryPoint.cs" /> <Compile Include="News\NewsService.cs" /> <Compile Include="Notifications\CoreNotificationTypes.cs" /> @@ -258,6 +261,7 @@ <Compile Include="Sync\SyncManager.cs" /> <Compile Include="Sync\SyncNotificationEntryPoint.cs" /> <Compile Include="Sync\SyncRegistrationInfo.cs" /> + <Compile Include="Sync\SyncRepository.cs" /> <Compile Include="Sync\TargetDataProvider.cs" /> <Compile Include="TV\SeriesPostScanTask.cs" /> <Compile Include="TV\TVSeriesManager.cs" /> diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs new file mode 100644 index 000000000..424153f22 --- /dev/null +++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs @@ -0,0 +1,59 @@ +using Emby.Server.Implementations.Browser; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Model.Logging; + +namespace Emby.Server.Implementations.EntryPoints +{ + /// <summary> + /// Class StartupWizard + /// </summary> + public class StartupWizard : IServerEntryPoint + { + /// <summary> + /// The _app host + /// </summary> + private readonly IServerApplicationHost _appHost; + /// <summary> + /// The _user manager + /// </summary> + private readonly ILogger _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="StartupWizard" /> class. + /// </summary> + /// <param name="appHost">The app host.</param> + /// <param name="logger">The logger.</param> + public StartupWizard(IServerApplicationHost appHost, ILogger logger) + { + _appHost = appHost; + _logger = logger; + } + + /// <summary> + /// Runs this instance. + /// </summary> + public void Run() + { + if (_appHost.IsFirstRun) + { + LaunchStartupWizard(); + } + } + + /// <summary> + /// Launches the startup wizard. + /// </summary> + private void LaunchStartupWizard() + { + BrowserLauncher.OpenDashboardPage("wizardstart.html", _appHost); + } + + /// <summary> + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// </summary> + public void Dispose() + { + } + } +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs b/Emby.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs index 5be7ba7ad..48a85e0e0 100644 --- a/Emby.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs +++ b/Emby.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.FileOrganization return new[] { // Every so often - new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromMinutes(5).Ticks} + new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromMinutes(15).Ticks} }; } diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 876d140ec..c1758127a 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -59,12 +59,13 @@ namespace Emby.Server.Implementations.HttpServer private readonly IEnvironmentInfo _environment; private readonly IStreamFactory _streamFactory; private readonly Func<Type, Func<string, object>> _funcParseFn; + private readonly bool _enableDualModeSockets; public HttpListenerHost(IServerApplicationHost applicationHost, ILogger logger, IServerConfigurationManager config, string serviceName, - string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, IEnvironmentInfo environment, ICertificate certificate, IStreamFactory streamFactory, Func<Type, Func<string, object>> funcParseFn) + string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, IEnvironmentInfo environment, ICertificate certificate, IStreamFactory streamFactory, Func<Type, Func<string, object>> funcParseFn, bool enableDualModeSockets) : base(serviceName) { _appHost = applicationHost; @@ -80,6 +81,7 @@ namespace Emby.Server.Implementations.HttpServer _certificate = certificate; _streamFactory = streamFactory; _funcParseFn = funcParseFn; + _enableDualModeSockets = enableDualModeSockets; _config = config; _logger = logger; @@ -179,8 +181,6 @@ namespace Emby.Server.Implementations.HttpServer private IHttpListener GetListener() { - var enableDualMode = _environment.OperatingSystem == OperatingSystem.Windows; - return new WebSocketSharpListener(_logger, _certificate, _memoryStreamProvider, @@ -189,7 +189,7 @@ namespace Emby.Server.Implementations.HttpServer _socketFactory, _cryptoProvider, _streamFactory, - enableDualMode, + _enableDualModeSockets, GetRequest); } diff --git a/Emby.Server.Implementations/Migrations/UpdateLevelMigration.cs b/Emby.Server.Implementations/Migrations/UpdateLevelMigration.cs new file mode 100644 index 000000000..c532ea08d --- /dev/null +++ b/Emby.Server.Implementations/Migrations/UpdateLevelMigration.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Common.Updates; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Updates; + +namespace Emby.Server.Implementations.Migrations +{ + public class UpdateLevelMigration : IVersionMigration + { + private readonly IServerConfigurationManager _config; + private readonly IServerApplicationHost _appHost; + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private readonly string _releaseAssetFilename; + private readonly ILogger _logger; + + public UpdateLevelMigration(IServerConfigurationManager config, IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer, string releaseAssetFilename, ILogger logger) + { + _config = config; + _appHost = appHost; + _httpClient = httpClient; + _jsonSerializer = jsonSerializer; + _releaseAssetFilename = releaseAssetFilename; + _logger = logger; + } + + public async Task Run() + { + var lastVersion = _config.Configuration.LastVersion; + var currentVersion = _appHost.ApplicationVersion; + + if (string.Equals(lastVersion, currentVersion.ToString(), StringComparison.OrdinalIgnoreCase)) + { + return; + } + + try + { + var updateLevel = _config.Configuration.SystemUpdateLevel; + + await CheckVersion(currentVersion, updateLevel, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.ErrorException("Error in update migration", ex); + } + } + + private async Task CheckVersion(Version currentVersion, PackageVersionClass currentUpdateLevel, CancellationToken cancellationToken) + { + var releases = await new GithubUpdater(_httpClient, _jsonSerializer) + .GetLatestReleases("MediaBrowser", "Emby", _releaseAssetFilename, cancellationToken).ConfigureAwait(false); + + var newUpdateLevel = GetNewUpdateLevel(currentVersion, currentUpdateLevel, releases); + + if (newUpdateLevel != currentUpdateLevel) + { + _config.Configuration.SystemUpdateLevel = newUpdateLevel; + _config.SaveConfiguration(); + } + } + + private PackageVersionClass GetNewUpdateLevel(Version currentVersion, PackageVersionClass currentUpdateLevel, List<GithubUpdater.RootObject> releases) + { + var newUpdateLevel = currentUpdateLevel; + + // If the current version is later than current stable, set the update level to beta + if (releases.Count >= 1) + { + var release = releases[0]; + var version = ParseVersion(release.tag_name); + if (version != null) + { + if (currentVersion > version) + { + newUpdateLevel = PackageVersionClass.Beta; + } + else + { + return PackageVersionClass.Release; + } + } + } + + // If the current version is later than current beta, set the update level to dev + if (releases.Count >= 2) + { + var release = releases[1]; + var version = ParseVersion(release.tag_name); + if (version != null) + { + if (currentVersion > version) + { + newUpdateLevel = PackageVersionClass.Dev; + } + else + { + return PackageVersionClass.Beta; + } + } + } + + return newUpdateLevel; + } + + private Version ParseVersion(string versionString) + { + if (!string.IsNullOrWhiteSpace(versionString)) + { + var parts = versionString.Split('.'); + if (parts.Length == 3) + { + versionString += ".0"; + } + } + + Version version; + Version.TryParse(versionString, out version); + + return version; + } + } +} diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index 5179bd258..f4cb42d29 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -40,7 +40,9 @@ namespace Emby.Server.Implementations.Security connection.RunInTransaction(db => { - AddColumn(db, "AccessTokens", "AppVersion", "TEXT"); + var existingColumnNames = GetColumnNames(db, "AccessTokens"); + + AddColumn(db, "AccessTokens", "AppVersion", "TEXT", existingColumnNames); }); } } diff --git a/Emby.Server.Implementations/Sync/SyncRepository.cs b/Emby.Server.Implementations/Sync/SyncRepository.cs new file mode 100644 index 000000000..fbc5772f3 --- /dev/null +++ b/Emby.Server.Implementations/Sync/SyncRepository.cs @@ -0,0 +1,770 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Emby.Server.Implementations.Data; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Sync; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Sync; +using SQLitePCL.pretty; + +namespace Emby.Server.Implementations.Sync +{ + public class SyncRepository : BaseSqliteRepository, ISyncRepository + { + private readonly CultureInfo _usCulture = new CultureInfo("en-US"); + + private readonly IJsonSerializer _json; + + public SyncRepository(ILogger logger, IJsonSerializer json, IServerApplicationPaths appPaths) + : base(logger) + { + _json = json; + DbFilePath = Path.Combine(appPaths.DataPath, "sync14.db"); + } + + private class SyncSummary + { + public Dictionary<string, int> Items { get; set; } + + public SyncSummary() + { + Items = new Dictionary<string, int>(); + } + } + + public void Initialize() + { + using (var connection = CreateConnection()) + { + string[] queries = { + + "create table if not exists SyncJobs (Id GUID PRIMARY KEY, TargetId TEXT NOT NULL, Name TEXT NOT NULL, Profile TEXT, Quality TEXT, Bitrate INT, Status TEXT NOT NULL, Progress FLOAT, UserId TEXT NOT NULL, ItemIds TEXT NOT NULL, Category TEXT, ParentId TEXT, UnwatchedOnly BIT, ItemLimit INT, SyncNewContent BIT, DateCreated DateTime, DateLastModified DateTime, ItemCount int)", + + "create table if not exists SyncJobItems (Id GUID PRIMARY KEY, ItemId TEXT, ItemName TEXT, MediaSourceId TEXT, JobId TEXT, TemporaryPath TEXT, OutputPath TEXT, Status TEXT, TargetId TEXT, DateCreated DateTime, Progress FLOAT, AdditionalFiles TEXT, MediaSource TEXT, IsMarkedForRemoval BIT, JobItemIndex INT, ItemDateModifiedTicks BIGINT)", + + "drop index if exists idx_SyncJobItems2", + "drop index if exists idx_SyncJobItems3", + "drop index if exists idx_SyncJobs1", + "drop index if exists idx_SyncJobs", + "drop index if exists idx_SyncJobItems1", + "create index if not exists idx_SyncJobItems4 on SyncJobItems(TargetId,ItemId,Status,Progress,DateCreated)", + "create index if not exists idx_SyncJobItems5 on SyncJobItems(TargetId,Status,ItemId,Progress)", + + "create index if not exists idx_SyncJobs2 on SyncJobs(TargetId,Status,ItemIds,Progress)", + + "pragma shrink_memory" + }; + + connection.RunQueries(queries); + + connection.RunInTransaction(db => + { + var existingColumnNames = GetColumnNames(db, "SyncJobs"); + AddColumn(db, "SyncJobs", "Profile", "TEXT", existingColumnNames); + AddColumn(db, "SyncJobs", "Bitrate", "INT", existingColumnNames); + + existingColumnNames = GetColumnNames(db, "SyncJobItems"); + AddColumn(db, "SyncJobItems", "ItemDateModifiedTicks", "BIGINT", existingColumnNames); + }); + } + } + + private const string BaseJobSelectText = "select Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount from SyncJobs"; + private const string BaseJobItemSelectText = "select Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex, ItemDateModifiedTicks from SyncJobItems"; + + public SyncJob GetJob(string id) + { + if (string.IsNullOrEmpty(id)) + { + throw new ArgumentNullException("id"); + } + + CheckDisposed(); + + var guid = new Guid(id); + + if (guid == Guid.Empty) + { + throw new ArgumentNullException("id"); + } + + lock (WriteLock) + { + using (var connection = CreateConnection(true)) + { + var commandText = BaseJobSelectText + " where Id=?"; + var paramList = new List<object>(); + + paramList.Add(guid.ToGuidParamValue()); + + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + return GetJob(row); + } + + return null; + } + } + } + + private SyncJob GetJob(IReadOnlyList<IResultSetValue> reader) + { + var info = new SyncJob + { + Id = reader[0].ReadGuid().ToString("N"), + TargetId = reader[1].ToString(), + Name = reader[2].ToString() + }; + + if (reader[3].SQLiteType != SQLiteType.Null) + { + info.Profile = reader[3].ToString(); + } + + if (reader[4].SQLiteType != SQLiteType.Null) + { + info.Quality = reader[4].ToString(); + } + + if (reader[5].SQLiteType != SQLiteType.Null) + { + info.Bitrate = reader[5].ToInt(); + } + + if (reader[6].SQLiteType != SQLiteType.Null) + { + info.Status = (SyncJobStatus)Enum.Parse(typeof(SyncJobStatus), reader[6].ToString(), true); + } + + if (reader[7].SQLiteType != SQLiteType.Null) + { + info.Progress = reader[7].ToDouble(); + } + + if (reader[8].SQLiteType != SQLiteType.Null) + { + info.UserId = reader[8].ToString(); + } + + if (reader[9].SQLiteType != SQLiteType.Null) + { + info.RequestedItemIds = reader[9].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + } + + if (reader[10].SQLiteType != SQLiteType.Null) + { + info.Category = (SyncCategory)Enum.Parse(typeof(SyncCategory), reader[10].ToString(), true); + } + + if (reader[11].SQLiteType != SQLiteType.Null) + { + info.ParentId = reader[11].ToString(); + } + + if (reader[12].SQLiteType != SQLiteType.Null) + { + info.UnwatchedOnly = reader[12].ToBool(); + } + + if (reader[13].SQLiteType != SQLiteType.Null) + { + info.ItemLimit = reader[13].ToInt(); + } + + info.SyncNewContent = reader[14].ToBool(); + + info.DateCreated = reader[15].ReadDateTime(); + info.DateLastModified = reader[16].ReadDateTime(); + info.ItemCount = reader[17].ToInt(); + + return info; + } + + public Task Create(SyncJob job) + { + return InsertOrUpdate(job, true); + } + + public Task Update(SyncJob job) + { + return InsertOrUpdate(job, false); + } + + private async Task InsertOrUpdate(SyncJob job, bool insert) + { + if (job == null) + { + throw new ArgumentNullException("job"); + } + + CheckDisposed(); + + lock (WriteLock) + { + using (var connection = CreateConnection()) + { + string commandText; + var paramList = new List<object>(); + + if (insert) + { + commandText = "insert into SyncJobs (Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + } + else + { + commandText = "update SyncJobs set TargetId=?,Name=?,Profile=?,Quality=?,Bitrate=?,Status=?,Progress=?,UserId=?,ItemIds=?,Category=?,ParentId=?,UnwatchedOnly=?,ItemLimit=?,SyncNewContent=?,DateCreated=?,DateLastModified=?,ItemCount=? where Id=?"; + } + + paramList.Add(job.Id.ToGuidParamValue()); + paramList.Add(job.TargetId); + paramList.Add(job.Name); + paramList.Add(job.Profile); + paramList.Add(job.Quality); + paramList.Add(job.Bitrate); + paramList.Add(job.Status.ToString()); + paramList.Add(job.Progress); + paramList.Add(job.UserId); + + paramList.Add(string.Join(",", job.RequestedItemIds.ToArray())); + paramList.Add(job.Category); + paramList.Add(job.ParentId); + paramList.Add(job.UnwatchedOnly); + paramList.Add(job.ItemLimit); + paramList.Add(job.SyncNewContent); + paramList.Add(job.DateCreated.ToDateTimeParamValue()); + paramList.Add(job.DateLastModified.ToDateTimeParamValue()); + paramList.Add(job.ItemCount); + + connection.RunInTransaction(conn => + { + conn.Execute(commandText, paramList.ToArray()); + }); + } + } + } + + public async Task DeleteJob(string id) + { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentNullException("id"); + } + + CheckDisposed(); + + lock (WriteLock) + { + using (var connection = CreateConnection()) + { + connection.RunInTransaction(conn => + { + conn.Execute("delete from SyncJobs where Id=?", id.ToGuidParamValue()); + conn.Execute("delete from SyncJobItems where JobId=?", id); + }); + } + } + } + + public QueryResult<SyncJob> GetJobs(SyncJobQuery query) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + CheckDisposed(); + + lock (WriteLock) + { + using (var connection = CreateConnection(true)) + { + var commandText = BaseJobSelectText; + var paramList = new List<object>(); + + var whereClauses = new List<string>(); + + if (query.Statuses.Length > 0) + { + var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray()); + + whereClauses.Add(string.Format("Status in ({0})", statuses)); + } + if (!string.IsNullOrWhiteSpace(query.TargetId)) + { + whereClauses.Add("TargetId=?"); + paramList.Add(query.TargetId); + } + if (!string.IsNullOrWhiteSpace(query.ExcludeTargetIds)) + { + var excludeIds = (query.ExcludeTargetIds ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + if (excludeIds.Length == 1) + { + whereClauses.Add("TargetId<>?"); + paramList.Add(excludeIds[0]); + } + else if (excludeIds.Length > 1) + { + whereClauses.Add("TargetId<>?"); + paramList.Add(excludeIds[0]); + } + } + if (!string.IsNullOrWhiteSpace(query.UserId)) + { + whereClauses.Add("UserId=?"); + paramList.Add(query.UserId); + } + if (query.SyncNewContent.HasValue) + { + whereClauses.Add("SyncNewContent=?"); + paramList.Add(query.SyncNewContent.Value); + } + + commandText += " mainTable"; + + var whereTextWithoutPaging = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + var startIndex = query.StartIndex ?? 0; + if (startIndex > 0) + { + whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM SyncJobs ORDER BY (Select Max(DateLastModified) from SyncJobs where TargetId=mainTable.TargetId) DESC, DateLastModified DESC LIMIT {0})", + startIndex.ToString(_usCulture))); + } + + if (whereClauses.Count > 0) + { + commandText += " where " + string.Join(" AND ", whereClauses.ToArray()); + } + + commandText += " ORDER BY (Select Max(DateLastModified) from SyncJobs where TargetId=mainTable.TargetId) DESC, DateLastModified DESC"; + + if (query.Limit.HasValue) + { + commandText += " LIMIT " + query.Limit.Value.ToString(_usCulture); + } + + var list = new List<SyncJob>(); + var count = connection.Query("select count (Id) from SyncJobs" + whereTextWithoutPaging, paramList.ToArray()) + .SelectScalarInt() + .First(); + + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + list.Add(GetJob(row)); + } + + return new QueryResult<SyncJob>() + { + Items = list.ToArray(), + TotalRecordCount = count + }; + } + } + } + + public SyncJobItem GetJobItem(string id) + { + if (string.IsNullOrEmpty(id)) + { + throw new ArgumentNullException("id"); + } + + CheckDisposed(); + + lock (WriteLock) + { + var guid = new Guid(id); + + using (var connection = CreateConnection(true)) + { + var commandText = BaseJobItemSelectText + " where Id=?"; + var paramList = new List<object>(); + + paramList.Add(guid.ToGuidParamValue()); + + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + return GetJobItem(row); + } + + return null; + } + } + } + + private QueryResult<T> GetJobItemReader<T>(SyncJobItemQuery query, string baseSelectText, Func<IReadOnlyList<IResultSetValue>, T> itemFactory) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + lock (WriteLock) + { + using (var connection = CreateConnection(true)) + { + var commandText = baseSelectText; + var paramList = new List<object>(); + + var whereClauses = new List<string>(); + + if (!string.IsNullOrWhiteSpace(query.JobId)) + { + whereClauses.Add("JobId=?"); + paramList.Add(query.JobId); + } + if (!string.IsNullOrWhiteSpace(query.ItemId)) + { + whereClauses.Add("ItemId=?"); + paramList.Add(query.ItemId); + } + if (!string.IsNullOrWhiteSpace(query.TargetId)) + { + whereClauses.Add("TargetId=?"); + paramList.Add(query.TargetId); + } + + if (query.Statuses.Length > 0) + { + var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray()); + + whereClauses.Add(string.Format("Status in ({0})", statuses)); + } + + var whereTextWithoutPaging = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + var startIndex = query.StartIndex ?? 0; + if (startIndex > 0) + { + whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM SyncJobItems ORDER BY JobItemIndex, DateCreated LIMIT {0})", + startIndex.ToString(_usCulture))); + } + + if (whereClauses.Count > 0) + { + commandText += " where " + string.Join(" AND ", whereClauses.ToArray()); + } + + commandText += " ORDER BY JobItemIndex, DateCreated"; + + if (query.Limit.HasValue) + { + commandText += " LIMIT " + query.Limit.Value.ToString(_usCulture); + } + + var list = new List<T>(); + var count = connection.Query("select count (Id) from SyncJobItems" + whereTextWithoutPaging, paramList.ToArray()) + .SelectScalarInt() + .First(); + + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + list.Add(itemFactory(row)); + } + + return new QueryResult<T>() + { + Items = list.ToArray(), + TotalRecordCount = count + }; + } + } + } + + public Dictionary<string, SyncedItemProgress> GetSyncedItemProgresses(SyncJobItemQuery query) + { + var result = new Dictionary<string, SyncedItemProgress>(); + + var now = DateTime.UtcNow; + + lock (WriteLock) + { + using (var connection = CreateConnection(true)) + { + var commandText = "select ItemId,Status,Progress from SyncJobItems"; + + var whereClauses = new List<string>(); + var paramList = new List<object>(); + + if (!string.IsNullOrWhiteSpace(query.TargetId)) + { + whereClauses.Add("TargetId=?"); + paramList.Add(query.TargetId); + } + + if (query.Statuses.Length > 0) + { + var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray()); + + whereClauses.Add(string.Format("Status in ({0})", statuses)); + } + + if (whereClauses.Count > 0) + { + commandText += " where " + string.Join(" AND ", whereClauses.ToArray()); + } + + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + AddStatusResult(row, result, false); + } + LogQueryTime("GetSyncedItemProgresses", commandText, now); + + commandText = commandText + .Replace("select ItemId,Status,Progress from SyncJobItems", "select ItemIds,Status,Progress from SyncJobs") + .Replace("'Synced'", "'Completed','CompletedWithError'"); + + now = DateTime.UtcNow; + foreach (var row in connection.Query(commandText, paramList.ToArray())) + { + AddStatusResult(row, result, true); + } + LogQueryTime("GetSyncedItemProgresses", commandText, now); + } + } + + return result; + } + + private void LogQueryTime(string methodName, string commandText, DateTime startDate) + { + var elapsed = (DateTime.UtcNow - startDate).TotalMilliseconds; + + var slowThreshold = 1000; + +#if DEBUG + slowThreshold = 50; +#endif + + if (elapsed >= slowThreshold) + { + Logger.Debug("{2} query time (slow): {0}ms. Query: {1}", + Convert.ToInt32(elapsed), + commandText, + methodName); + } + else + { + //Logger.Debug("{2} query time: {0}ms. Query: {1}", + // Convert.ToInt32(elapsed), + // cmd.CommandText, + // methodName); + } + } + + private void AddStatusResult(IReadOnlyList<IResultSetValue> reader, Dictionary<string, SyncedItemProgress> result, bool multipleIds) + { + if (reader[0].SQLiteType == SQLiteType.Null) + { + return; + } + + var itemIds = new List<string>(); + + var ids = reader[0].ToString(); + + if (multipleIds) + { + itemIds = ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + } + else + { + itemIds.Add(ids); + } + + if (reader[1].SQLiteType != SQLiteType.Null) + { + SyncJobItemStatus status; + var statusString = reader[1].ToString(); + if (string.Equals(statusString, "Completed", StringComparison.OrdinalIgnoreCase) || + string.Equals(statusString, "CompletedWithError", StringComparison.OrdinalIgnoreCase)) + { + status = SyncJobItemStatus.Synced; + } + else + { + status = (SyncJobItemStatus)Enum.Parse(typeof(SyncJobItemStatus), statusString, true); + } + + if (status == SyncJobItemStatus.Synced) + { + foreach (var itemId in itemIds) + { + result[itemId] = new SyncedItemProgress + { + Status = SyncJobItemStatus.Synced + }; + } + } + else + { + double progress = reader[2].SQLiteType == SQLiteType.Null ? 0.0 : reader[2].ToDouble(); + + foreach (var itemId in itemIds) + { + SyncedItemProgress currentStatus; + if (!result.TryGetValue(itemId, out currentStatus) || (currentStatus.Status != SyncJobItemStatus.Synced && progress >= currentStatus.Progress)) + { + result[itemId] = new SyncedItemProgress + { + Status = status, + Progress = progress + }; + } + } + } + } + } + + public QueryResult<SyncJobItem> GetJobItems(SyncJobItemQuery query) + { + return GetJobItemReader(query, BaseJobItemSelectText, GetJobItem); + } + + public Task Create(SyncJobItem jobItem) + { + return InsertOrUpdate(jobItem, true); + } + + public Task Update(SyncJobItem jobItem) + { + return InsertOrUpdate(jobItem, false); + } + + private async Task InsertOrUpdate(SyncJobItem jobItem, bool insert) + { + if (jobItem == null) + { + throw new ArgumentNullException("jobItem"); + } + + CheckDisposed(); + + lock (WriteLock) + { + using (var connection = CreateConnection()) + { + string commandText; + + if (insert) + { + commandText = "insert into SyncJobItems (Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex, ItemDateModifiedTicks) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + } + else + { + // cmd + commandText = "update SyncJobItems set ItemId=?,ItemName=?,MediaSourceId=?,JobId=?,TemporaryPath=?,OutputPath=?,Status=?,TargetId=?,DateCreated=?,Progress=?,AdditionalFiles=?,MediaSource=?,IsMarkedForRemoval=?,JobItemIndex=?,ItemDateModifiedTicks=? where Id=?"; + } + + var paramList = new List<object>(); + paramList.Add(jobItem.Id.ToGuidParamValue()); + paramList.Add(jobItem.ItemId); + paramList.Add(jobItem.ItemName); + paramList.Add(jobItem.MediaSourceId); + paramList.Add(jobItem.JobId); + paramList.Add(jobItem.TemporaryPath); + paramList.Add(jobItem.OutputPath); + paramList.Add(jobItem.Status.ToString()); + + paramList.Add(jobItem.TargetId); + paramList.Add(jobItem.DateCreated.ToDateTimeParamValue()); + paramList.Add(jobItem.Progress); + paramList.Add(_json.SerializeToString(jobItem.AdditionalFiles)); + paramList.Add(jobItem.MediaSource == null ? null : _json.SerializeToString(jobItem.MediaSource)); + paramList.Add(jobItem.IsMarkedForRemoval); + paramList.Add(jobItem.JobItemIndex); + paramList.Add(jobItem.ItemDateModifiedTicks); + + connection.RunInTransaction(conn => + { + conn.Execute(commandText, paramList.ToArray()); + }); + } + } + } + + private SyncJobItem GetJobItem(IReadOnlyList<IResultSetValue> reader) + { + var info = new SyncJobItem + { + Id = reader[0].ReadGuid().ToString("N"), + ItemId = reader[1].ToString() + }; + + if (reader[2].SQLiteType != SQLiteType.Null) + { + info.ItemName = reader[2].ToString(); + } + + if (reader[3].SQLiteType != SQLiteType.Null) + { + info.MediaSourceId = reader[3].ToString(); + } + + info.JobId = reader[4].ToString(); + + if (reader[5].SQLiteType != SQLiteType.Null) + { + info.TemporaryPath = reader[5].ToString(); + } + if (reader[6].SQLiteType != SQLiteType.Null) + { + info.OutputPath = reader[6].ToString(); + } + + if (reader[7].SQLiteType != SQLiteType.Null) + { + info.Status = (SyncJobItemStatus)Enum.Parse(typeof(SyncJobItemStatus), reader[7].ToString(), true); + } + + info.TargetId = reader[8].ToString(); + + info.DateCreated = reader[9].ReadDateTime(); + + if (reader[10].SQLiteType != SQLiteType.Null) + { + info.Progress = reader[10].ToDouble(); + } + + if (reader[11].SQLiteType != SQLiteType.Null) + { + var json = reader[11].ToString(); + + if (!string.IsNullOrWhiteSpace(json)) + { + info.AdditionalFiles = _json.DeserializeFromString<List<ItemFileInfo>>(json); + } + } + + if (reader[12].SQLiteType != SQLiteType.Null) + { + var json = reader[12].ToString(); + + if (!string.IsNullOrWhiteSpace(json)) + { + info.MediaSource = _json.DeserializeFromString<MediaSourceInfo>(json); + } + } + + info.IsMarkedForRemoval = reader[13].ToBool(); + info.JobItemIndex = reader[14].ToInt(); + + if (reader[15].SQLiteType != SQLiteType.Null) + { + info.ItemDateModifiedTicks = reader[15].ToInt64(); + } + + return info; + } + } +} diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index f3bab7883..a47aaa305 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -148,10 +148,6 @@ namespace Emby.Server.Implementations.TV private string GetUniqueSeriesKey(BaseItem series) { - if (_config.Configuration.SchemaVersion < 97) - { - return series.Id.ToString("N"); - } return series.GetPresentationUniqueKey(); } |
