From 060215143ff62e4cf475a493e57c8607beca8640 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 20 Oct 2017 12:16:56 -0400 Subject: [PATCH] improve httpclient resource disposal --- .../ContentDirectoryBrowser.cs | 51 +++--- Emby.Dlna/Eventing/EventManager.cs | 5 +- Emby.Dlna/PlayTo/SsdpHttpClient.cs | 27 +-- .../HttpClientManager/HttpClientManager.cs | 62 ------- .../Library/Resolvers/TV/SeasonResolver.cs | 4 +- .../LiveTv/EmbyTV/EmbyTV.cs | 3 + .../LiveTv/Listings/SchedulesDirect.cs | 119 +++++++------ .../TunerHosts/HdHomerun/HdHomerunHost.cs | 42 +++-- .../HdHomerun/HdHomerunHttpStream.cs | 17 +- .../Localization/LocalizationManager.cs | 5 + .../News/NewsEntryPoint.cs | 13 +- .../Security/PluginSecurityManager.cs | 9 +- .../Session/HttpSessionController.cs | 9 +- .../Updates/InstallationManager.cs | 19 +- MediaBrowser.Api/Images/RemoteImageService.cs | 33 ++-- MediaBrowser.Common/Net/IHttpClient.cs | 47 ----- MediaBrowser.Common/Updates/GithubUpdater.cs | 26 +-- .../BoxSets/MovieDbBoxSetProvider.cs | 14 +- .../Manager/ProviderManager.cs | 10 +- .../Movies/FanartMovieImageProvider.cs | 11 +- .../Movies/MovieDbProvider.cs | 29 ++-- .../Movies/MovieDbSearch.cs | 94 +++++----- .../Music/AudioDbAlbumProvider.cs | 11 +- .../Music/AudioDbArtistProvider.cs | 15 +- .../Music/FanArtArtistProvider.cs | 11 +- .../Music/MusicBrainzAlbumProvider.cs | 164 ++++++++++-------- .../Music/MusicBrainzArtistProvider.cs | 28 +-- .../Omdb/OmdbItemProvider.cs | 111 ++++++------ MediaBrowser.Providers/Omdb/OmdbProvider.cs | 28 +-- .../People/MovieDbPersonProvider.cs | 24 ++- .../TV/FanArt/FanartSeriesProvider.cs | 11 +- .../TV/TheMovieDb/MovieDbProviderBase.cs | 7 +- .../TV/TheMovieDb/MovieDbSeasonProvider.cs | 7 +- .../TV/TheMovieDb/MovieDbSeriesProvider.cs | 57 +++--- .../TV/TheTVDB/TvdbPrescanTask.cs | 27 +-- .../TV/TheTVDB/TvdbSeriesProvider.cs | 115 ++++++------ 36 files changed, 664 insertions(+), 601 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryBrowser.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryBrowser.cs index 2b421794a..9c5c5fb64 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryBrowser.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryBrowser.cs @@ -43,37 +43,38 @@ namespace Emby.Dlna.ContentDirectory options.RequestContent = GetRequestBody(request); - var response = await _httpClient.SendAsync(options, "POST"); - - using (var reader = new StreamReader(response.Content)) + using (var response = await _httpClient.SendAsync(options, "POST")) { - var doc = XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); - - var queryResult = new QueryResult(); - - if (doc.Document == null) - return queryResult; - - var responseElement = doc.Document.Descendants(UNamespace + "BrowseResponse").ToList(); - - var countElement = responseElement.Select(i => i.Element("TotalMatches")).FirstOrDefault(i => i != null); - var countValue = countElement == null ? null : countElement.Value; - - int count; - if (!string.IsNullOrWhiteSpace(countValue) && int.TryParse(countValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out count)) + using (var reader = new StreamReader(response.Content)) { - queryResult.TotalRecordCount = count; + var doc = XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); - var resultElement = responseElement.Select(i => i.Element("Result")).FirstOrDefault(i => i != null); - var resultString = (string)resultElement; + var queryResult = new QueryResult(); - if (resultElement != null) + if (doc.Document == null) + return queryResult; + + var responseElement = doc.Document.Descendants(UNamespace + "BrowseResponse").ToList(); + + var countElement = responseElement.Select(i => i.Element("TotalMatches")).FirstOrDefault(i => i != null); + var countValue = countElement == null ? null : countElement.Value; + + int count; + if (!string.IsNullOrWhiteSpace(countValue) && int.TryParse(countValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out count)) { - var xElement = XElement.Parse(resultString); - } - } + queryResult.TotalRecordCount = count; - return queryResult; + var resultElement = responseElement.Select(i => i.Element("Result")).FirstOrDefault(i => i != null); + var resultString = (string)resultElement; + + if (resultElement != null) + { + var xElement = XElement.Parse(resultString); + } + } + + return queryResult; + } } } diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs index 99ba74f32..67eac640e 100644 --- a/Emby.Dlna/Eventing/EventManager.cs +++ b/Emby.Dlna/Eventing/EventManager.cs @@ -182,7 +182,10 @@ namespace Emby.Dlna.Eventing try { - await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false); + using (await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false)) + { + + } } catch (OperationCanceledException) { diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index 1aa671b8f..6c66a999c 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -31,14 +31,15 @@ namespace Emby.Dlna.PlayTo bool logRequest = true, string header = null) { - var response = await PostSoapDataAsync(NormalizeServiceUrl(baseUrl, service.ControlUrl), "\"" + service.ServiceType + "#" + command + "\"", postData, header, logRequest) - .ConfigureAwait(false); - - using (var stream = response.Content) + using (var response = await PostSoapDataAsync(NormalizeServiceUrl(baseUrl, service.ControlUrl), "\"" + service.ServiceType + "#" + command + "\"", postData, header, logRequest) + .ConfigureAwait(false)) { - using (var reader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); + using (var reader = new StreamReader(stream, Encoding.UTF8)) + { + return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); + } } } } @@ -79,7 +80,10 @@ namespace Emby.Dlna.PlayTo options.RequestHeaders["NT"] = "upnp:event"; options.RequestHeaders["TIMEOUT"] = "Second-" + timeOut.ToString(_usCulture); - await _httpClient.SendAsync(options, "SUBSCRIBE").ConfigureAwait(false); + using (await _httpClient.SendAsync(options, "SUBSCRIBE").ConfigureAwait(false)) + { + + } } public async Task GetDataAsync(string url) @@ -94,11 +98,14 @@ namespace Emby.Dlna.PlayTo options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName; - using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { - using (var reader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); + using (var reader = new StreamReader(stream, Encoding.UTF8)) + { + return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); + } } } } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index fe545ecff..3fdd05135 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -279,39 +279,9 @@ namespace Emby.Server.Implementations.HttpClientManager public async Task Get(HttpRequestOptions options) { var response = await GetResponse(options).ConfigureAwait(false); - return response.Content; } - /// - /// Performs a GET request and returns the resulting stream - /// - /// The URL. - /// The resource pool. - /// The cancellation token. - /// Task{Stream}. - public Task Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken) - { - return Get(new HttpRequestOptions - { - Url = url, - ResourcePool = resourcePool, - CancellationToken = cancellationToken, - BufferContent = resourcePool != null - }); - } - - /// - /// Gets the specified URL. - /// - /// The URL. - /// The cancellation token. - /// Task{Stream}. - public Task Get(string url, CancellationToken cancellationToken) - { - return Get(url, null, cancellationToken); - } - /// /// send as an asynchronous operation. /// @@ -589,26 +559,6 @@ namespace Emby.Server.Implementations.HttpClientManager return response.Content; } - /// - /// Performs a POST request - /// - /// The URL. - /// Params to add to the POST data. - /// The resource pool. - /// The cancellation token. - /// stream on success, null on failure - public Task Post(string url, Dictionary postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken) - { - return Post(new HttpRequestOptions - { - Url = url, - ResourcePool = resourcePool, - CancellationToken = cancellationToken, - BufferContent = resourcePool != null - - }, postData); - } - /// /// Downloads the contents of a given url into a temporary location /// @@ -891,18 +841,6 @@ namespace Emby.Server.Implementations.HttpClientManager } } - /// - /// Posts the specified URL. - /// - /// The URL. - /// The post data. - /// The cancellation token. - /// Task{Stream}. - public Task Post(string url, Dictionary postData, CancellationToken cancellationToken) - { - return Post(url, postData, null, cancellationToken); - } - private Task GetResponseAsync(WebRequest request, TimeSpan timeout) { var taskCompletion = new TaskCompletionSource(); diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index a859d8ec8..a0ff29482 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -55,10 +55,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV if (season.IndexNumber.HasValue) { var seasonNumber = season.IndexNumber.Value; - + season.Name = seasonNumber == 0 ? args.LibraryOptions.SeasonZeroDisplayName : - string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.ToString(UsCulture)); + string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.ToString(UsCulture), args.GetLibraryOptions().PreferredMetadataLanguage); } return season; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 5c32086ff..e7a360594 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1463,6 +1463,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _timerProvider.AddOrUpdate(timer, false); await SaveRecordingMetadata(timer, recordPath, seriesPath).ConfigureAwait(false); + + CreateRecordingFolders(); + TriggerRefresh(recordPath); EnforceKeepUpTo(timer, seriesPath); }; diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index b7cfdea1b..136d0cc7f 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -541,27 +541,30 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { - using (Stream responce = await Get(options, false, info).ConfigureAwait(false)) + using (var httpResponse = await Get(options, false, info).ConfigureAwait(false)) { - var root = _jsonSerializer.DeserializeFromStream>(responce); - - if (root != null) + using (Stream responce = httpResponse.Content) { - foreach (ScheduleDirect.Headends headend in root) + var root = _jsonSerializer.DeserializeFromStream>(responce); + + if (root != null) { - foreach (ScheduleDirect.Lineup lineup in headend.lineups) + foreach (ScheduleDirect.Headends headend in root) { - lineups.Add(new NameIdPair + foreach (ScheduleDirect.Lineup lineup in headend.lineups) { - Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, - Id = lineup.uri.Substring(18) - }); + lineups.Add(new NameIdPair + { + Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, + Id = lineup.uri.Substring(18) + }); + } } } - } - else - { - _logger.Info("No lineups available"); + else + { + _logger.Info("No lineups available"); + } } } } @@ -671,13 +674,13 @@ namespace Emby.Server.Implementations.LiveTv.Listings return await Post(options, false, providerInfo).ConfigureAwait(false); } - private async Task Get(HttpRequestOptions options, + private async Task Get(HttpRequestOptions options, bool enableRetry, ListingsProviderInfo providerInfo) { try { - return await _httpClient.Get(options).ConfigureAwait(false); + return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false); } catch (HttpException ex) { @@ -797,11 +800,14 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { - using (var response = await Get(options, false, null).ConfigureAwait(false)) + using (var httpResponse = await Get(options, false, null).ConfigureAwait(false)) { - var root = _jsonSerializer.DeserializeFromStream(response); + using (var response = httpResponse.Content) + { + var root = _jsonSerializer.DeserializeFromStream(response); - return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); + return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); + } } } catch (HttpException ex) @@ -879,53 +885,56 @@ namespace Emby.Server.Implementations.LiveTv.Listings var list = new List(); - using (var response = await Get(httpOptions, true, info).ConfigureAwait(false)) + using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false)) { - var root = _jsonSerializer.DeserializeFromStream(response); - _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); - _logger.Info("Mapping Stations to Channel"); - - var allStations = root.stations ?? new List(); - - foreach (ScheduleDirect.Map map in root.map) + using (var response = httpResponse.Content) { - var channelNumber = GetChannelNumber(map); + var root = _jsonSerializer.DeserializeFromStream(response); + _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); + _logger.Info("Mapping Stations to Channel"); - var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); - if (station == null) + var allStations = root.stations ?? new List(); + + foreach (ScheduleDirect.Map map in root.map) { - station = new ScheduleDirect.Station + var channelNumber = GetChannelNumber(map); + + var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); + if (station == null) { - stationID = map.stationID + station = new ScheduleDirect.Station + { + stationID = map.stationID + }; + } + + var name = channelNumber; + + var channelInfo = new ChannelInfo + { + Number = channelNumber, + Name = name }; - } - var name = channelNumber; - - var channelInfo = new ChannelInfo - { - Number = channelNumber, - Name = name - }; - - if (station != null) - { - if (!string.IsNullOrWhiteSpace(station.name)) + if (station != null) { - channelInfo.Name = station.name; + if (!string.IsNullOrWhiteSpace(station.name)) + { + channelInfo.Name = station.name; + } + + channelInfo.Id = station.stationID; + channelInfo.CallSign = station.callsign; + + if (station.logo != null) + { + channelInfo.ImageUrl = station.logo.URL; + channelInfo.HasImage = true; + } } - channelInfo.Id = station.stationID; - channelInfo.CallSign = station.callsign; - - if (station.logo != null) - { - channelInfo.ImageUrl = station.logo.URL; - channelInfo.HasImage = true; - } + list.Add(channelInfo); } - - list.Add(channelInfo); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index cfdaaed10..f8bb766d2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -86,16 +86,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun CancellationToken = cancellationToken, BufferContent = false }; - using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { - var lineup = JsonSerializer.DeserializeFromStream>(stream) ?? new List(); - - if (info.ImportFavoritesOnly) + using (var stream = response.Content) { - lineup = lineup.Where(i => i.Favorite).ToList(); - } + var lineup = JsonSerializer.DeserializeFromStream>(stream) ?? new List(); - return lineup.Where(i => !i.DRM).ToList(); + if (info.ImportFavoritesOnly) + { + lineup = lineup.Where(i => i.Favorite).ToList(); + } + + return lineup.Where(i => !i.DRM).ToList(); + } } } @@ -143,26 +146,29 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun try { - using (var stream = await _httpClient.Get(new HttpRequestOptions() + using (var response = await _httpClient.SendAsync(new HttpRequestOptions() { Url = string.Format("{0}/discover.json", GetApiUrl(info, false)), CancellationToken = cancellationToken, TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds), BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - var response = JsonSerializer.DeserializeFromStream(stream); - - if (!string.IsNullOrWhiteSpace(info.Id)) + using (var stream = response.Content) { - lock (_modelCache) - { - _modelCache[info.Id] = response; - } - } + var discoverResponse = JsonSerializer.DeserializeFromStream(stream); - return response; + if (!string.IsNullOrWhiteSpace(info.Id)) + { + lock (_modelCache) + { + _modelCache[info.Id] = discoverResponse; + } + } + + return discoverResponse; + } } } catch (HttpException ex) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs index ad9c0d894..f3d89c6cc 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs @@ -92,14 +92,17 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun }, "GET").ConfigureAwait(false)) { - Logger.Info("Opened HDHR stream from {0}", url); - - Logger.Info("Beginning multicastStream.CopyUntilCancelled"); - - FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); - using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) + using (var stream = response.Content) { - StreamHelper.CopyTo(response.Content, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken); + Logger.Info("Opened HDHR stream from {0}", url); + + Logger.Info("Beginning multicastStream.CopyUntilCancelled"); + + FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); + using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) + { + StreamHelper.CopyTo(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken); + } } } } diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index b0cee12be..48df96289 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -315,6 +315,11 @@ namespace Emby.Server.Implementations.Localization public string GetLocalizedString(string phrase, string culture) { + if (string.IsNullOrWhiteSpace(culture)) + { + culture = _configurationManager.Configuration.UICulture; + } + var dictionary = GetLocalizationDictionary(culture); string value; diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs index 03c79c2c1..74366233c 100644 --- a/Emby.Server.Implementations/News/NewsEntryPoint.cs +++ b/Emby.Server.Implementations/News/NewsEntryPoint.cs @@ -88,15 +88,18 @@ namespace Emby.Server.Implementations.News BufferContent = false }; - using (var stream = await _httpClient.Get(requestOptions).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(requestOptions, "GET").ConfigureAwait(false)) { - using (var reader = XmlReader.Create(stream)) + using (var stream = response.Content) { - var news = ParseRssItems(reader).ToList(); + using (var reader = XmlReader.Create(stream)) + { + var news = ParseRssItems(reader).ToList(); - _json.SerializeToFile(news, path); + _json.SerializeToFile(news, path); - await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false); + await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false); + } } } } diff --git a/Emby.Server.Implementations/Security/PluginSecurityManager.cs b/Emby.Server.Implementations/Security/PluginSecurityManager.cs index d42fae3ad..615ffa1f4 100644 --- a/Emby.Server.Implementations/Security/PluginSecurityManager.cs +++ b/Emby.Server.Implementations/Security/PluginSecurityManager.cs @@ -293,10 +293,13 @@ namespace Emby.Server.Implementations.Security options.SetPostData(data); - using (var json = (await _httpClient.Post(options).ConfigureAwait(false)).Content) + using (var response = (await _httpClient.Post(options).ConfigureAwait(false))) { - reg = _jsonSerializer.DeserializeFromStream(json); - success = true; + using (var json = response.Content) + { + reg = _jsonSerializer.DeserializeFromStream(json); + success = true; + } } if (reg.registered) diff --git a/Emby.Server.Implementations/Session/HttpSessionController.cs b/Emby.Server.Implementations/Session/HttpSessionController.cs index bd53da1bd..940c821e2 100644 --- a/Emby.Server.Implementations/Session/HttpSessionController.cs +++ b/Emby.Server.Implementations/Session/HttpSessionController.cs @@ -66,19 +66,22 @@ namespace Emby.Server.Implementations.Session return SendMessage(name, new Dictionary(), cancellationToken); } - private Task SendMessage(string name, + private async Task SendMessage(string name, Dictionary args, CancellationToken cancellationToken) { var url = PostUrl + "/" + name + ToQueryString(args); - return _httpClient.Post(new HttpRequestOptions + using ((await _httpClient.Post(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = false - }); + }).ConfigureAwait(false))) + { + + } } public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 772f2338a..51acfee88 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -175,13 +175,24 @@ namespace Emby.Server.Implementations.Updates { "systemid", _applicationHost.SystemId } }; - using (var json = await _httpClient.Post("https://www.mb3admin.com/admin/service/package/retrieveall?includeAllRuntimes=true", data, cancellationToken).ConfigureAwait(false)) + var options = new HttpRequestOptions { - cancellationToken.ThrowIfCancellationRequested(); + Url = "https://www.mb3admin.com/admin/service/package/retrieveall?includeAllRuntimes=true", + CancellationToken = cancellationToken + }; - var packages = _jsonSerializer.DeserializeFromStream(json); + options.SetPostData(data); - return FilterPackages(packages, packageType, applicationVersion); + using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)) + { + using (var json = response.Content) + { + cancellationToken.ThrowIfCancellationRequested(); + + var packages = _jsonSerializer.DeserializeFromStream(json); + + return FilterPackages(packages, packageType, applicationVersion); + } } } else diff --git a/MediaBrowser.Api/Images/RemoteImageService.cs b/MediaBrowser.Api/Images/RemoteImageService.cs index 413762a5c..4782d76df 100644 --- a/MediaBrowser.Api/Images/RemoteImageService.cs +++ b/MediaBrowser.Api/Images/RemoteImageService.cs @@ -262,28 +262,29 @@ namespace MediaBrowser.Api.Images /// Task. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath) { - var result = await _httpClient.GetResponse(new HttpRequestOptions + using (var result = await _httpClient.GetResponse(new HttpRequestOptions { Url = url, BufferContent = false - }).ConfigureAwait(false); - - var ext = result.ContentType.Split('/').Last(); - - var fullCachePath = GetFullCachePath(urlHash + "." + ext); - - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullCachePath)); - using (var stream = result.Content) + }).ConfigureAwait(false)) { - using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) - { - await stream.CopyToAsync(filestream).ConfigureAwait(false); - } - } + var ext = result.ContentType.Split('/').Last(); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(pointerCachePath)); - _fileSystem.WriteAllText(pointerCachePath, fullCachePath); + var fullCachePath = GetFullCachePath(urlHash + "." + ext); + + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullCachePath)); + using (var stream = result.Content) + { + using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await stream.CopyToAsync(filestream).ConfigureAwait(false); + } + } + + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(pointerCachePath)); + _fileSystem.WriteAllText(pointerCachePath, fullCachePath); + } } /// diff --git a/MediaBrowser.Common/Net/IHttpClient.cs b/MediaBrowser.Common/Net/IHttpClient.cs index 15257715f..cf5511965 100644 --- a/MediaBrowser.Common/Net/IHttpClient.cs +++ b/MediaBrowser.Common/Net/IHttpClient.cs @@ -18,24 +18,6 @@ namespace MediaBrowser.Common.Net /// Task{HttpResponseInfo}. Task GetResponse(HttpRequestOptions options); - /// - /// Performs a GET request and returns the resulting stream - /// - /// The URL. - /// The resource pool. - /// The cancellation token. - /// Task{Stream}. - /// - Task Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken); - - /// - /// Gets the specified URL. - /// - /// The URL. - /// The cancellation token. - /// Task{Stream}. - Task Get(string url, CancellationToken cancellationToken); - /// /// Gets the specified options. /// @@ -51,35 +33,6 @@ namespace MediaBrowser.Common.Net /// Task{HttpResponseInfo}. Task SendAsync(HttpRequestOptions options, string httpMethod); - /// - /// Performs a POST request - /// - /// The URL. - /// Params to add to the POST data. - /// The resource pool. - /// The cancellation token. - /// stream on success, null on failure - /// postData - /// - Task Post(string url, Dictionary postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken); - - /// - /// Posts the specified URL. - /// - /// The URL. - /// The post data. - /// The cancellation token. - /// Task{Stream}. - Task Post(string url, Dictionary postData, CancellationToken cancellationToken); - - /// - /// Posts the specified options with post data - /// - /// The options - /// The post data - /// Task{Stream} - Task Post(HttpRequestOptions options, Dictionary postData); - /// /// Posts the specified options. /// diff --git a/MediaBrowser.Common/Updates/GithubUpdater.cs b/MediaBrowser.Common/Updates/GithubUpdater.cs index 2106ac6d5..30abdc5da 100644 --- a/MediaBrowser.Common/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common/Updates/GithubUpdater.cs @@ -40,11 +40,14 @@ namespace MediaBrowser.Common.Updates options.CacheLength = cacheLength; } - using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { - var obj = _jsonSerializer.DeserializeFromStream(stream); + using (var stream = response.Content) + { + var obj = _jsonSerializer.DeserializeFromStream(stream); - return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); + return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); + } } } @@ -110,17 +113,20 @@ namespace MediaBrowser.Common.Updates BufferContent = false }; - using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { - var obj = _jsonSerializer.DeserializeFromStream(stream); + using (var stream = response.Content) + { + var obj = _jsonSerializer.DeserializeFromStream(stream); - obj = obj.Where(i => (i.assets ?? new List()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray(); + obj = obj.Where(i => (i.assets ?? new List()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray(); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1)); - return list; + return list; + } } } diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs index e271772cc..17b0646ed 100644 --- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs +++ b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs @@ -179,7 +179,7 @@ namespace MediaBrowser.Providers.BoxSets RootObject mainResult = null; - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -187,7 +187,10 @@ namespace MediaBrowser.Providers.BoxSets }).ConfigureAwait(false)) { - mainResult = _json.DeserializeFromStream(json); + using (var json = response.Content) + { + mainResult = _json.DeserializeFromStream(json); + } } cancellationToken.ThrowIfCancellationRequested(); @@ -204,7 +207,7 @@ namespace MediaBrowser.Providers.BoxSets url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language); } - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -212,7 +215,10 @@ namespace MediaBrowser.Providers.BoxSets }).ConfigureAwait(false)) { - mainResult = _json.DeserializeFromStream(json); + using (var json = response.Content) + { + mainResult = _json.DeserializeFromStream(json); + } } } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 28367662b..9dd5052da 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -153,16 +153,16 @@ namespace MediaBrowser.Providers.Manager public async Task SaveImage(IHasMetadata item, string url, ImageType type, int? imageIndex, CancellationToken cancellationToken) { - var response = await _httpClient.GetResponse(new HttpRequestOptions + using (var response = await _httpClient.GetResponse(new HttpRequestOptions { CancellationToken = cancellationToken, Url = url, BufferContent = false - }).ConfigureAwait(false); - - await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken) - .ConfigureAwait(false); + }).ConfigureAwait(false)) + { + await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken).ConfigureAwait(false); + } } public Task SaveImage(IHasMetadata item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken) diff --git a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs b/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs index 0214788ab..545c3baba 100644 --- a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs +++ b/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs @@ -274,17 +274,20 @@ namespace MediaBrowser.Providers.Movies try { - using (var response = await _httpClient.Get(new HttpRequestOptions + using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = true - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var response = httpResponse.Content) { - await response.CopyToAsync(fileStream).ConfigureAwait(false); + using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await response.CopyToAsync(fileStream).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index 0a6067694..06adbffd7 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -146,7 +146,7 @@ namespace MediaBrowser.Providers.Movies return _tmdbSettings; } - using (var json = await GetMovieDbResponse(new HttpRequestOptions + using (var response = await GetMovieDbResponse(new HttpRequestOptions { Url = string.Format(TmdbConfigUrl, ApiKey), CancellationToken = cancellationToken, @@ -154,9 +154,12 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - _tmdbSettings = _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + _tmdbSettings = _jsonSerializer.DeserializeFromStream(json); - return _tmdbSettings; + return _tmdbSettings; + } } } @@ -339,7 +342,7 @@ namespace MediaBrowser.Providers.Movies try { - using (var json = await GetMovieDbResponse(new HttpRequestOptions + using (var response = await GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -349,7 +352,10 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - mainResult = _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + mainResult = _jsonSerializer.DeserializeFromStream(json); + } } } catch (HttpException ex) @@ -381,7 +387,7 @@ namespace MediaBrowser.Providers.Movies url += "&include_image_language=" + GetImageLanguagesParam(language); } - using (var json = await GetMovieDbResponse(new HttpRequestOptions + using (var response = await GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -391,9 +397,12 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - var englishResult = _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + var englishResult = _jsonSerializer.DeserializeFromStream(json); - mainResult.overview = englishResult.overview; + mainResult.overview = englishResult.overview; + } } } @@ -407,7 +416,7 @@ namespace MediaBrowser.Providers.Movies /// /// Gets the movie db response. /// - internal async Task GetMovieDbResponse(HttpRequestOptions options) + internal async Task GetMovieDbResponse(HttpRequestOptions options) { var delayTicks = (requestIntervalMs * 10000) - (DateTime.UtcNow.Ticks - _lastRequestTicks); var delayMs = Math.Min(delayTicks / 10000, requestIntervalMs); @@ -423,7 +432,7 @@ namespace MediaBrowser.Providers.Movies options.BufferContent = true; options.UserAgent = "Emby/" + _appHost.ApplicationVersion; - return await _httpClient.Get(options).ConfigureAwait(false); + return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false); } /// diff --git a/MediaBrowser.Providers/Movies/MovieDbSearch.cs b/MediaBrowser.Providers/Movies/MovieDbSearch.cs index 595c0249f..673af5534 100644 --- a/MediaBrowser.Providers/Movies/MovieDbSearch.cs +++ b/MediaBrowser.Providers/Movies/MovieDbSearch.cs @@ -154,7 +154,7 @@ namespace MediaBrowser.Providers.Movies var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, type); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url3, CancellationToken = cancellationToken, @@ -162,38 +162,41 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - var searchResults = _json.DeserializeFromStream(json); + using (var json = response.Content) + { + var searchResults = _json.DeserializeFromStream(json); - var results = searchResults.results ?? new List(); + var results = searchResults.results ?? new List(); - return results - .Select(i => - { - var remoteResult = new RemoteSearchResult + return results + .Select(i => { - SearchProviderName = MovieDbProvider.Current.Name, - Name = i.title ?? i.name ?? i.original_title, - ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path - }; + var remoteResult = new RemoteSearchResult + { + SearchProviderName = MovieDbProvider.Current.Name, + Name = i.title ?? i.name ?? i.original_title, + ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path + }; - if (!string.IsNullOrWhiteSpace(i.release_date)) - { - DateTime r; + if (!string.IsNullOrWhiteSpace(i.release_date)) + { + DateTime r; // These dates are always in this exact format if (DateTime.TryParseExact(i.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r)) - { - remoteResult.PremiereDate = r.ToUniversalTime(); - remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year; + { + remoteResult.PremiereDate = r.ToUniversalTime(); + remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year; + } } - } - remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs)); + remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs)); - return remoteResult; + return remoteResult; - }) - .ToList(); + }) + .ToList(); + } } } @@ -206,7 +209,7 @@ namespace MediaBrowser.Providers.Movies var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, "tv"); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url3, CancellationToken = cancellationToken, @@ -214,38 +217,41 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - var searchResults = _json.DeserializeFromStream(json); + using (var json = response.Content) + { + var searchResults = _json.DeserializeFromStream(json); - var results = searchResults.results ?? new List(); + var results = searchResults.results ?? new List(); - return results - .Select(i => - { - var remoteResult = new RemoteSearchResult + return results + .Select(i => { - SearchProviderName = MovieDbProvider.Current.Name, - Name = i.name ?? i.original_name, - ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path - }; + var remoteResult = new RemoteSearchResult + { + SearchProviderName = MovieDbProvider.Current.Name, + Name = i.name ?? i.original_name, + ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path + }; - if (!string.IsNullOrWhiteSpace(i.first_air_date)) - { - DateTime r; + if (!string.IsNullOrWhiteSpace(i.first_air_date)) + { + DateTime r; // These dates are always in this exact format if (DateTime.TryParseExact(i.first_air_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r)) - { - remoteResult.PremiereDate = r.ToUniversalTime(); - remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year; + { + remoteResult.PremiereDate = r.ToUniversalTime(); + remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year; + } } - } - remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs)); + remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs)); - return remoteResult; + return remoteResult; - }) - .ToList(); + }) + .ToList(); + } } } diff --git a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs b/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs index 80f122402..1082685a8 100644 --- a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs @@ -161,16 +161,19 @@ namespace MediaBrowser.Providers.Music _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - using (var response = await _httpClient.Get(new HttpRequestOptions + using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var response = httpResponse.Content) { - await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); + using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs b/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs index d8a7dbc04..66d688959 100644 --- a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs +++ b/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs @@ -147,19 +147,22 @@ namespace MediaBrowser.Providers.Music var path = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId); - using (var response = await _httpClient.Get(new HttpRequestOptions + using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = true - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - - using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var response = httpResponse.Content) { - await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); + + using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/Music/FanArtArtistProvider.cs b/MediaBrowser.Providers/Music/FanArtArtistProvider.cs index 6094fd26e..c06ee9d73 100644 --- a/MediaBrowser.Providers/Music/FanArtArtistProvider.cs +++ b/MediaBrowser.Providers/Music/FanArtArtistProvider.cs @@ -251,17 +251,20 @@ namespace MediaBrowser.Providers.Music try { - using (var response = await _httpClient.Get(new HttpRequestOptions + using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = true - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var response = httpResponse.Content) { - await response.CopyToAsync(saveFileStream).ConfigureAwait(false); + using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await response.CopyToAsync(saveFileStream).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs index a35fd696a..b54d14935 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs @@ -83,9 +83,12 @@ namespace MediaBrowser.Providers.Music if (!string.IsNullOrWhiteSpace(url)) { - using (var stream = await GetMusicBrainzResponse(url, isNameSearch, forceMusicBrainzProper, cancellationToken).ConfigureAwait(false)) + using (var response = await GetMusicBrainzResponse(url, isNameSearch, forceMusicBrainzProper, cancellationToken).ConfigureAwait(false)) { - return GetResultsFromResponse(stream); + using (var stream = response.Content) + { + return GetResultsFromResponse(stream); + } } } @@ -226,19 +229,22 @@ namespace MediaBrowser.Providers.Music WebUtility.UrlEncode(albumName), artistId); - using (var stream = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) + using (var response = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - var settings = _xmlSettings.Create(false); - - settings.CheckCharacters = false; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreComments = true; - - using (var reader = XmlReader.Create(oReader, settings)) + using (var oReader = new StreamReader(stream, Encoding.UTF8)) { - return ReleaseResult.Parse(reader).FirstOrDefault(); + var settings = _xmlSettings.Create(false); + + settings.CheckCharacters = false; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreComments = true; + + using (var reader = XmlReader.Create(oReader, settings)) + { + return ReleaseResult.Parse(reader).FirstOrDefault(); + } } } } @@ -250,19 +256,22 @@ namespace MediaBrowser.Providers.Music WebUtility.UrlEncode(albumName), WebUtility.UrlEncode(artistName)); - using (var stream = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) + using (var response = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - var settings = _xmlSettings.Create(false); - - settings.CheckCharacters = false; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreComments = true; - - using (var reader = XmlReader.Create(oReader, settings)) + using (var oReader = new StreamReader(stream, Encoding.UTF8)) { - return ReleaseResult.Parse(reader).FirstOrDefault(); + var settings = _xmlSettings.Create(false); + + settings.CheckCharacters = false; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreComments = true; + + using (var reader = XmlReader.Create(oReader, settings)) + { + return ReleaseResult.Parse(reader).FirstOrDefault(); + } } } } @@ -431,23 +440,26 @@ namespace MediaBrowser.Providers.Music { var url = string.Format("/ws/2/release?release-group={0}", releaseGroupId); - using (var stream = await GetMusicBrainzResponse(url, true, true, cancellationToken).ConfigureAwait(false)) + using (var response = await GetMusicBrainzResponse(url, true, true, cancellationToken).ConfigureAwait(false)) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - var settings = _xmlSettings.Create(false); - - settings.CheckCharacters = false; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreComments = true; - - using (var reader = XmlReader.Create(oReader, settings)) + using (var oReader = new StreamReader(stream, Encoding.UTF8)) { - var result = ReleaseResult.Parse(reader).FirstOrDefault(); + var settings = _xmlSettings.Create(false); - if (result != null) + settings.CheckCharacters = false; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreComments = true; + + using (var reader = XmlReader.Create(oReader, settings)) { - return result.ReleaseId; + var result = ReleaseResult.Parse(reader).FirstOrDefault(); + + if (result != null) + { + return result.ReleaseId; + } } } } @@ -466,53 +478,56 @@ namespace MediaBrowser.Providers.Music { var url = string.Format("/ws/2/release-group/?query=reid:{0}", releaseEntryId); - using (var stream = await GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false)) + using (var response = await GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false)) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - var settings = _xmlSettings.Create(false); - - settings.CheckCharacters = false; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreComments = true; - - using (var reader = XmlReader.Create(oReader, settings)) + using (var oReader = new StreamReader(stream, Encoding.UTF8)) { - reader.MoveToContent(); - reader.Read(); + var settings = _xmlSettings.Create(false); - // Loop through each element - while (!reader.EOF && reader.ReadState == ReadState.Interactive) + settings.CheckCharacters = false; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreComments = true; + + using (var reader = XmlReader.Create(oReader, settings)) { - if (reader.NodeType == XmlNodeType.Element) + reader.MoveToContent(); + reader.Read(); + + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) { - switch (reader.Name) + if (reader.NodeType == XmlNodeType.Element) { - case "release-group-list": - { - if (reader.IsEmptyElement) + switch (reader.Name) + { + case "release-group-list": { - reader.Read(); - continue; + if (reader.IsEmptyElement) + { + reader.Read(); + continue; + } + using (var subReader = reader.ReadSubtree()) + { + return GetFirstReleaseGroupId(subReader); + } } - using (var subReader = reader.ReadSubtree()) + default: { - return GetFirstReleaseGroupId(subReader); + reader.Skip(); + break; } - } - default: - { - reader.Skip(); - break; - } + } + } + else + { + reader.Read(); } } - else - { - reader.Read(); - } + return null; } - return null; } } } @@ -598,11 +613,14 @@ namespace MediaBrowser.Providers.Music UserAgent = _appHost.Name + "/" + _appHost.ApplicationVersion }; - using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { - var results = _json.DeserializeFromStream>(stream); + using (var stream = response.Content) + { + var results = _json.DeserializeFromStream>(stream); - list = results; + list = results; + } } _lastMbzUrlQueryTicks = DateTime.UtcNow.Ticks; } @@ -626,7 +644,7 @@ namespace MediaBrowser.Providers.Music return list; } - internal Task GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken) + internal Task GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken) { return GetMusicBrainzResponse(url, isSearch, false, cancellationToken); } @@ -634,7 +652,7 @@ namespace MediaBrowser.Providers.Music /// /// Gets the music brainz response. /// - internal async Task GetMusicBrainzResponse(string url, bool isSearch, bool forceMusicBrainzProper, CancellationToken cancellationToken) + internal async Task GetMusicBrainzResponse(string url, bool isSearch, bool forceMusicBrainzProper, CancellationToken cancellationToken) { var urlInfo = await GetMbzUrl(forceMusicBrainzProper).ConfigureAwait(false); var throttleMs = urlInfo.throttleMs; @@ -656,7 +674,7 @@ namespace MediaBrowser.Providers.Music BufferContent = throttleMs > 0 }; - return await _httpClient.Get(options).ConfigureAwait(false); + return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false); } public int Order diff --git a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs index 06f60c8a3..f514791a7 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs @@ -35,10 +35,12 @@ namespace MediaBrowser.Providers.Music { var url = string.Format("/ws/2/artist/?query=arid:{0}", musicBrainzId); - using (var stream = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, false, cancellationToken) - .ConfigureAwait(false)) + using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false)) { - return GetResultsFromResponse(stream); + using (var stream = response.Content) + { + return GetResultsFromResponse(stream); + } } } else @@ -48,13 +50,16 @@ namespace MediaBrowser.Providers.Music var url = String.Format("/ws/2/artist/?query=artist:\"{0}\"", UrlEncode(nameToSearch)); - using (var stream = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) + using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) { - var results = GetResultsFromResponse(stream); - - if (results.Count > 0) + using (var stream = response.Content) { - return results; + var results = GetResultsFromResponse(stream); + + if (results.Count > 0) + { + return results; + } } } @@ -63,9 +68,12 @@ namespace MediaBrowser.Providers.Music // Try again using the search with accent characters url url = String.Format("/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch)); - using (var stream = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) + using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false)) { - return GetResultsFromResponse(stream); + using (var stream = response.Content) + { + return GetResultsFromResponse(stream); + } } } } diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs index bab1374c2..c1b98dfbf 100644 --- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs @@ -126,65 +126,68 @@ namespace MediaBrowser.Providers.Omdb var url = OmdbProvider.GetOmdbUrl(urlQuery, cancellationToken); - using (var stream = await OmdbProvider.GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) + using (var response = await OmdbProvider.GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) { - var resultList = new List(); - - if (isSearch) + using (var stream = response.Content) { - var searchResultList = _jsonSerializer.DeserializeFromStream(stream); - if (searchResultList != null && searchResultList.Search != null) + var resultList = new List(); + + if (isSearch) { - resultList.AddRange(searchResultList.Search); + var searchResultList = _jsonSerializer.DeserializeFromStream(stream); + if (searchResultList != null && searchResultList.Search != null) + { + resultList.AddRange(searchResultList.Search); + } } + else + { + var result = _jsonSerializer.DeserializeFromStream(stream); + if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase)) + { + resultList.Add(result); + } + } + + return resultList.Select(result => + { + var item = new RemoteSearchResult + { + IndexNumber = searchInfo.IndexNumber, + Name = result.Title, + ParentIndexNumber = searchInfo.ParentIndexNumber, + SearchProviderName = Name + }; + + if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue) + { + item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value; + } + + item.SetProviderId(MetadataProviders.Imdb, result.imdbID); + + int parsedYear; + if (result.Year.Length > 0 + && int.TryParse(result.Year.Substring(0, Math.Min(result.Year.Length, 4)), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedYear)) + { + item.ProductionYear = parsedYear; + } + + DateTime released; + if (!string.IsNullOrEmpty(result.Released) + && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out released)) + { + item.PremiereDate = released; + } + + if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase)) + { + item.ImageUrl = result.Poster; + } + + return item; + }); } - else - { - var result = _jsonSerializer.DeserializeFromStream(stream); - if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase)) - { - resultList.Add(result); - } - } - - return resultList.Select(result => - { - var item = new RemoteSearchResult - { - IndexNumber = searchInfo.IndexNumber, - Name = result.Title, - ParentIndexNumber = searchInfo.ParentIndexNumber, - SearchProviderName = Name - }; - - if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue) - { - item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value; - } - - item.SetProviderId(MetadataProviders.Imdb, result.imdbID); - - int parsedYear; - if (result.Year.Length > 0 - && int.TryParse(result.Year.Substring(0, Math.Min(result.Year.Length, 4)), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedYear)) - { - item.ProductionYear = parsedYear; - } - - DateTime released; - if (!string.IsNullOrEmpty(result.Released) - && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out released)) - { - item.PremiereDate = released; - } - - if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase)) - { - item.ImageUrl = result.Poster; - } - - return item; - }); } } diff --git a/MediaBrowser.Providers/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Omdb/OmdbProvider.cs index c481bf0e9..2cac44944 100644 --- a/MediaBrowser.Providers/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbProvider.cs @@ -301,11 +301,14 @@ namespace MediaBrowser.Providers.Omdb var url = GetOmdbUrl(string.Format("i={0}&plot=short&tomatoes=true&r=json", imdbParam), cancellationToken); - using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) + using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) { - var rootObject = _jsonSerializer.DeserializeFromStream(stream); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(rootObject, path); + using (var stream = response.Content) + { + var rootObject = _jsonSerializer.DeserializeFromStream(stream); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); + _jsonSerializer.SerializeToFile(rootObject, path); + } } return path; @@ -335,25 +338,28 @@ namespace MediaBrowser.Providers.Omdb var url = GetOmdbUrl(string.Format("i={0}&season={1}&detail=full", imdbParam, seasonId), cancellationToken); - using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) + using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false)) { - var rootObject = _jsonSerializer.DeserializeFromStream(stream); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(rootObject, path); + using (var stream = response.Content) + { + var rootObject = _jsonSerializer.DeserializeFromStream(stream); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); + _jsonSerializer.SerializeToFile(rootObject, path); + } } return path; } - public static Task GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken) + public static Task GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken) { - return httpClient.Get(new HttpRequestOptions + return httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = true, EnableDefaultUserAgent = true - }); + }, "GET"); } internal string GetDataFilePath(string imdbId) diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs index 9aeaa8d1f..c921df61c 100644 --- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs +++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs @@ -91,7 +91,7 @@ namespace MediaBrowser.Providers.People var url = string.Format(@"https://api.themoviedb.org/3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), MovieDbProvider.ApiKey); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -99,10 +99,13 @@ namespace MediaBrowser.Providers.People }).ConfigureAwait(false)) { - var result = _jsonSerializer.DeserializeFromStream(json) ?? - new PersonSearchResults(); + using (var json = response.Content) + { + var result = _jsonSerializer.DeserializeFromStream(json) ?? + new PersonSearchResults(); - return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl)); + return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl)); + } } } @@ -223,7 +226,7 @@ namespace MediaBrowser.Providers.People var url = string.Format(@"https://api.themoviedb.org/3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", MovieDbProvider.ApiKey, id); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -231,11 +234,14 @@ namespace MediaBrowser.Providers.People }).ConfigureAwait(false)) { - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath)); - - using (var fs = _fileSystem.GetFileStream(dataFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var json = response.Content) { - await json.CopyToAsync(fs).ConfigureAwait(false); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath)); + + using (var fs = _fileSystem.GetFileStream(dataFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await json.CopyToAsync(fs).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs b/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs index 583e5900d..33bf1a7c2 100644 --- a/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs @@ -316,17 +316,20 @@ namespace MediaBrowser.Providers.TV try { - using (var response = await _httpClient.Get(new HttpRequestOptions + using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = true - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var response = httpResponse.Content) { - await response.CopyToAsync(fileStream).ConfigureAwait(false); + using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await response.CopyToAsync(fileStream).ConfigureAwait(false); + } } } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs index 5ca2d5518..b19936480 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs @@ -125,7 +125,7 @@ namespace MediaBrowser.Providers.TV cancellationToken.ThrowIfCancellationRequested(); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -133,7 +133,10 @@ namespace MediaBrowser.Providers.TV }).ConfigureAwait(false)) { - return _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + return _jsonSerializer.DeserializeFromStream(json); + } } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs index ac4523788..0c4c2d9ab 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs @@ -214,7 +214,7 @@ namespace MediaBrowser.Providers.TV cancellationToken.ThrowIfCancellationRequested(); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -222,7 +222,10 @@ namespace MediaBrowser.Providers.TV }).ConfigureAwait(false)) { - return _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + return _jsonSerializer.DeserializeFromStream(json); + } } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs index 72745a9c3..08099179c 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs @@ -352,7 +352,7 @@ namespace MediaBrowser.Providers.TV RootObject mainResult; - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -360,11 +360,14 @@ namespace MediaBrowser.Providers.TV }).ConfigureAwait(false)) { - mainResult = _jsonSerializer.DeserializeFromStream(json); - - if (!string.IsNullOrEmpty(language)) + using (var json = response.Content) { - mainResult.ResultLanguage = language; + mainResult = _jsonSerializer.DeserializeFromStream(json); + + if (!string.IsNullOrEmpty(language)) + { + mainResult.ResultLanguage = language; + } } } @@ -386,7 +389,7 @@ namespace MediaBrowser.Providers.TV url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language); } - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -394,10 +397,13 @@ namespace MediaBrowser.Providers.TV }).ConfigureAwait(false)) { - var englishResult = _jsonSerializer.DeserializeFromStream(json); + using (var json = response.Content) + { + var englishResult = _jsonSerializer.DeserializeFromStream(json); - mainResult.overview = englishResult.overview; - mainResult.ResultLanguage = "en"; + mainResult.overview = englishResult.overview; + mainResult.ResultLanguage = "en"; + } } } @@ -449,7 +455,7 @@ namespace MediaBrowser.Providers.TV MovieDbProvider.ApiKey, externalSource); - using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions + using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, @@ -457,27 +463,30 @@ namespace MediaBrowser.Providers.TV }).ConfigureAwait(false)) { - var result = _jsonSerializer.DeserializeFromStream(json); - - if (result != null && result.tv_results != null) + using (var json = response.Content) { - var tv = result.tv_results.FirstOrDefault(); + var result = _jsonSerializer.DeserializeFromStream(json); - if (tv != null) + if (result != null && result.tv_results != null) { - var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false); - var tmdbImageUrl = tmdbSettings.images.secure_base_url + "original"; + var tv = result.tv_results.FirstOrDefault(); - var remoteResult = new RemoteSearchResult + if (tv != null) { - Name = tv.name, - SearchProviderName = Name, - ImageUrl = string.IsNullOrWhiteSpace(tv.poster_path) ? null : tmdbImageUrl + tv.poster_path - }; + var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false); + var tmdbImageUrl = tmdbSettings.images.secure_base_url + "original"; - remoteResult.SetProviderId(MetadataProviders.Tmdb, tv.id.ToString(_usCulture)); + var remoteResult = new RemoteSearchResult + { + Name = tv.name, + SearchProviderName = Name, + ImageUrl = string.IsNullOrWhiteSpace(tv.poster_path) ? null : tmdbImageUrl + tv.poster_path + }; - return remoteResult; + remoteResult.SetProviderId(MetadataProviders.Tmdb, tv.id.ToString(_usCulture)); + + return remoteResult; + } } } } diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs index 30d2691e3..ebcd61a6e 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs @@ -142,16 +142,20 @@ namespace MediaBrowser.Providers.TV if (string.IsNullOrEmpty(lastUpdateTime)) { // First get tvdb server time - using (var stream = await _httpClient.Get(new HttpRequestOptions + using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = ServerTimeUrl, CancellationToken = cancellationToken, EnableHttpCompression = true, BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - newUpdateTime = GetUpdateTime(stream); + // First get tvdb server time + using (var stream = response.Content) + { + newUpdateTime = GetUpdateTime(stream); + } } existingDirectories.AddRange(missingSeries); @@ -238,23 +242,26 @@ namespace MediaBrowser.Providers.TV private async Task, string>> GetSeriesIdsToUpdate(IEnumerable existingSeriesIds, string lastUpdateTime, CancellationToken cancellationToken) { // First get last time - using (var stream = await _httpClient.Get(new HttpRequestOptions + using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = string.Format(UpdatesUrl, lastUpdateTime), CancellationToken = cancellationToken, EnableHttpCompression = true, BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - var data = GetUpdatedSeriesIdList(stream); + using (var stream = response.Content) + { + var data = GetUpdatedSeriesIdList(stream); - var existingDictionary = existingSeriesIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); + var existingDictionary = existingSeriesIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); - var seriesList = data.Item1 - .Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i)); + var seriesList = data.Item1 + .Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i)); - return new Tuple, string>(seriesList, data.Item2); + return new Tuple, string>(seriesList, data.Item2); + } } } diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs index 812d80b3b..846ab9558 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs @@ -216,24 +216,27 @@ namespace MediaBrowser.Providers.TV var url = string.Format(SeriesGetZip, TVUtils.TvdbApiKey, seriesId, NormalizeLanguage(preferredMetadataLanguage)); - using (var zipStream = await _httpClient.Get(new HttpRequestOptions + using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - // Delete existing files - DeleteXmlFiles(seriesDataPath); - - // Copy to memory stream because we need a seekable stream - using (var ms = _memoryStreamProvider.CreateNew()) + using (var zipStream = response.Content) { - await zipStream.CopyToAsync(ms).ConfigureAwait(false); + // Delete existing files + DeleteXmlFiles(seriesDataPath); - ms.Position = 0; - _zipClient.ExtractAllFromZip(ms, seriesDataPath, true); + // Copy to memory stream because we need a seekable stream + using (var ms = _memoryStreamProvider.CreateNew()) + { + await zipStream.CopyToAsync(ms).ConfigureAwait(false); + + ms.Position = 0; + _zipClient.ExtractAllFromZip(ms, seriesDataPath, true); + } } } @@ -260,15 +263,18 @@ namespace MediaBrowser.Providers.TV { var url = string.Format(GetSeriesByImdbId, id, NormalizeLanguage(language)); - using (var result = await _httpClient.Get(new HttpRequestOptions + using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - return FindSeriesId(result); + using (var result = response.Content) + { + return FindSeriesId(result); + } } } @@ -514,64 +520,67 @@ namespace MediaBrowser.Providers.TV var comparableName = GetComparableName(name); - using (var stream = await _httpClient.Get(new HttpRequestOptions + using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = false - }).ConfigureAwait(false)) + }, "GET").ConfigureAwait(false)) { - var settings = _xmlSettings.Create(false); - - settings.CheckCharacters = false; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreComments = true; - - using (var streamReader = new StreamReader(stream, Encoding.UTF8)) + using (var stream = response.Content) { - // Use XmlReader for best performance - using (var reader = XmlReader.Create(streamReader, settings)) + var settings = _xmlSettings.Create(false); + + settings.CheckCharacters = false; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreComments = true; + + using (var streamReader = new StreamReader(stream, Encoding.UTF8)) { - reader.MoveToContent(); - reader.Read(); - - // Loop through each element - while (!reader.EOF && reader.ReadState == ReadState.Interactive) + // Use XmlReader for best performance + using (var reader = XmlReader.Create(streamReader, settings)) { - cancellationToken.ThrowIfCancellationRequested(); + reader.MoveToContent(); + reader.Read(); - if (reader.NodeType == XmlNodeType.Element) + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) { - switch (reader.Name) + cancellationToken.ThrowIfCancellationRequested(); + + if (reader.NodeType == XmlNodeType.Element) { - case "Series": - { - if (reader.IsEmptyElement) + switch (reader.Name) + { + case "Series": { - reader.Read(); - continue; - } - using (var subtree = reader.ReadSubtree()) - { - var searchResult = GetSeriesSearchResultFromSubTree(subtree, comparableName); - if (searchResult != null) + if (reader.IsEmptyElement) { - searchResult.SearchProviderName = Name; - searchResults.Add(searchResult); + reader.Read(); + continue; } + using (var subtree = reader.ReadSubtree()) + { + var searchResult = GetSeriesSearchResultFromSubTree(subtree, comparableName); + if (searchResult != null) + { + searchResult.SearchProviderName = Name; + searchResults.Add(searchResult); + } + } + break; } - break; - } - default: - reader.Skip(); - break; + default: + reader.Skip(); + break; + } + } + else + { + reader.Read(); } - } - else - { - reader.Read(); } } }