From f165811e5f0627e138b094a081a68960c3f9a8f9 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 30 Apr 2015 23:00:46 -0400 Subject: [PATCH 01/24] improve handling of anamorphic content --- .../Playback/BaseStreamingService.cs | 28 ++----------------- .../Encoder/BaseEncoder.cs | 28 ++----------------- .../Encoder/VideoEncoder.cs | 2 -- 3 files changed, 6 insertions(+), 52 deletions(-) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index db94e37f49..ba20c0c587 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -598,7 +598,7 @@ namespace MediaBrowser.Api.Playback var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture); var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture); - filters.Add(string.Format("scale=trunc(min(iw\\,{0})/2)*2:trunc(min((iw/dar)\\,{1})/2)*2", maxWidthParam, maxHeightParam)); + filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam)); } // If a fixed width was requested @@ -618,7 +618,7 @@ namespace MediaBrowser.Api.Playback } // If a max width was requested - else if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null)) + else if (request.MaxWidth.HasValue) { var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture); @@ -626,35 +626,13 @@ namespace MediaBrowser.Api.Playback } // If a max height was requested - else if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null)) + else if (request.MaxHeight.HasValue) { var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture); filters.Add(string.Format("scale=trunc(oh*a*2)/2:min(ih\\,{0})", maxHeightParam)); } - else if (request.MaxWidth.HasValue || - request.MaxHeight.HasValue || - request.Width.HasValue || - request.Height.HasValue) - { - if (state.VideoStream != null) - { - // Need to perform calculations manually - - // Try to account for bad media info - var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0; - var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0; - - var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight); - - var manualWidthParam = outputSize.Width.ToString(UsCulture); - var manualHeightParam = outputSize.Height.ToString(UsCulture); - - filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", manualWidthParam, manualHeightParam)); - } - } - if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) { filters[filters.Count - 1] += ":flags=fast_bilinear"; diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs index c30ceb62db..e255373627 100644 --- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs @@ -840,7 +840,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture); var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture); - filters.Add(string.Format("scale=trunc(min(iw\\,{0})/2)*2:trunc(min((iw/dar)\\,{1})/2)*2", maxWidthParam, maxHeightParam)); + filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam)); } // If a fixed width was requested @@ -860,7 +860,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } // If a max width was requested - else if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null)) + else if (request.MaxWidth.HasValue) { var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture); @@ -868,35 +868,13 @@ namespace MediaBrowser.MediaEncoding.Encoder } // If a max height was requested - else if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null)) + else if (request.MaxHeight.HasValue) { var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture); filters.Add(string.Format("scale=trunc(oh*a*2)/2:min(ih\\,{0})", maxHeightParam)); } - else if (request.MaxWidth.HasValue || - request.MaxHeight.HasValue || - request.Width.HasValue || - request.Height.HasValue) - { - if (state.VideoStream != null) - { - // Need to perform calculations manually - - // Try to account for bad media info - var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0; - var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0; - - var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight); - - var manualWidthParam = outputSize.Width.ToString(UsCulture); - var manualHeightParam = outputSize.Height.ToString(UsCulture); - - filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", manualWidthParam, manualHeightParam)); - } - } - var output = string.Empty; if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream) diff --git a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs index 26d4a76509..49eed9ee52 100644 --- a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs @@ -1,8 +1,6 @@ using MediaBrowser.Common.IO; -using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dlna; From 8ae0822e13fff4d72e78732a8f574a1163325423 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 30 Apr 2015 23:00:54 -0400 Subject: [PATCH 02/24] adjust dlna logging --- MediaBrowser.Dlna/PlayTo/Device.cs | 12 ++++---- MediaBrowser.Dlna/PlayTo/SsdpHttpClient.cs | 14 ++++----- .../Service/BaseControlHandler.cs | 6 ++-- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 30 ++++++++++++------- 4 files changed, 36 insertions(+), 26 deletions(-) diff --git a/MediaBrowser.Dlna/PlayTo/Device.cs b/MediaBrowser.Dlna/PlayTo/Device.cs index 00cb34be3e..d0a46e771d 100644 --- a/MediaBrowser.Dlna/PlayTo/Device.cs +++ b/MediaBrowser.Dlna/PlayTo/Device.cs @@ -296,7 +296,7 @@ namespace MediaBrowser.Dlna.PlayTo } var post = AvCommands.BuildPost(command, service.ServiceType, url, dictionary); - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header) + await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); @@ -466,7 +466,7 @@ namespace MediaBrowser.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType)) + var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -499,7 +499,7 @@ namespace MediaBrowser.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType)) + var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -521,7 +521,7 @@ namespace MediaBrowser.Dlna.PlayTo if (service == null) return null; - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, AvCommands.BuildPost(command, service.ServiceType)) + var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, AvCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -558,7 +558,7 @@ namespace MediaBrowser.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType)) + var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -589,7 +589,7 @@ namespace MediaBrowser.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType)) + var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) diff --git a/MediaBrowser.Dlna/PlayTo/SsdpHttpClient.cs b/MediaBrowser.Dlna/PlayTo/SsdpHttpClient.cs index f0689751c5..39d3a8d075 100644 --- a/MediaBrowser.Dlna/PlayTo/SsdpHttpClient.cs +++ b/MediaBrowser.Dlna/PlayTo/SsdpHttpClient.cs @@ -1,7 +1,7 @@ -using System; -using MediaBrowser.Common.Net; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Dlna.Common; +using System; using System.Globalization; using System.IO; using System.Text; @@ -28,9 +28,10 @@ namespace MediaBrowser.Dlna.PlayTo DeviceService service, string command, string postData, + bool logRequest = true, string header = null) { - var response = await PostSoapDataAsync(NormalizeServiceUrl(baseUrl, service.ControlUrl), "\"" + service.ServiceType + "#" + command + "\"", postData, header) + var response = await PostSoapDataAsync(NormalizeServiceUrl(baseUrl, service.ControlUrl), "\"" + service.ServiceType + "#" + command + "\"", postData, header, logRequest) .ConfigureAwait(false); using (var stream = response.Content) @@ -69,7 +70,6 @@ namespace MediaBrowser.Dlna.PlayTo { Url = url, UserAgent = USERAGENT, - LogRequest = _config.GetDlnaConfiguration().EnableDebugLogging, LogErrorResponseBody = true }; @@ -87,7 +87,6 @@ namespace MediaBrowser.Dlna.PlayTo { Url = url, UserAgent = USERAGENT, - LogRequest = _config.GetDlnaConfiguration().EnableDebugLogging, LogErrorResponseBody = true }; @@ -105,7 +104,8 @@ namespace MediaBrowser.Dlna.PlayTo private Task PostSoapDataAsync(string url, string soapAction, string postData, - string header = null) + string header, + bool logRequest) { if (!soapAction.StartsWith("\"")) soapAction = "\"" + soapAction + "\""; @@ -114,7 +114,7 @@ namespace MediaBrowser.Dlna.PlayTo { Url = url, UserAgent = USERAGENT, - LogRequest = _config.GetDlnaConfiguration().EnableDebugLogging, + LogRequest = logRequest || _config.GetDlnaConfiguration().EnableDebugLogging, LogErrorResponseBody = true }; diff --git a/MediaBrowser.Dlna/Service/BaseControlHandler.cs b/MediaBrowser.Dlna/Service/BaseControlHandler.cs index a17182a7e0..a65520d65b 100644 --- a/MediaBrowser.Dlna/Service/BaseControlHandler.cs +++ b/MediaBrowser.Dlna/Service/BaseControlHandler.cs @@ -27,14 +27,16 @@ namespace MediaBrowser.Dlna.Service { try { - if (Config.GetDlnaConfiguration().EnableDebugLogging) + var enableDebugLogging = Config.GetDlnaConfiguration().EnableDebugLogging; + + if (enableDebugLogging) { LogRequest(request); } var response = ProcessControlRequestInternal(request); - if (Config.GetDlnaConfiguration().EnableDebugLogging) + if (enableDebugLogging) { LogResponse(response); } diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index 5b3746aeb4..e21074bd40 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -212,7 +212,9 @@ namespace MediaBrowser.Dlna.Ssdp private void RespondToSearch(EndPoint endpoint, string deviceType) { - if (_config.GetDlnaConfiguration().EnableDebugLogging) + var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; + + if (enableDebugLogging) { _logger.Debug("RespondToSearch"); } @@ -238,7 +240,7 @@ namespace MediaBrowser.Dlna.Ssdp SendDatagram(header, values, endpoint, new IPEndPoint(d.Address, 0), true, 1); //SendDatagram(header, values, endpoint, null, true); - if (_config.GetDlnaConfiguration().EnableDebugLogging) + if (enableDebugLogging) { _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString()); } @@ -316,7 +318,9 @@ namespace MediaBrowser.Dlna.Ssdp var received = (byte[])result.AsyncState; - if (_config.GetDlnaConfiguration().EnableDebugLogging) + var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; + + if (enableDebugLogging) { _logger.Debug(Encoding.ASCII.GetString(received)); } @@ -324,7 +328,7 @@ namespace MediaBrowser.Dlna.Ssdp var args = SsdpHelper.ParseSsdpResponse(received); args.EndPoint = endpoint; - if (_config.GetDlnaConfiguration().EnableDebugLogging) + if (enableDebugLogging) { var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)); var headerText = string.Join(",", headerTexts.ToArray()); @@ -399,17 +403,19 @@ namespace MediaBrowser.Dlna.Ssdp private void NotifyAll() { - if (_config.GetDlnaConfiguration().EnableDebugLogging) + var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; + + if (enableDebugLogging) { _logger.Debug("Sending alive notifications"); } foreach (var d in RegisteredDevices) { - NotifyDevice(d, "alive", 1); + NotifyDevice(d, "alive", 1, enableDebugLogging); } } - private void NotifyDevice(UpnpDevice dev, string type, int sendCount) + private void NotifyDevice(UpnpDevice dev, string type, int sendCount, bool logMessage) { const string header = "NOTIFY * HTTP/1.1"; @@ -424,7 +430,7 @@ namespace MediaBrowser.Dlna.Ssdp values["NT"] = dev.Type; values["USN"] = dev.USN; - if (_config.GetDlnaConfiguration().EnableDebugLogging) + if (logMessage) { _logger.Debug("{0} said {1}", dev.USN, type); } @@ -457,7 +463,7 @@ namespace MediaBrowser.Dlna.Ssdp foreach (var d in dl.ToList()) { - NotifyDevice(d, "byebye", 2); + NotifyDevice(d, "byebye", 2, true); } _logger.Debug("Unregistered mount {0}", uuid); @@ -468,13 +474,15 @@ namespace MediaBrowser.Dlna.Ssdp private int _aliveNotifierIntervalMs; private void ReloadAliveNotifier() { - if (!_config.GetDlnaConfiguration().BlastAliveMessages) + var config = _config.GetDlnaConfiguration(); + + if (!config.BlastAliveMessages) { DisposeNotificationTimer(); return; } - var intervalMs = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 1000; + var intervalMs = config.BlastAliveMessageIntervalSeconds * 1000; if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs) { From 9f4407028bc5e4b42ac417b16a261d3e90b0e7c0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 1 May 2015 14:37:01 -0400 Subject: [PATCH 03/24] update photo resolving --- MediaBrowser.Dlna/PlayTo/PlayToController.cs | 5 +++- .../Manager/ItemImageProvider.cs | 14 ++++++++--- .../Photos/PhotoAlbumImageProvider.cs | 25 ++++++++++--------- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/MediaBrowser.Dlna/PlayTo/PlayToController.cs b/MediaBrowser.Dlna/PlayTo/PlayToController.cs index 5aa8c1f9ca..cf21211f4d 100644 --- a/MediaBrowser.Dlna/PlayTo/PlayToController.cs +++ b/MediaBrowser.Dlna/PlayTo/PlayToController.cs @@ -768,8 +768,11 @@ namespace MediaBrowser.Dlna.PlayTo await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl).ConfigureAwait(false); - if (newItem.StreamInfo.IsDirectStream) + if (newItem.StreamInfo.IsDirectStream && newPosition > 0) { + // This is rather arbitrary, but give the player time to start playing + await Task.Delay(2000).ConfigureAwait(false); + await _device.Seek(TimeSpan.FromTicks(newPosition)).ConfigureAwait(false); } } diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index fc47b0259a..c95cf67256 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -38,13 +38,19 @@ namespace MediaBrowser.Providers.Manager { var hasChanges = false; - var images = providers.OfType() - .SelectMany(i => i.GetImages(item, directoryService)) + var localImageProviders = providers.OfType() .ToList(); - if (MergeImages(item, images)) + if (localImageProviders.Count > 0 || !(item is Photo)) { - hasChanges = true; + var images = localImageProviders + .SelectMany(i => i.GetImages(item, directoryService)) + .ToList(); + + if (MergeImages(item, images)) + { + hasChanges = true; + } } return hasChanges; diff --git a/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs b/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs index 8c142b646a..b55c76b8f8 100644 --- a/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs +++ b/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs @@ -9,18 +9,19 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Photos { - //public class PhotoAlbumImageProvider : BaseDynamicImageProvider - //{ - // public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) : base(fileSystem, providerManager, applicationPaths, imageProcessor) - // { - // } + public class PhotoAlbumImageProvider : BaseDynamicImageProvider + { + public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) + : base(fileSystem, providerManager, applicationPaths, imageProcessor) + { + } - // protected override Task> GetItemsWithImages(IHasImages item) - // { - // var photoAlbum = (PhotoAlbum)item; - // var items = GetFinalItems(photoAlbum.Children.ToList()); + protected override Task> GetItemsWithImages(IHasImages item) + { + var photoAlbum = (PhotoAlbum)item; + var items = GetFinalItems(photoAlbum.Children.ToList()); - // return Task.FromResult(items); - // } - //} + return Task.FromResult(items); + } + } } From 095379c25b89749f58abd03d78aa27aecbd967f3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 May 2015 12:34:27 -0400 Subject: [PATCH 04/24] adjust startup sequences --- .../Api/DashboardService.cs | 27 +++++---- .../Api/PackageCreator.cs | 55 +++++++++++++------ 2 files changed, 54 insertions(+), 28 deletions(-) diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index dcafa94171..119e92cd12 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -52,6 +52,7 @@ namespace MediaBrowser.WebDashboard.Api [Route("/dashboard/Package", "GET")] public class GetDashboardPackage { + public string Mode { get; set; } } /// @@ -134,7 +135,7 @@ namespace MediaBrowser.WebDashboard.Api { var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase)); - return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml(page.GetHtmlStream(), null, false)); + return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml(page.GetHtmlStream(), null, null, false)); } /// @@ -252,7 +253,7 @@ namespace MediaBrowser.WebDashboard.Api var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification; return GetPackageCreator() - .GetResource(path, localizationCulture, _appHost.ApplicationVersion.ToString(), minify); + .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify); } private PackageCreator GetPackageCreator() @@ -292,38 +293,40 @@ namespace MediaBrowser.WebDashboard.Api var appVersion = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture); - await DumpHtml(creator.DashboardUIPath, path, culture, appVersion); - await DumpJs(creator.DashboardUIPath, path, culture, appVersion); + var mode = request.Mode; - await DumpFile("scripts/all.js", Path.Combine(path, "scripts", "all.js"), culture, appVersion).ConfigureAwait(false); - await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), culture, appVersion).ConfigureAwait(false); + await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion); + await DumpJs(creator.DashboardUIPath, path, mode, culture, appVersion); + + await DumpFile("scripts/all.js", Path.Combine(path, "scripts", "all.js"), mode, culture, appVersion).ConfigureAwait(false); + await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false); return ""; } - private async Task DumpHtml(string source, string destination, string culture, string appVersion) + private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion) { foreach (var file in Directory.GetFiles(source, "*.html", SearchOption.TopDirectoryOnly)) { var filename = Path.GetFileName(file); - await DumpFile(filename, Path.Combine(destination, filename), culture, appVersion).ConfigureAwait(false); + await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false); } } - private async Task DumpJs(string source, string destination, string culture, string appVersion) + private async Task DumpJs(string source, string mode, string destination, string culture, string appVersion) { foreach (var file in Directory.GetFiles(source, "*.js", SearchOption.TopDirectoryOnly)) { var filename = Path.GetFileName(file); - await DumpFile("scripts/" + filename, Path.Combine(destination, "scripts", filename), culture, appVersion).ConfigureAwait(false); + await DumpFile("scripts/" + filename, Path.Combine(destination, "scripts", filename), mode, culture, appVersion).ConfigureAwait(false); } } - private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string culture, string appVersion) + private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion) { - using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, culture, appVersion, true).ConfigureAwait(false)) + using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false)) { using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs index 8f4d2ae8b7..26f2f8babd 100644 --- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs +++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs @@ -32,8 +32,10 @@ namespace MediaBrowser.WebDashboard.Api } public async Task GetResource(string path, + string mode, string localizationCulture, - string appVersion, bool enableMinification) + string appVersion, + bool enableMinification) { var isHtml = IsHtml(path); @@ -41,7 +43,7 @@ namespace MediaBrowser.WebDashboard.Api if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase)) { - resourceStream = await GetAllJavascript(localizationCulture, appVersion, enableMinification).ConfigureAwait(false); + resourceStream = await GetAllJavascript(mode, localizationCulture, appVersion, enableMinification).ConfigureAwait(false); } else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase)) { @@ -58,7 +60,7 @@ namespace MediaBrowser.WebDashboard.Api // jQuery ajax doesn't seem to handle if-modified-since correctly if (isHtml) { - resourceStream = await ModifyHtml(resourceStream, localizationCulture, enableMinification).ConfigureAwait(false); + resourceStream = await ModifyHtml(resourceStream, mode, localizationCulture, enableMinification).ConfigureAwait(false); } } @@ -106,10 +108,11 @@ namespace MediaBrowser.WebDashboard.Api /// Modifies the HTML by adding common meta tags, css and js. /// /// The source stream. + /// The mode. /// The localization culture. /// if set to true [enable minification]. /// Task{Stream}. - public async Task ModifyHtml(Stream sourceStream, string localizationCulture, bool enableMinification) + public async Task ModifyHtml(Stream sourceStream, string mode, string localizationCulture, bool enableMinification) { using (sourceStream) { @@ -155,7 +158,7 @@ namespace MediaBrowser.WebDashboard.Api var version = GetType().Assembly.GetName().Version; - html = html.Replace("", "" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version)); + html = html.Replace("", "" + GetMetaTags(mode) + GetCommonCss(mode, version) + GetCommonJavascript(mode, version)); var bytes = Encoding.UTF8.GetBytes(html); @@ -172,12 +175,19 @@ namespace MediaBrowser.WebDashboard.Api /// Gets the meta tags. /// /// System.String. - private static string GetMetaTags() + private static string GetMetaTags(string mode) { var sb = new StringBuilder(); + if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase)) + { + sb.Append(""); + } + sb.Append(""); - sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); sb.Append(""); sb.Append(""); sb.Append(""); @@ -200,11 +210,12 @@ namespace MediaBrowser.WebDashboard.Api /// /// Gets the common CSS. /// + /// The mode. /// The version. /// System.String. - private string GetCommonCss(Version version) + private string GetCommonCss(string mode, Version version) { - var versionString = "?v=" + version; + var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty; var files = new[] { @@ -223,20 +234,26 @@ namespace MediaBrowser.WebDashboard.Api /// /// Gets the common javascript. /// + /// The mode. /// The version. /// System.String. - private string GetCommonJavascript(Version version) + private string GetCommonJavascript(string mode, Version version) { var builder = new StringBuilder(); - var versionString = "?v=" + version; + var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty; - var files = new[] - { - "scripts/all.js" + versionString, - "thirdparty/swipebox-master/js/jquery.swipebox.min.js" + versionString + var files = new List + { + "scripts/all.js" + versionString, + "thirdparty/swipebox-master/js/jquery.swipebox.min.js" + versionString }; + if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase)) + { + files.Insert(0, "cordova.js"); + } + var tags = files.Select(s => string.Format("", s)).ToArray(); builder.Append(string.Join(string.Empty, tags)); @@ -248,7 +265,7 @@ namespace MediaBrowser.WebDashboard.Api /// Gets a stream containing all concatenated javascript /// /// Task{Stream}. - private async Task GetAllJavascript(string culture, string version, bool enableMinification) + private async Task GetAllJavascript(string mode, string culture, string version, bool enableMinification) { var memoryStream = new MemoryStream(); var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine); @@ -267,6 +284,12 @@ namespace MediaBrowser.WebDashboard.Api await AppendLocalization(memoryStream, culture).ConfigureAwait(false); await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(mode)) + { + var appModeBytes = Encoding.UTF8.GetBytes(string.Format("window.appMode='{0}';", mode)); + await memoryStream.WriteAsync(appModeBytes, 0, appModeBytes.Length).ConfigureAwait(false); + } + // Write the version string for the dashboard comparison function var versionString = string.Format("window.dashboardVersion='{0}';", version); var versionBytes = Encoding.UTF8.GetBytes(versionString); From e15ea55b5645456f0da7babe5bfbdc90ced75426 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 May 2015 18:32:41 -0400 Subject: [PATCH 05/24] support multiple orgPn values --- MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index 3a798e3fe7..b3fe28561a 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -164,7 +164,7 @@ namespace MediaBrowser.Model.Dlna if (mediaProfile != null && !string.IsNullOrEmpty(mediaProfile.OrgPn)) { - orgPnValues.Add(mediaProfile.OrgPn); + orgPnValues.AddRange(mediaProfile.OrgPn.Split(',')); } else { From ee2fbf59d02cb63eed15e22e74d3f1dc9981eb37 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 May 2015 18:43:56 -0400 Subject: [PATCH 06/24] remove shrink mem timer --- ...MediaBrowser.Server.Implementations.csproj | 1 - .../Persistence/SqliteChapterRepository.cs | 10 --- .../SqliteFileOrganizationRepository.cs | 9 -- .../Persistence/SqliteItemRepository.cs | 10 --- .../SqliteMediaStreamsRepository.cs | 13 +-- .../SqliteProviderInfoRepository.cs | 10 --- .../Persistence/SqliteShrinkMemoryTimer.cs | 84 ------------------- .../Persistence/SqliteUserDataRepository.cs | 10 --- 8 files changed, 1 insertion(+), 146 deletions(-) delete mode 100644 MediaBrowser.Server.Implementations/Persistence/SqliteShrinkMemoryTimer.cs diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 9e7810c761..519b0f49c0 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -242,7 +242,6 @@ - diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteChapterRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteChapterRepository.cs index 77b9932059..075ef42398 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteChapterRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteChapterRepository.cs @@ -32,8 +32,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _logger = logManager.GetLogger(GetType().Name); } - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; - /// /// Opens the connection to the database /// @@ -54,8 +52,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.RunQueries(queries, _logger); PrepareStatements(); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } /// @@ -286,12 +282,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - if (_connection != null) { if (_connection.IsOpen()) diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs index 5d5855bf8b..b2a0004b42 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs @@ -21,7 +21,6 @@ namespace MediaBrowser.Server.Implementations.Persistence private readonly ILogger _logger; private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; private readonly IServerApplicationPaths _appPaths; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); @@ -61,8 +60,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.RunQueries(queries, _logger); PrepareStatements(); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } private void PrepareStatements() @@ -446,12 +443,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - if (_connection != null) { if (_connection.IsOpen()) diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index e063d44dc6..c5a9db87bf 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -130,12 +130,8 @@ namespace MediaBrowser.Server.Implementations.Persistence _mediaStreamsRepository.Initialize(); _chapterRepository.Initialize(); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; - /// /// The _write lock /// @@ -430,12 +426,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - _writeLock.Wait(); if (_connection != null) diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs index 293da3f0f9..9943976243 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs @@ -1,5 +1,4 @@ -using System.Globalization; -using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using System; @@ -21,8 +20,6 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _deleteStreamsCommand; private IDbCommand _saveStreamCommand; - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; - public SqliteMediaStreamsRepository(IDbConnection connection, ILogManager logManager) { _connection = connection; @@ -64,8 +61,6 @@ namespace MediaBrowser.Server.Implementations.Persistence AddRefFramesCommand(); PrepareStatements(); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } private void AddPixelFormatColumnCommand() @@ -563,12 +558,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - if (_connection != null) { if (_connection.IsOpen()) diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs index 743d8fed6b..62f63395ab 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs @@ -26,8 +26,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _logger = logManager.GetLogger(GetType().Name); } - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; - /// /// Gets the name of the repository /// @@ -66,8 +64,6 @@ namespace MediaBrowser.Server.Implementations.Persistence AddItemDateModifiedCommand(); PrepareStatements(); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } private static readonly string[] StatusColumns = @@ -307,12 +303,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - if (_connection != null) { if (_connection.IsOpen()) diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteShrinkMemoryTimer.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteShrinkMemoryTimer.cs deleted file mode 100644 index b5a0c10b1e..0000000000 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteShrinkMemoryTimer.cs +++ /dev/null @@ -1,84 +0,0 @@ -using MediaBrowser.Model.Logging; -using System; -using System.Data; -using System.Threading; - -namespace MediaBrowser.Server.Implementations.Persistence -{ - class SqliteShrinkMemoryTimer : IDisposable - { - private Timer _shrinkMemoryTimer; - - private readonly SemaphoreSlim _writeLock; - private readonly ILogger _logger; - private readonly IDbConnection _connection; - - public SqliteShrinkMemoryTimer(IDbConnection connection, SemaphoreSlim writeLock, ILogger logger) - { - _connection = connection; - _writeLock = writeLock; - _logger = logger; - - _shrinkMemoryTimer = new Timer(TimerCallback, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(10)); - } - - private async void TimerCallback(object state) - { - await _writeLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); - - IDbTransaction transaction = null; - - try - { - transaction = _connection.BeginTransaction(); - - using (var cmd = _connection.CreateCommand()) - { - cmd.Transaction = transaction; - cmd.CommandText = "pragma shrink_memory"; - cmd.ExecuteNonQuery(); - } - - transaction.Commit(); - } - catch (OperationCanceledException) - { - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - catch (Exception e) - { - _logger.ErrorException("Failed to save items:", e); - - if (transaction != null) - { - transaction.Rollback(); - } - - throw; - } - finally - { - if (transaction != null) - { - transaction.Dispose(); - } - - _writeLock.Release(); - } - } - - public void Dispose() - { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - } - } -} diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs index 0f04881684..786c77605f 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs @@ -55,8 +55,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _logger = logManager.GetLogger(GetType().Name); } - private SqliteShrinkMemoryTimer _shrinkMemoryTimer; - /// /// Opens the connection to the database /// @@ -80,8 +78,6 @@ namespace MediaBrowser.Server.Implementations.Persistence }; _connection.RunQueries(queries, _logger); - - _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger); } /// @@ -402,12 +398,6 @@ namespace MediaBrowser.Server.Implementations.Persistence { lock (_disposeLock) { - if (_shrinkMemoryTimer != null) - { - _shrinkMemoryTimer.Dispose(); - _shrinkMemoryTimer = null; - } - if (_connection != null) { if (_connection.IsOpen()) From ae99233759749494c911b0c0aa2114df5a78b3a2 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 May 2015 18:59:01 -0400 Subject: [PATCH 07/24] rework repo disposal --- ...MediaBrowser.Server.Implementations.csproj | 1 + .../Persistence/BaseSqliteRepository.cs | 56 +++++++++++ .../SqliteDisplayPreferencesRepository.cs | 96 ++++-------------- .../SqliteFileOrganizationRepository.cs | 73 ++++---------- .../SqliteProviderInfoRepository.cs | 70 ++++--------- .../Persistence/SqliteUserDataRepository.cs | 94 +++++------------- .../Persistence/SqliteUserRepository.cs | 99 +++++-------------- .../ApplicationHost.cs | 8 +- 8 files changed, 165 insertions(+), 332 deletions(-) create mode 100644 MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 519b0f49c0..0bbea3acc7 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -226,6 +226,7 @@ + diff --git a/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs b/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs new file mode 100644 index 0000000000..15d76fb603 --- /dev/null +++ b/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs @@ -0,0 +1,56 @@ +using MediaBrowser.Model.Logging; +using System; +using System.Threading; + +namespace MediaBrowser.Server.Implementations.Persistence +{ + public abstract class BaseSqliteRepository : IDisposable + { + protected readonly SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1); + protected ILogger Logger; + + protected BaseSqliteRepository(ILogManager logManager) + { + Logger = logManager.GetLogger(GetType().Name); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private readonly object _disposeLock = new object(); + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool dispose) + { + if (dispose) + { + try + { + lock (_disposeLock) + { + WriteLock.Wait(); + + CloseConnection(); + } + } + catch (Exception ex) + { + Logger.ErrorException("Error disposing database", ex); + } + } + } + + protected virtual void DisposeInternal() + { + + } + + protected abstract void CloseConnection(); + } +} diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteDisplayPreferencesRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteDisplayPreferencesRepository.cs index 3dfa747273..c9ab43e63e 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteDisplayPreferencesRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteDisplayPreferencesRepository.cs @@ -16,11 +16,15 @@ namespace MediaBrowser.Server.Implementations.Persistence /// /// Class SQLiteDisplayPreferencesRepository /// - public class SqliteDisplayPreferencesRepository : IDisplayPreferencesRepository + public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository { private IDbConnection _connection; - private readonly ILogger _logger; + public SqliteDisplayPreferencesRepository(ILogManager logManager, IJsonSerializer jsonSerializer, IApplicationPaths appPaths) : base(logManager) + { + _jsonSerializer = jsonSerializer; + _appPaths = appPaths; + } /// /// Gets the name of the repository @@ -44,36 +48,6 @@ namespace MediaBrowser.Server.Implementations.Persistence /// private readonly IApplicationPaths _appPaths; - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - - /// - /// Initializes a new instance of the class. - /// - /// The app paths. - /// The json serializer. - /// The log manager. - /// - /// jsonSerializer - /// or - /// appPaths - /// - public SqliteDisplayPreferencesRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager) - { - if (jsonSerializer == null) - { - throw new ArgumentNullException("jsonSerializer"); - } - if (appPaths == null) - { - throw new ArgumentNullException("appPaths"); - } - - _jsonSerializer = jsonSerializer; - _appPaths = appPaths; - - _logger = logManager.GetLogger(GetType().Name); - } - /// /// Opens the connection to the database /// @@ -82,7 +56,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -95,7 +69,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); } /// @@ -122,7 +96,7 @@ namespace MediaBrowser.Server.Implementations.Persistence var serialized = _jsonSerializer.SerializeToBytes(displayPreferences); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -157,7 +131,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save display preferences:", e); + Logger.ErrorException("Failed to save display preferences:", e); if (transaction != null) { @@ -173,7 +147,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -194,7 +168,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -235,7 +209,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save display preferences:", e); + Logger.ErrorException("Failed to save display preferences:", e); if (transaction != null) { @@ -251,7 +225,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -322,45 +296,17 @@ namespace MediaBrowser.Server.Implementations.Persistence } } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } + _connection.Close(); + } - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); - } + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs index b2a0004b42..2d5aad04df 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteFileOrganizationRepository.cs @@ -14,13 +14,10 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Persistence { - public class SqliteFileOrganizationRepository : IFileOrganizationRepository, IDisposable + public class SqliteFileOrganizationRepository : BaseSqliteRepository, IFileOrganizationRepository, IDisposable { private IDbConnection _connection; - private readonly ILogger _logger; - - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); private readonly IServerApplicationPaths _appPaths; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); @@ -29,11 +26,9 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _deleteResultCommand; private IDbCommand _deleteAllCommand; - public SqliteFileOrganizationRepository(ILogManager logManager, IServerApplicationPaths appPaths) + public SqliteFileOrganizationRepository(ILogManager logManager, IServerApplicationPaths appPaths) : base(logManager) { _appPaths = appPaths; - - _logger = logManager.GetLogger(GetType().Name); } /// @@ -44,7 +39,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "fileorganization.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -57,7 +52,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); PrepareStatements(); } @@ -100,7 +95,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -142,7 +137,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save FileOrganizationResult:", e); + Logger.ErrorException("Failed to save FileOrganizationResult:", e); if (transaction != null) { @@ -158,7 +153,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -169,7 +164,7 @@ namespace MediaBrowser.Server.Implementations.Persistence throw new ArgumentNullException("id"); } - await _writeLock.WaitAsync().ConfigureAwait(false); + await WriteLock.WaitAsync().ConfigureAwait(false); IDbTransaction transaction = null; @@ -196,7 +191,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to delete FileOrganizationResult:", e); + Logger.ErrorException("Failed to delete FileOrganizationResult:", e); if (transaction != null) { @@ -212,13 +207,13 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } public async Task DeleteAll() { - await _writeLock.WaitAsync().ConfigureAwait(false); + await WriteLock.WaitAsync().ConfigureAwait(false); IDbTransaction transaction = null; @@ -243,7 +238,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to delete results", e); + Logger.ErrorException("Failed to delete results", e); if (transaction != null) { @@ -259,7 +254,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -420,45 +415,17 @@ namespace MediaBrowser.Server.Implementations.Persistence return result; } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } + _connection.Close(); + } - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); - } + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs index 62f63395ab..bce33e834d 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs @@ -1,29 +1,26 @@ -using System.Text; -using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Logging; using System; using System.Data; using System.IO; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Persistence { - public class SqliteProviderInfoRepository : IProviderRepository + public class SqliteProviderInfoRepository : BaseSqliteRepository, IProviderRepository { private IDbConnection _connection; - private readonly ILogger _logger; - private IDbCommand _saveStatusCommand; private readonly IApplicationPaths _appPaths; - public SqliteProviderInfoRepository(IApplicationPaths appPaths, ILogManager logManager) + public SqliteProviderInfoRepository(ILogManager logManager, IApplicationPaths appPaths) : base(logManager) { _appPaths = appPaths; - _logger = logManager.GetLogger(GetType().Name); } /// @@ -46,7 +43,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "refreshinfo.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -59,7 +56,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); AddItemDateModifiedCommand(); @@ -109,14 +106,9 @@ namespace MediaBrowser.Server.Implementations.Persistence builder.AppendLine("alter table MetadataStatus"); builder.AppendLine("add column ItemDateModified DateTime NULL"); - _connection.RunQueries(new[] { builder.ToString() }, _logger); + _connection.RunQueries(new[] { builder.ToString() }, Logger); } - /// - /// The _write lock - /// - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - /// /// Prepares the statements. /// @@ -223,7 +215,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -260,7 +252,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save provider info:", e); + Logger.ErrorException("Failed to save provider info:", e); if (transaction != null) { @@ -276,49 +268,21 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } + _connection.Close(); + } - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); - } + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs index 786c77605f..8b86d19a2f 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteUserDataRepository.cs @@ -11,13 +11,15 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Persistence { - public class SqliteUserDataRepository : IUserDataRepository + public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository { - private readonly ILogger _logger; - - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - private IDbConnection _connection; + private readonly IApplicationPaths _appPaths; + + public SqliteUserDataRepository(ILogManager logManager, IApplicationPaths appPaths) : base(logManager) + { + _appPaths = appPaths; + } /// /// Gets the name of the repository @@ -31,30 +33,6 @@ namespace MediaBrowser.Server.Implementations.Persistence } } - /// - /// The _app paths - /// - private readonly IApplicationPaths _appPaths; - - /// - /// Initializes a new instance of the class. - /// - /// The app paths. - /// The log manager. - /// jsonSerializer - /// or - /// appPaths - public SqliteUserDataRepository(IApplicationPaths appPaths, ILogManager logManager) - { - if (appPaths == null) - { - throw new ArgumentNullException("appPaths"); - } - - _appPaths = appPaths; - _logger = logManager.GetLogger(GetType().Name); - } - /// /// Opens the connection to the database /// @@ -63,7 +41,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "userdata_v2.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -77,7 +55,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); } /// @@ -139,7 +117,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -178,7 +156,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save user data:", e); + Logger.ErrorException("Failed to save user data:", e); if (transaction != null) { @@ -194,7 +172,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -209,7 +187,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -253,7 +231,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save user data:", e); + Logger.ErrorException("Failed to save user data:", e); if (transaction != null) { @@ -269,7 +247,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -375,45 +353,17 @@ namespace MediaBrowser.Server.Implementations.Persistence return userData; } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } + _connection.Close(); + } - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); - } + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteUserRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteUserRepository.cs index d97a55ae64..ad784ae5d6 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteUserRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteUserRepository.cs @@ -15,14 +15,17 @@ namespace MediaBrowser.Server.Implementations.Persistence /// /// Class SQLiteUserRepository /// - public class SqliteUserRepository : IUserRepository + public class SqliteUserRepository : BaseSqliteRepository, IUserRepository { - private readonly ILogger _logger; - - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - private IDbConnection _connection; private readonly IServerApplicationPaths _appPaths; + private readonly IJsonSerializer _jsonSerializer; + + public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer) : base(logManager) + { + _appPaths = appPaths; + _jsonSerializer = jsonSerializer; + } /// /// Gets the name of the repository @@ -36,32 +39,6 @@ namespace MediaBrowser.Server.Implementations.Persistence } } - /// - /// Gets the json serializer. - /// - /// The json serializer. - private readonly IJsonSerializer _jsonSerializer; - - /// - /// Initializes a new instance of the class. - /// - /// The json serializer. - /// The log manager. - /// The app paths. - /// appPaths - public SqliteUserRepository(IJsonSerializer jsonSerializer, ILogManager logManager, IServerApplicationPaths appPaths) - { - if (jsonSerializer == null) - { - throw new ArgumentNullException("jsonSerializer"); - } - - _jsonSerializer = jsonSerializer; - _appPaths = appPaths; - - _logger = logManager.GetLogger(GetType().Name); - } - /// /// Opens the connection to the database /// @@ -70,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "users.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -84,7 +61,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); } /// @@ -107,8 +84,8 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); - + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); + IDbTransaction transaction = null; try @@ -139,7 +116,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save user:", e); + Logger.ErrorException("Failed to save user:", e); if (transaction != null) { @@ -155,7 +132,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -199,7 +176,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -231,7 +208,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to delete user:", e); + Logger.ErrorException("Failed to delete user:", e); if (transaction != null) { @@ -247,49 +224,21 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } + _connection.Close(); + } - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); - } + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index c9a2d3f22c..4c25c968cf 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -392,13 +392,13 @@ namespace MediaBrowser.Server.Startup.Common UserRepository = await GetUserRepository().ConfigureAwait(false); RegisterSingleInstance(UserRepository); - DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager); + DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(LogManager, JsonSerializer, ApplicationPaths); RegisterSingleInstance(DisplayPreferencesRepository); ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(ItemRepository); - ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager); + ProviderRepository = new SqliteProviderInfoRepository(LogManager, ApplicationPaths); RegisterSingleInstance(ProviderRepository); FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false); @@ -614,7 +614,7 @@ namespace MediaBrowser.Server.Startup.Common /// Task{IUserRepository}. private async Task GetUserRepository() { - var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths); + var repo = new SqliteUserRepository(LogManager, ApplicationPaths, JsonSerializer); await repo.Initialize().ConfigureAwait(false); @@ -704,7 +704,7 @@ namespace MediaBrowser.Server.Startup.Common /// Task. private async Task ConfigureUserDataRepositories() { - var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager); + var repo = new SqliteUserDataRepository(LogManager, ApplicationPaths); await repo.Initialize().ConfigureAwait(false); From d34ddf3ebde6685f336382c0e475c49677469492 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 May 2015 19:08:02 -0400 Subject: [PATCH 08/24] adjust top left menu --- .../Photos/PhotoAlbumImageProvider.cs | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs b/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs index b55c76b8f8..f04c0bf770 100644 --- a/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs +++ b/MediaBrowser.Server.Implementations/Photos/PhotoAlbumImageProvider.cs @@ -9,19 +9,19 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Photos { - public class PhotoAlbumImageProvider : BaseDynamicImageProvider - { - public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) - : base(fileSystem, providerManager, applicationPaths, imageProcessor) - { - } + //public class PhotoAlbumImageProvider : BaseDynamicImageProvider + //{ + // public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) + // : base(fileSystem, providerManager, applicationPaths, imageProcessor) + // { + // } - protected override Task> GetItemsWithImages(IHasImages item) - { - var photoAlbum = (PhotoAlbum)item; - var items = GetFinalItems(photoAlbum.Children.ToList()); + // protected override Task> GetItemsWithImages(IHasImages item) + // { + // var photoAlbum = (PhotoAlbum)item; + // var items = GetFinalItems(photoAlbum.Children.ToList()); - return Task.FromResult(items); - } - } + // return Task.FromResult(items); + // } + //} } From a38f04b1b95aa8c80b51590bfaefbdf28819d029 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 10:35:38 -0400 Subject: [PATCH 09/24] added headroom scrolling --- MediaBrowser.Api/Images/ImageService.cs | 4 +- MediaBrowser.Api/Library/LibraryService.cs | 53 +------------------ .../Entities/Audio/Audio.cs | 38 +++---------- .../Entities/Audio/MusicAlbum.cs | 47 ---------------- MediaBrowser.Controller/Entities/BaseItem.cs | 34 +----------- .../Entities/TV/Episode.cs | 23 -------- MediaBrowser.Controller/Entities/TV/Season.cs | 44 +-------------- MediaBrowser.Controller/Entities/TV/Series.cs | 13 ----- .../Profiles/SonyBravia2010Profile.cs | 6 +++ .../Profiles/SonyBravia2011Profile.cs | 6 +++ .../Profiles/SonyBravia2012Profile.cs | 6 +++ .../Profiles/SonyBravia2013Profile.cs | 6 +++ .../MediaInfo/AudioImageProvider.cs | 2 +- .../Dto/DtoService.cs | 11 +--- .../IO/LibraryMonitor.cs | 2 +- .../Session/SessionManager.cs | 2 +- .../UserViews/DynamicImageProvider.cs | 2 +- .../Api/PackageCreator.cs | 2 + .../MediaBrowser.WebDashboard.csproj | 3 ++ 19 files changed, 47 insertions(+), 257 deletions(-) diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index 7da11a405c..639c1f54b0 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -648,10 +648,8 @@ namespace MediaBrowser.Api.Images var serverFormats = _imageProcessor.GetSupportedImageOutputFormats(); - var clientFormats = GetClientSupportedFormats(); - if (serverFormats.Contains(ImageFormat.Webp) && - clientFormats.Contains(ImageFormat.Webp)) + GetClientSupportedFormats().Contains(ImageFormat.Webp)) { return ImageFormat.Webp; } diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index f89a703406..269f4cb201 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -617,36 +617,14 @@ namespace MediaBrowser.Api.Library : (Folder)_libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id); - var originalItem = item; - while (GetThemeSongIds(item).Count == 0 && request.InheritFromParent && item.Parent != null) { item = item.Parent; } - var themeSongIds = GetThemeSongIds(item); - - if (themeSongIds.Count == 0 && request.InheritFromParent) - { - var album = originalItem as MusicAlbum; - - if (album != null) - { - var linkedItemWithThemes = album.SoundtrackIds - .Select(i => _libraryManager.GetItemById(i)) - .FirstOrDefault(i => GetThemeSongIds(i).Count > 0); - - if (linkedItemWithThemes != null) - { - themeSongIds = GetThemeSongIds(linkedItemWithThemes); - item = linkedItemWithThemes; - } - } - } - var dtoOptions = GetDtoOptions(request); - var dtos = themeSongIds.Select(_libraryManager.GetItemById) + var dtos = GetThemeSongIds(item).Select(_libraryManager.GetItemById) .OrderBy(i => i.SortName) .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)); @@ -682,41 +660,14 @@ namespace MediaBrowser.Api.Library : (Folder)_libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id); - var originalItem = item; - while (GetThemeVideoIds(item).Count == 0 && request.InheritFromParent && item.Parent != null) { item = item.Parent; } - var themeVideoIds = GetThemeVideoIds(item); - - if (themeVideoIds.Count == 0 && request.InheritFromParent) - { - var album = originalItem as MusicAlbum; - - if (album == null) - { - album = originalItem.Parents.OfType().FirstOrDefault(); - } - - if (album != null) - { - var linkedItemWithThemes = album.SoundtrackIds - .Select(i => _libraryManager.GetItemById(i)) - .FirstOrDefault(i => GetThemeVideoIds(i).Count > 0); - - if (linkedItemWithThemes != null) - { - themeVideoIds = GetThemeVideoIds(linkedItemWithThemes); - item = linkedItemWithThemes; - } - } - } - var dtoOptions = GetDtoOptions(request); - var dtos = themeVideoIds.Select(_libraryManager.GetItemById) + var dtos = GetThemeVideoIds(item).Select(_libraryManager.GetItemById) .OrderBy(i => i.SortName) .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)); diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index 100633d7ff..623329ca66 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -52,34 +52,6 @@ namespace MediaBrowser.Controller.Entities.Audio /// true if this instance has embedded image; otherwise, false. public bool HasEmbeddedImage { get; set; } - /// - /// Override this to true if class should be grouped under a container in indicies - /// The container class should be defined via IndexContainer - /// - /// true if [group in index]; otherwise, false. - [IgnoreDataMember] - public override bool GroupInIndex - { - get - { - return true; - } - } - - /// - /// Override this to return the folder that should be used to construct a container - /// for this item in an index. GroupInIndex should be true as well. - /// - /// The index container. - [IgnoreDataMember] - public override Folder IndexContainer - { - get - { - return LatestItemsIndexContainer ?? new MusicAlbum { Name = "Unknown Album" }; - } - } - [IgnoreDataMember] protected override bool SupportsOwnedItems { @@ -94,7 +66,7 @@ namespace MediaBrowser.Controller.Entities.Audio { get { - return Parents.OfType().FirstOrDefault(); + return AlbumEntity; } } @@ -148,6 +120,12 @@ namespace MediaBrowser.Controller.Entities.Audio /// The album. public string Album { get; set; } + [IgnoreDataMember] + public MusicAlbum AlbumEntity + { + get { return FindParent(); } + } + /// /// Gets the type of the media. /// @@ -177,7 +155,7 @@ namespace MediaBrowser.Controller.Entities.Audio /// System.String. protected override string CreateUserDataKey() { - var parent = FindParent(); + var parent = AlbumEntity; if (parent != null) { diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index dc3f13b01d..c060f53a69 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -2,7 +2,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Users; -using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; @@ -14,11 +13,8 @@ namespace MediaBrowser.Controller.Entities.Audio /// public class MusicAlbum : Folder, IHasAlbumArtist, IHasArtist, IHasMusicGenres, IHasLookupInfo { - public List SoundtrackIds { get; set; } - public MusicAlbum() { - SoundtrackIds = new List(); Artists = new List(); AlbumArtists = new List(); } @@ -77,49 +73,6 @@ namespace MediaBrowser.Controller.Entities.Audio return Tracks; } - /// - /// Songs will group into us so don't also include us in the index - /// - /// true if [include in index]; otherwise, false. - [IgnoreDataMember] - public override bool IncludeInIndex - { - get - { - return false; - } - } - - /// - /// Override this to true if class should be grouped under a container in indicies - /// The container class should be defined via IndexContainer - /// - /// true if [group in index]; otherwise, false. - [IgnoreDataMember] - public override bool GroupInIndex - { - get - { - return true; - } - } - - /// - /// The unknwon artist - /// - private static readonly MusicArtist UnknwonArtist = new MusicArtist { Name = "" }; - - /// - /// Override this to return the folder that should be used to construct a container - /// for this item in an index. GroupInIndex should be true as well. - /// - /// The index container. - [IgnoreDataMember] - public override Folder IndexContainer - { - get { return Parent as MusicArtist ?? UnknwonArtist; } - } - public List Artists { get; set; } /// diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 3313f45fd1..bbc3b6fd31 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -496,7 +496,7 @@ namespace MediaBrowser.Controller.Entities /// /// /// ``0. - public T FindParent() + protected T FindParent() where T : Folder { return Parents.OfType().FirstOrDefault(); @@ -906,38 +906,6 @@ namespace MediaBrowser.Controller.Entities /// The provider ids. public Dictionary ProviderIds { get; set; } - /// - /// Override this to false if class should be ignored for indexing purposes - /// - /// true if [include in index]; otherwise, false. - [IgnoreDataMember] - public virtual bool IncludeInIndex - { - get { return true; } - } - - /// - /// Override this to true if class should be grouped under a container in indicies - /// The container class should be defined via IndexContainer - /// - /// true if [group in index]; otherwise, false. - [IgnoreDataMember] - public virtual bool GroupInIndex - { - get { return false; } - } - - /// - /// Override this to return the folder that should be used to construct a container - /// for this item in an index. GroupInIndex should be true as well. - /// - /// The index container. - [IgnoreDataMember] - public virtual Folder IndexContainer - { - get { return null; } - } - [IgnoreDataMember] public virtual Folder LatestItemsIndexContainer { diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index c8408365d3..8f5b8f6cff 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -45,16 +45,6 @@ namespace MediaBrowser.Controller.Entities.TV /// The index number. public int? IndexNumberEnd { get; set; } - /// - /// We want to group into series not show individually in an index - /// - /// true if [group in index]; otherwise, false. - [IgnoreDataMember] - public override bool GroupInIndex - { - get { return true; } - } - [IgnoreDataMember] protected override bool SupportsOwnedItems { @@ -91,19 +81,6 @@ namespace MediaBrowser.Controller.Entities.TV } } - /// - /// We roll up into series - /// - /// The index container. - [IgnoreDataMember] - public override Folder IndexContainer - { - get - { - return Season; - } - } - [IgnoreDataMember] public override Folder LatestItemsIndexContainer { diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index a99b8c659a..cfd6b46e0f 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Controller.Localization; -using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Users; @@ -15,20 +14,6 @@ namespace MediaBrowser.Controller.Entities.TV /// public class Season : Folder, IHasSeries, IHasLookupInfo { - - /// - /// Seasons are just containers - /// - /// true if [include in index]; otherwise, false. - [IgnoreDataMember] - public override bool IncludeInIndex - { - get - { - return false; - } - } - [IgnoreDataMember] public override bool SupportsAddingToPlaylist { @@ -50,33 +35,6 @@ namespace MediaBrowser.Controller.Entities.TV get { return Series ?? Parent; } } - /// - /// We want to group into our Series - /// - /// true if [group in index]; otherwise, false. - [IgnoreDataMember] - public override bool GroupInIndex - { - get - { - return true; - } - } - - /// - /// Override this to return the folder that should be used to construct a container - /// for this item in an index. GroupInIndex should be true as well. - /// - /// The index container. - [IgnoreDataMember] - public override Folder IndexContainer - { - get - { - return Series; - } - } - // Genre, Rating and Stuido will all be the same protected override IEnumerable GetIndexByOptions() { diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 4696afeb62..2663d19e8f 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -94,19 +94,6 @@ namespace MediaBrowser.Controller.Entities.TV } } - /// - /// Series aren't included directly in indices - Their Episodes will roll up to them - /// - /// true if [include in index]; otherwise, false. - [IgnoreDataMember] - public override bool IncludeInIndex - { - get - { - return false; - } - } - /// /// Gets the user data key. /// diff --git a/MediaBrowser.Dlna/Profiles/SonyBravia2010Profile.cs b/MediaBrowser.Dlna/Profiles/SonyBravia2010Profile.cs index 71f8772325..78e90af26e 100644 --- a/MediaBrowser.Dlna/Profiles/SonyBravia2010Profile.cs +++ b/MediaBrowser.Dlna/Profiles/SonyBravia2010Profile.cs @@ -293,6 +293,12 @@ namespace MediaBrowser.Dlna.Profiles Condition = ProfileConditionType.LessThanEqual, Property = ProfileConditionValue.Height, Value = "1080" + }, + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + Property = ProfileConditionValue.VideoFramerate, + Value = "30" } } }, diff --git a/MediaBrowser.Dlna/Profiles/SonyBravia2011Profile.cs b/MediaBrowser.Dlna/Profiles/SonyBravia2011Profile.cs index 0b157ae336..b435c63642 100644 --- a/MediaBrowser.Dlna/Profiles/SonyBravia2011Profile.cs +++ b/MediaBrowser.Dlna/Profiles/SonyBravia2011Profile.cs @@ -310,6 +310,12 @@ namespace MediaBrowser.Dlna.Profiles Condition = ProfileConditionType.LessThanEqual, Property = ProfileConditionValue.Height, Value = "1080" + }, + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + Property = ProfileConditionValue.VideoFramerate, + Value = "30" } } }, diff --git a/MediaBrowser.Dlna/Profiles/SonyBravia2012Profile.cs b/MediaBrowser.Dlna/Profiles/SonyBravia2012Profile.cs index 0d974cbc0e..b0cbb0970d 100644 --- a/MediaBrowser.Dlna/Profiles/SonyBravia2012Profile.cs +++ b/MediaBrowser.Dlna/Profiles/SonyBravia2012Profile.cs @@ -250,6 +250,12 @@ namespace MediaBrowser.Dlna.Profiles Condition = ProfileConditionType.LessThanEqual, Property = ProfileConditionValue.Height, Value = "1080" + }, + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + Property = ProfileConditionValue.VideoFramerate, + Value = "30" } } }, diff --git a/MediaBrowser.Dlna/Profiles/SonyBravia2013Profile.cs b/MediaBrowser.Dlna/Profiles/SonyBravia2013Profile.cs index ac4cb21312..ca4e802a16 100644 --- a/MediaBrowser.Dlna/Profiles/SonyBravia2013Profile.cs +++ b/MediaBrowser.Dlna/Profiles/SonyBravia2013Profile.cs @@ -284,6 +284,12 @@ namespace MediaBrowser.Dlna.Profiles Condition = ProfileConditionType.LessThanEqual, Property = ProfileConditionValue.Height, Value = "1080" + }, + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + Property = ProfileConditionValue.VideoFramerate, + Value = "30" } } } diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs index 99be102f85..bd83862a8a 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Providers.MediaInfo private string GetAudioImagePath(Audio item) { - var album = item.Parent as MusicAlbum; + var album = item.AlbumEntity; var filename = item.Album ?? string.Empty; filename += string.Join(",", item.Artists.ToArray()); diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 402bd4d985..1b55f47d5e 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -1193,7 +1193,7 @@ namespace MediaBrowser.Server.Implementations.Dto { dto.Album = audio.Album; - var albumParent = audio.FindParent(); + var albumParent = audio.AlbumEntity; if (albumParent != null) { @@ -1208,15 +1208,6 @@ namespace MediaBrowser.Server.Implementations.Dto //} } - var album = item as MusicAlbum; - - if (album != null) - { - dto.SoundtrackIds = album.SoundtrackIds - .Select(i => i.ToString("N")) - .ToArray(); - } - var hasArtist = item as IHasArtist; if (hasArtist != null) { diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index d501d1210b..5f63a8d08a 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -84,7 +84,7 @@ namespace MediaBrowser.Server.Implementations.IO // This is an arbitraty amount of time, but delay it because file system writes often trigger events after RemoveTempIgnore has been called. // Seeing long delays in some situations, especially over the network. // Seeing delays up to 40 seconds, but not going to ignore changes for that long. - await Task.Delay(1500).ConfigureAwait(false); + await Task.Delay(5000).ConfigureAwait(false); string val; _tempIgnoredPaths.TryRemove(path, out val); diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 112778ec8a..757e6938ad 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -1550,7 +1550,7 @@ namespace MediaBrowser.Server.Implementations.Session if (info.PrimaryImageTag == null) { - var album = audio.Parents.OfType().FirstOrDefault(); + var album = audio.AlbumEntity; if (album != null && album.HasImage(ImageType.Primary)) { diff --git a/MediaBrowser.Server.Implementations/UserViews/DynamicImageProvider.cs b/MediaBrowser.Server.Implementations/UserViews/DynamicImageProvider.cs index 93a9bc8f6f..8bbc746cb3 100644 --- a/MediaBrowser.Server.Implementations/UserViews/DynamicImageProvider.cs +++ b/MediaBrowser.Server.Implementations/UserViews/DynamicImageProvider.cs @@ -122,7 +122,7 @@ namespace MediaBrowser.Server.Implementations.UserViews var audio = i as Audio; if (audio != null) { - var album = audio.FindParent(); + var album = audio.AlbumEntity; if (album != null && album.HasImage(ImageType.Primary)) { return album; diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs index 26f2f8babd..6c812acce0 100644 --- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs +++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs @@ -281,6 +281,8 @@ namespace MediaBrowser.WebDashboard.Api await AppendResource(memoryStream, "thirdparty/jstree3.0.8/jstree.js", newLineBytes).ConfigureAwait(false); + await AppendResource(memoryStream, "thirdparty/headroom.js", newLineBytes).ConfigureAwait(false); + await AppendLocalization(memoryStream, culture).ConfigureAwait(false); await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false); diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index 5c4aab1e4f..0da2d56606 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -999,6 +999,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest From 923899fcce9ff8890ebfd55718c51280ca61aa1e Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 13:44:25 -0400 Subject: [PATCH 10/24] adjust debug logging --- .../Playback/BaseStreamingService.cs | 7 +++++-- .../Playback/Dash/MpegDashService.cs | 3 ++- .../Playback/Hls/BaseHlsService.cs | 3 ++- .../Playback/Hls/DynamicHlsService.cs | 3 ++- .../Playback/Hls/VideoHlsService.cs | 3 ++- .../Playback/Progressive/AudioService.cs | 3 ++- .../BaseProgressiveStreamingService.cs | 3 ++- .../Playback/Progressive/VideoService.cs | 3 ++- MediaBrowser.Dlna/Ssdp/Datagram.cs | 19 +++++++++++++++---- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 4 +++- .../Configuration/ServerConfiguration.cs | 6 ++---- .../IO/LibraryMonitor.cs | 4 ++-- 12 files changed, 41 insertions(+), 20 deletions(-) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index ba20c0c587..34fb29b94a 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -23,6 +23,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.Serialization; namespace MediaBrowser.Api.Playback { @@ -68,12 +69,14 @@ namespace MediaBrowser.Api.Playback protected ISubtitleEncoder SubtitleEncoder { get; private set; } protected IMediaSourceManager MediaSourceManager { get; private set; } protected IZipClient ZipClient { get; private set; } + protected IJsonSerializer JsonSerializer { get; private set; } /// /// Initializes a new instance of the class. /// - protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient) + protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer) { + JsonSerializer = jsonSerializer; ZipClient = zipClient; MediaSourceManager = mediaSourceManager; DeviceManager = deviceManager; @@ -1005,7 +1008,7 @@ namespace MediaBrowser.Api.Playback // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true); - var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); + var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false); process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state); diff --git a/MediaBrowser.Api/Playback/Dash/MpegDashService.cs b/MediaBrowser.Api/Playback/Dash/MpegDashService.cs index 0692c4863e..1a90dbb531 100644 --- a/MediaBrowser.Api/Playback/Dash/MpegDashService.cs +++ b/MediaBrowser.Api/Playback/Dash/MpegDashService.cs @@ -8,6 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Net; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using ServiceStack; using System; using System.Collections.Generic; @@ -53,7 +54,7 @@ namespace MediaBrowser.Api.Playback.Dash public class MpegDashService : BaseHlsService { - public MpegDashService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient) + public MpegDashService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer) { NetworkManager = networkManager; } diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 78dee4c448..b10c02e17c 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -13,6 +13,7 @@ using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.Serialization; namespace MediaBrowser.Api.Playback.Hls { @@ -21,7 +22,7 @@ namespace MediaBrowser.Api.Playback.Hls /// public abstract class BaseHlsService : BaseStreamingService { - protected BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient) + protected BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer) { } diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 4f938dc419..1f6bc242df 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -10,6 +10,7 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using ServiceStack; using System; using System.Collections.Generic; @@ -61,7 +62,7 @@ namespace MediaBrowser.Api.Playback.Hls public class DynamicHlsService : BaseHlsService { - public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient) + public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer) { NetworkManager = networkManager; } diff --git a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs index 8e2854c5e8..626df59f25 100644 --- a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs @@ -5,6 +5,7 @@ using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using ServiceStack; using System; @@ -40,7 +41,7 @@ namespace MediaBrowser.Api.Playback.Hls /// public class VideoHlsService : BaseHlsService { - public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient) + public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer) { } diff --git a/MediaBrowser.Api/Playback/Progressive/AudioService.cs b/MediaBrowser.Api/Playback/Progressive/AudioService.cs index fee5011596..67a9cab58f 100644 --- a/MediaBrowser.Api/Playback/Progressive/AudioService.cs +++ b/MediaBrowser.Api/Playback/Progressive/AudioService.cs @@ -8,6 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using ServiceStack; using System.Collections.Generic; @@ -31,7 +32,7 @@ namespace MediaBrowser.Api.Playback.Progressive /// public class AudioService : BaseProgressiveStreamingService { - public AudioService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, imageProcessor, httpClient) + public AudioService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, imageProcessor, httpClient) { } diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index 8ed17ca17e..835f3357eb 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Net; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Serialization; using ServiceStack.Web; using System; using System.Collections.Generic; @@ -27,7 +28,7 @@ namespace MediaBrowser.Api.Playback.Progressive protected readonly IImageProcessor ImageProcessor; protected readonly IHttpClient HttpClient; - protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient) + protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer) { ImageProcessor = imageProcessor; HttpClient = httpClient; diff --git a/MediaBrowser.Api/Playback/Progressive/VideoService.cs b/MediaBrowser.Api/Playback/Progressive/VideoService.cs index 0ded108b1d..27482c50c6 100644 --- a/MediaBrowser.Api/Playback/Progressive/VideoService.cs +++ b/MediaBrowser.Api/Playback/Progressive/VideoService.cs @@ -7,6 +7,7 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using ServiceStack; using System; using System.IO; @@ -61,7 +62,7 @@ namespace MediaBrowser.Api.Playback.Progressive /// public class VideoService : BaseProgressiveStreamingService { - public VideoService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, imageProcessor, httpClient) + public VideoService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, imageProcessor, httpClient) { } diff --git a/MediaBrowser.Dlna/Ssdp/Datagram.cs b/MediaBrowser.Dlna/Ssdp/Datagram.cs index ae79ab44f1..4a0bb6f48b 100644 --- a/MediaBrowser.Dlna/Ssdp/Datagram.cs +++ b/MediaBrowser.Dlna/Ssdp/Datagram.cs @@ -12,13 +12,15 @@ namespace MediaBrowser.Dlna.Ssdp public EndPoint FromEndPoint { get; private set; } public string Message { get; private set; } public bool IgnoreBindFailure { get; private set; } + public bool EnableDebugLogging { get; private set; } private readonly ILogger _logger; - public Datagram(EndPoint toEndPoint, EndPoint fromEndPoint, ILogger logger, string message, bool ignoreBindFailure) + public Datagram(EndPoint toEndPoint, EndPoint fromEndPoint, ILogger logger, string message, bool ignoreBindFailure, bool enableDebugLogging) { Message = message; _logger = logger; + EnableDebugLogging = enableDebugLogging; IgnoreBindFailure = ignoreBindFailure; FromEndPoint = fromEndPoint; ToEndPoint = toEndPoint; @@ -37,8 +39,13 @@ namespace MediaBrowser.Dlna.Ssdp { client.Bind(FromEndPoint); } - catch + catch (Exception ex) { + if (EnableDebugLogging) + { + _logger.ErrorException("Error binding datagram socket", ex); + } + if (!IgnoreBindFailure) throw; } } @@ -51,7 +58,7 @@ namespace MediaBrowser.Dlna.Ssdp } catch (Exception ex) { - if (!IgnoreBindFailure) + if (!IgnoreBindFailure || EnableDebugLogging) { _logger.ErrorException("Error sending Datagram to {0} from {1}: " + Message, ex, ToEndPoint, FromEndPoint == null ? "" : FromEndPoint.ToString()); } @@ -62,8 +69,12 @@ namespace MediaBrowser.Dlna.Ssdp { client.Close(); } - catch (Exception) + catch (Exception ex) { + if (EnableDebugLogging) + { + _logger.ErrorException("Error closing datagram socket", ex); + } } } }, null); diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index e21074bd40..a146047098 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -166,9 +166,11 @@ namespace MediaBrowser.Dlna.Ssdp var msg = new SsdpMessageBuilder().BuildMessage(header, values); var queued = false; + var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; + for (var i = 0; i < sendCount; i++) { - var dgram = new Datagram(endpoint, localAddress, _logger, msg, ignoreBindFailure); + var dgram = new Datagram(endpoint, localAddress, _logger, msg, ignoreBindFailure, enableDebugLogging); if (_messageQueue.Count == 0) { diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 8a3a2a3e43..2833e71677 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -158,7 +158,7 @@ namespace MediaBrowser.Model.Configuration /// different directories and files. /// /// The file watcher delay. - public int RealtimeMonitorDelay { get; set; } + public int RealtimeLibraryMonitorDelay { get; set; } /// /// Gets or sets a value indicating whether [enable dashboard response caching]. @@ -233,7 +233,7 @@ namespace MediaBrowser.Model.Configuration // 5 minutes MinResumeDurationSeconds = 300; - RealtimeMonitorDelay = 30; + RealtimeLibraryMonitorDelay = 40; EnableInternetProviders = true; FindInternetTrailers = true; @@ -261,8 +261,6 @@ namespace MediaBrowser.Model.Configuration "Chromecast", "iOS", "Unknown app", - "MediaPortal", - "Media Portal", "iPad", "iPhone", "Windows Phone" diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index 5f63a8d08a..3d6a6c2f13 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -437,11 +437,11 @@ namespace MediaBrowser.Server.Implementations.IO { if (_updateTimer == null) { - _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1)); + _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); } else { - _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1)); + _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); } } } From c02ba2dab27a362ab9db83f79b482c612b56900c Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 13:46:44 -0400 Subject: [PATCH 11/24] update server signature --- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index a146047098..d60d575a64 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -67,7 +67,7 @@ namespace MediaBrowser.Dlna.Ssdp } return String.Format( - "{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 MediaBrowser/{4}", + "{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 Emby/{4}", pstring, IntPtr.Size * 8, os.Version.Major, From cc160367c82b42e1d8463b4b465b40ef74295d0d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 13:50:23 -0400 Subject: [PATCH 12/24] update RespondToSearch --- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index d60d575a64..d4cfd284a3 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -216,10 +216,7 @@ namespace MediaBrowser.Dlna.Ssdp { var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; - if (enableDebugLogging) - { - _logger.Debug("RespondToSearch"); - } + var isLogged = false; const string header = "HTTP/1.1 200 OK"; @@ -228,6 +225,15 @@ namespace MediaBrowser.Dlna.Ssdp if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) || string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase)) { + if (!isLogged) + { + if (enableDebugLogging) + { + _logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType); + } + isLogged = true; + } + var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["CACHE-CONTROL"] = "max-age = 600"; From 4bf8c8211f153f564e981dc6b667bc177b9271ac Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 13:53:45 -0400 Subject: [PATCH 13/24] update OnMessageReceived --- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index d4cfd284a3..6159b18f0f 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -88,24 +88,21 @@ namespace MediaBrowser.Dlna.Ssdp private async void OnMessageReceived(SsdpMessageEventArgs args) { - if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase)) - { - var headers = args.Headers; + var headers = args.Headers; + string st; + if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase) && headers.TryGetValue("st", out st)) + { TimeSpan delay = GetSearchDelay(headers); - + if (_config.GetDlnaConfiguration().EnableDebugLogging) { _logger.Debug("Delaying search response by {0} seconds", delay.TotalSeconds); } - + await Task.Delay(delay).ConfigureAwait(false); - string st; - if (headers.TryGetValue("st", out st)) - { - RespondToSearch(args.EndPoint, st); - } + RespondToSearch(args.EndPoint, st); } EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger); From fabb4f4c9559bbc0f6bee9b28a2cdd2e60318786 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 13:56:39 -0400 Subject: [PATCH 14/24] avoid responding to self messages --- MediaBrowser.Dlna/Ssdp/SsdpHandler.cs | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs index 6159b18f0f..28ea5ad6c9 100644 --- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs +++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs @@ -333,6 +333,11 @@ namespace MediaBrowser.Dlna.Ssdp var args = SsdpHelper.ParseSsdpResponse(received); args.EndPoint = endpoint; + if (IsSelfNotification(args)) + { + return; + } + if (enableDebugLogging) { var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)); @@ -354,6 +359,44 @@ namespace MediaBrowser.Dlna.Ssdp } } + internal bool IsSelfNotification(SsdpMessageEventArgs args) + { + // Avoid responding to self search messages + //string serverId; + //if (args.Headers.TryGetValue("X-EMBYSERVERID", out serverId) && + // string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase)) + //{ + // return true; + //} + + string server; + args.Headers.TryGetValue("SERVER", out server); + + if (string.Equals(server, _serverSignature, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + return false; + //string usn; + //args.Headers.TryGetValue("USN", out usn); + + //if (string.IsNullOrWhiteSpace(usn)) + //{ + // return false; + //} + + //_logger.Debug("IsSelfNotification test: " + usn); + + //return RegisteredDevices.Any(i => + //{ + // var isSameDevice = string.Equals(usn, i.USN, StringComparison.OrdinalIgnoreCase) || + // i.USN.IndexOf(usn, StringComparison.OrdinalIgnoreCase) != 1 || + // usn.IndexOf(i.USN, StringComparison.OrdinalIgnoreCase) != 1; + + // return isSameDevice; + //}); + } + public void Dispose() { _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated; From 50bf2de329e80a6eda07315a5a7295dd9bb47ba6 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 14:01:01 -0400 Subject: [PATCH 15/24] fire DeviceLeft on byebye --- MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs index 3dd482e647..737eb4287a 100644 --- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs +++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs @@ -203,18 +203,25 @@ namespace MediaBrowser.Dlna.Ssdp string nts; args.Headers.TryGetValue("NTS", out nts); + if (String.Equals(nts, "ssdp:byebye", StringComparison.OrdinalIgnoreCase)) + { + if (String.Equals(args.Method, "NOTIFY", StringComparison.OrdinalIgnoreCase)) + { + if (!_disposed) + { + EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger); + } + } + + return; + } + string usn; if (!args.Headers.TryGetValue("USN", out usn)) usn = string.Empty; string nt; if (!args.Headers.TryGetValue("NT", out nt)) nt = string.Empty; - // Ignore when a device is indicating it's shutting down - if (string.Equals(nts, "ssdp:byebye", StringComparison.OrdinalIgnoreCase)) - { - return; - } - // Need to be able to download device description string location; if (!args.Headers.TryGetValue("Location", out location) || From 59c13ee90235c1ba438574639e55f0afc8a35e27 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 May 2015 18:07:46 -0400 Subject: [PATCH 16/24] create dlna profiles for bubble & vlc --- MediaBrowser.Dlna/DlnaManager.cs | 4 +- MediaBrowser.Dlna/MediaBrowser.Dlna.csproj | 6 ++ MediaBrowser.Dlna/PlayTo/Device.cs | 8 +- .../Profiles/BubbleUpnpProfile.cs | 76 +++++++++++++++++++ MediaBrowser.Dlna/Profiles/VlcProfile.cs | 76 +++++++++++++++++++ MediaBrowser.Dlna/Profiles/WdtvLiveProfile.cs | 1 - MediaBrowser.Dlna/Profiles/Xml/BubbleUPnp.xml | 50 ++++++++++++ MediaBrowser.Dlna/Profiles/Xml/Default.xml | 1 - MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml | 1 - .../Profiles/Xml/DirecTV HD-DVR.xml | 1 - .../Profiles/Xml/Dish Hopper-Joey.xml | 1 - .../Profiles/Xml/Generic Device.xml | 43 +++++++++++ .../Profiles/Xml/LG Smart TV.xml | 1 - .../Profiles/Xml/Linksys DMA2100.xml | 1 - .../Profiles/Xml/MediaMonkey.xml | 1 - .../Profiles/Xml/Panasonic Viera.xml | 1 - .../Profiles/Xml/Popcorn Hour.xml | 1 - .../Profiles/Xml/Samsung Smart TV.xml | 1 - .../Profiles/Xml/Sony Blu-ray Player 2013.xml | 1 - .../Profiles/Xml/Sony Blu-ray Player.xml | 1 - .../Profiles/Xml/Sony Bravia (2010).xml | 2 +- .../Profiles/Xml/Sony Bravia (2011).xml | 2 +- .../Profiles/Xml/Sony Bravia (2012).xml | 2 +- .../Profiles/Xml/Sony Bravia (2013).xml | 2 +- .../Profiles/Xml/Sony PlayStation 3.xml | 1 - MediaBrowser.Dlna/Profiles/Xml/Vlc.xml | 50 ++++++++++++ MediaBrowser.Dlna/Profiles/Xml/WDTV Live.xml | 1 - MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml | 1 - MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml | 1 - MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml | 1 - MediaBrowser.Model/Dlna/DeviceProfile.cs | 1 - 31 files changed, 312 insertions(+), 28 deletions(-) create mode 100644 MediaBrowser.Dlna/Profiles/BubbleUpnpProfile.cs create mode 100644 MediaBrowser.Dlna/Profiles/VlcProfile.cs create mode 100644 MediaBrowser.Dlna/Profiles/Xml/BubbleUPnp.xml create mode 100644 MediaBrowser.Dlna/Profiles/Xml/Generic Device.xml create mode 100644 MediaBrowser.Dlna/Profiles/Xml/Vlc.xml diff --git a/MediaBrowser.Dlna/DlnaManager.cs b/MediaBrowser.Dlna/DlnaManager.cs index bdc8beb989..62756e4c43 100644 --- a/MediaBrowser.Dlna/DlnaManager.cs +++ b/MediaBrowser.Dlna/DlnaManager.cs @@ -544,7 +544,9 @@ namespace MediaBrowser.Dlna new DirectTvProfile(), new DishHopperJoeyProfile(), new DefaultProfile(), - new PopcornHourProfile() + new PopcornHourProfile(), + new VlcProfile(), + new BubbleUpnpProfile() }; foreach (var item in list) diff --git a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj index b4e93ed681..204872e7b6 100644 --- a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj +++ b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj @@ -77,10 +77,12 @@ + + @@ -204,6 +206,10 @@ + + + +