diff --git a/MediaBrowser.Api/ApiService.cs b/MediaBrowser.Api/ApiService.cs index b7a2c4adc3..03ea97fd0e 100644 --- a/MediaBrowser.Api/ApiService.cs +++ b/MediaBrowser.Api/ApiService.cs @@ -81,16 +81,16 @@ namespace MediaBrowser.Api dto.UserData = item.GetUserData(user); - await AttachStudios(dto, item); + await AttachStudios(dto, item).ConfigureAwait(false); if (includeChildren) { - await AttachChildren(dto, item, user); + await AttachChildren(dto, item, user).ConfigureAwait(false); } if (includePeople) { - await AttachPeople(dto, item); + await AttachPeople(dto, item).ConfigureAwait(false); } Folder folder = item as Folder; @@ -125,7 +125,7 @@ namespace MediaBrowser.Api // Attach Studios by transforming them into BaseItemStudio (DTO) if (item.Studios != null) { - IEnumerable entities = await Task.WhenAll(item.Studios.Select(c => Kernel.Instance.ItemController.GetStudio(c))); + IEnumerable entities = await Task.WhenAll(item.Studios.Select(c => Kernel.Instance.ItemController.GetStudio(c))).ConfigureAwait(false); dto.Studios = item.Studios.Select(s => { @@ -153,12 +153,12 @@ namespace MediaBrowser.Api { IEnumerable children = folder.GetParentalAllowedChildren(user); - dto.Children = await Task.WhenAll(children.Select(c => GetDTOBaseItem(c, user, false, false))); + dto.Children = await Task.WhenAll(children.Select(c => GetDTOBaseItem(c, user, false, false))).ConfigureAwait(false); } if (item.LocalTrailers != null && item.LocalTrailers.Any()) { - dto.LocalTrailers = await Task.WhenAll(item.LocalTrailers.Select(c => GetDTOBaseItem(c, user, false, false))); + dto.LocalTrailers = await Task.WhenAll(item.LocalTrailers.Select(c => GetDTOBaseItem(c, user, false, false))).ConfigureAwait(false); } } @@ -167,7 +167,7 @@ namespace MediaBrowser.Api // Attach People by transforming them into BaseItemPerson (DTO) if (item.People != null) { - IEnumerable entities = await Task.WhenAll(item.People.Select(c => Kernel.Instance.ItemController.GetPerson(c.Name))); + IEnumerable entities = await Task.WhenAll(item.People.Select(c => Kernel.Instance.ItemController.GetPerson(c.Name))).ConfigureAwait(false); dto.People = item.People.Select(p => { diff --git a/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs b/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs index d2dbd699d3..7d9200b111 100644 --- a/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs @@ -92,10 +92,7 @@ namespace MediaBrowser.Api.HttpHandlers public override Task GetContentType() { - return Task.Run(() => - { - return MimeTypes.GetMimeType("." + GetConversionOutputFormat()); - }); + return Task.FromResult(MimeTypes.GetMimeType("." + GetConversionOutputFormat())); } public override bool ShouldCompressResponse(string contentType) @@ -103,17 +100,17 @@ namespace MediaBrowser.Api.HttpHandlers return false; } - public override async Task ProcessRequest(HttpListenerContext ctx) + public override Task ProcessRequest(HttpListenerContext ctx) { HttpListenerContext = ctx; if (!RequiresConversion()) { - await new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx); + return new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx); } else { - await base.ProcessRequest(ctx); + return base.ProcessRequest(ctx); } } @@ -180,15 +177,15 @@ namespace MediaBrowser.Api.HttpHandlers // If we ever decide to disable the ffmpeg log then you must uncomment the below line. //process.BeginErrorReadLine(); - Task debugLogTask = Task.Run(async () => { await process.StandardError.BaseStream.CopyToAsync(logStream); }); + Task debugLogTask = process.StandardError.BaseStream.CopyToAsync(logStream); - await process.StandardOutput.BaseStream.CopyToAsync(stream); + await process.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false); process.WaitForExit(); Logger.LogInfo("FFMpeg exited with code " + process.ExitCode); - await debugLogTask; + await debugLogTask.ConfigureAwait(false); } catch (Exception ex) { diff --git a/MediaBrowser.Api/HttpHandlers/GenreHandler.cs b/MediaBrowser.Api/HttpHandlers/GenreHandler.cs index c4198b0288..e9e5c41f45 100644 --- a/MediaBrowser.Api/HttpHandlers/GenreHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/GenreHandler.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Api.HttpHandlers /// public class GenreHandler : BaseJsonHandler> { - protected override async Task> GetObjectToSerialize() + protected override Task> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); @@ -22,7 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers string name = QueryString["name"]; - return await GetGenre(parent, user, name); + return GetGenre(parent, user, name); } /// @@ -46,7 +46,7 @@ namespace MediaBrowser.Api.HttpHandlers // Get the original entity so that we can also supply the PrimaryImagePath return new IBNItem() { - Item = await Kernel.Instance.ItemController.GetGenre(name), + Item = await Kernel.Instance.ItemController.GetGenre(name).ConfigureAwait(false), BaseItemCount = count }; } diff --git a/MediaBrowser.Api/HttpHandlers/GenresHandler.cs b/MediaBrowser.Api/HttpHandlers/GenresHandler.cs index cd68f1eaa9..8ac30043ef 100644 --- a/MediaBrowser.Api/HttpHandlers/GenresHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/GenresHandler.cs @@ -11,13 +11,13 @@ namespace MediaBrowser.Api.HttpHandlers { public class GenresHandler : BaseJsonHandler>> { - protected override async Task>> GetObjectToSerialize() + protected override Task>> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); User user = Kernel.Instance.Users.First(u => u.Id == userId); - return await GetAllGenres(parent, user); + return GetAllGenres(parent, user); } /// @@ -53,7 +53,7 @@ namespace MediaBrowser.Api.HttpHandlers } } - IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetGenre(key); })); + IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetGenre(key); })).ConfigureAwait(false); return entities.Select(e => new IBNItem() { Item = e, BaseItemCount = data[e.Name] }); } diff --git a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs index 39a115cefb..48c67eeef2 100644 --- a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs @@ -29,28 +29,28 @@ namespace MediaBrowser.Api.HttpHandlers if (!string.IsNullOrEmpty(personName)) { - return (await Kernel.Instance.ItemController.GetPerson(personName)).PrimaryImagePath; + return (await Kernel.Instance.ItemController.GetPerson(personName).ConfigureAwait(false)).PrimaryImagePath; } string genreName = QueryString["genre"]; if (!string.IsNullOrEmpty(genreName)) { - return (await Kernel.Instance.ItemController.GetGenre(genreName)).PrimaryImagePath; + return (await Kernel.Instance.ItemController.GetGenre(genreName).ConfigureAwait(false)).PrimaryImagePath; } string year = QueryString["year"]; if (!string.IsNullOrEmpty(year)) { - return (await Kernel.Instance.ItemController.GetYear(int.Parse(year))).PrimaryImagePath; + return (await Kernel.Instance.ItemController.GetYear(int.Parse(year)).ConfigureAwait(false)).PrimaryImagePath; } string studio = QueryString["studio"]; if (!string.IsNullOrEmpty(studio)) { - return (await Kernel.Instance.ItemController.GetStudio(studio)).PrimaryImagePath; + return (await Kernel.Instance.ItemController.GetStudio(studio).ConfigureAwait(false)).PrimaryImagePath; } BaseItem item = ApiService.GetItemById(QueryString["id"]); @@ -64,7 +64,7 @@ namespace MediaBrowser.Api.HttpHandlers private Stream _SourceStream = null; private async Task GetSourceStream() { - await EnsureSourceStream(); + await EnsureSourceStream().ConfigureAwait(false); return _SourceStream; } @@ -75,7 +75,7 @@ namespace MediaBrowser.Api.HttpHandlers { try { - _SourceStream = File.OpenRead(await GetImagePath()); + _SourceStream = File.OpenRead(await GetImagePath().ConfigureAwait(false)); } catch (FileNotFoundException ex) { @@ -101,14 +101,14 @@ namespace MediaBrowser.Api.HttpHandlers public async override Task GetContentType() { - await EnsureSourceStream(); + await EnsureSourceStream().ConfigureAwait(false); - if (await GetSourceStream() == null) + if (await GetSourceStream().ConfigureAwait(false) == null) { return null; } - return MimeTypes.GetMimeType(await GetImagePath()); + return MimeTypes.GetMimeType(await GetImagePath().ConfigureAwait(false)); } public override TimeSpan CacheDuration @@ -121,14 +121,14 @@ namespace MediaBrowser.Api.HttpHandlers protected async override Task GetLastDateModified() { - await EnsureSourceStream(); + await EnsureSourceStream().ConfigureAwait(false); - if (await GetSourceStream() == null) + if (await GetSourceStream().ConfigureAwait(false) == null) { return null; } - return File.GetLastWriteTime(await GetImagePath()); + return File.GetLastWriteTime(await GetImagePath().ConfigureAwait(false)); } private int? Height @@ -223,7 +223,7 @@ namespace MediaBrowser.Api.HttpHandlers protected override async Task WriteResponseToOutputStream(Stream stream) { - ImageProcessor.ProcessImage(await GetSourceStream(), stream, Width, Height, MaxWidth, MaxHeight, Quality); + ImageProcessor.ProcessImage(await GetSourceStream().ConfigureAwait(false), stream, Width, Height, MaxWidth, MaxHeight, Quality); } private string GetImagePathFromTypes(BaseItem item, ImageType imageType, int imageIndex) diff --git a/MediaBrowser.Api/HttpHandlers/ItemHandler.cs b/MediaBrowser.Api/HttpHandlers/ItemHandler.cs index ac27633b7b..4f2a9c68e5 100644 --- a/MediaBrowser.Api/HttpHandlers/ItemHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ItemHandler.cs @@ -10,7 +10,7 @@ namespace MediaBrowser.Api.HttpHandlers { public class ItemHandler : BaseJsonHandler { - protected async override Task GetObjectToSerialize() + protected override Task GetObjectToSerialize() { Guid userId = Guid.Parse(QueryString["userid"]); User user = Kernel.Instance.Users.First(u => u.Id == userId); @@ -22,7 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers return null; } - return await ApiService.GetDTOBaseItem(item, user); + return ApiService.GetDTOBaseItem(item, user); } protected virtual BaseItem ItemToSerialize diff --git a/MediaBrowser.Api/HttpHandlers/ItemListHandler.cs b/MediaBrowser.Api/HttpHandlers/ItemListHandler.cs index 6e4a420813..9d5e3eb580 100644 --- a/MediaBrowser.Api/HttpHandlers/ItemListHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ItemListHandler.cs @@ -9,13 +9,13 @@ using MediaBrowser.Model.Entities; namespace MediaBrowser.Api.HttpHandlers { - public class ItemListHandler : BaseJsonHandler> + public class ItemListHandler : BaseJsonHandler { - protected override async Task> GetObjectToSerialize() + protected override Task GetObjectToSerialize() { User user = Kernel.Instance.Users.First(u => u.Id == UserId); - return await Task.WhenAll(ItemsToSerialize.Select(i => + return Task.WhenAll(ItemsToSerialize.Select(i => { return ApiService.GetDTOBaseItem(i, user, includeChildren: false, includePeople: false); })); diff --git a/MediaBrowser.Api/HttpHandlers/PersonHandler.cs b/MediaBrowser.Api/HttpHandlers/PersonHandler.cs index f095a3a47c..b144c0bdf4 100644 --- a/MediaBrowser.Api/HttpHandlers/PersonHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/PersonHandler.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Api.HttpHandlers /// public class PersonHandler : BaseJsonHandler> { - protected async override Task> GetObjectToSerialize() + protected override Task> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); @@ -22,7 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers string name = QueryString["name"]; - return await GetPerson(parent, user, name); + return GetPerson(parent, user, name); } /// @@ -46,7 +46,7 @@ namespace MediaBrowser.Api.HttpHandlers // Get the original entity so that we can also supply the PrimaryImagePath return new IBNItem() { - Item = await Kernel.Instance.ItemController.GetPerson(name), + Item = await Kernel.Instance.ItemController.GetPerson(name).ConfigureAwait(false), BaseItemCount = count }; } diff --git a/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs b/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs index 109440e982..fbc16109d8 100644 --- a/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs @@ -11,12 +11,11 @@ namespace MediaBrowser.Api.HttpHandlers { protected override Task GetObjectToSerialize() { - return Task.Run(() => - { - string pluginName = QueryString["name"]; + string pluginName = QueryString["name"]; - return Kernel.Instance.Plugins.First(p => p.Name.Equals(pluginName, StringComparison.OrdinalIgnoreCase)).Configuration; - }); + BasePluginConfiguration config = Kernel.Instance.Plugins.First(p => p.Name.Equals(pluginName, StringComparison.OrdinalIgnoreCase)).Configuration; + + return Task.FromResult(config); } } } diff --git a/MediaBrowser.Api/HttpHandlers/PluginsHandler.cs b/MediaBrowser.Api/HttpHandlers/PluginsHandler.cs index f451832dd4..1cb4e95f76 100644 --- a/MediaBrowser.Api/HttpHandlers/PluginsHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/PluginsHandler.cs @@ -14,27 +14,24 @@ namespace MediaBrowser.Api.HttpHandlers { protected override Task> GetObjectToSerialize() { - return Task.Run(() => + var plugins = Kernel.Instance.Plugins.Select(p => { - var plugins = Kernel.Instance.Plugins.Select(p => + return new PluginInfo() { - return new PluginInfo() - { - Path = p.Path, - Name = p.Name, - Enabled = p.Enabled, - DownloadToUI = p.DownloadToUI, - Version = p.Version - }; - }); + Path = p.Path, + Name = p.Name, + Enabled = p.Enabled, + DownloadToUI = p.DownloadToUI, + Version = p.Version + }; + }); - if (QueryString["uionly"] == "1") - { - plugins = plugins.Where(p => p.DownloadToUI); - } + if (QueryString["uionly"] == "1") + { + plugins = plugins.Where(p => p.DownloadToUI); + } - return plugins; - }); + return Task.FromResult>(plugins); } } } diff --git a/MediaBrowser.Api/HttpHandlers/StudioHandler.cs b/MediaBrowser.Api/HttpHandlers/StudioHandler.cs index b44970ea50..727237882b 100644 --- a/MediaBrowser.Api/HttpHandlers/StudioHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/StudioHandler.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Api.HttpHandlers /// public class StudioHandler : BaseJsonHandler> { - protected async override Task> GetObjectToSerialize() + protected override Task> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); @@ -22,7 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers string name = QueryString["name"]; - return await GetStudio(parent, user, name); + return GetStudio(parent, user, name); } /// @@ -46,7 +46,7 @@ namespace MediaBrowser.Api.HttpHandlers // Get the original entity so that we can also supply the PrimaryImagePath return new IBNItem() { - Item = await Kernel.Instance.ItemController.GetStudio(name), + Item = await Kernel.Instance.ItemController.GetStudio(name).ConfigureAwait(false), BaseItemCount = count }; } diff --git a/MediaBrowser.Api/HttpHandlers/StudiosHandler.cs b/MediaBrowser.Api/HttpHandlers/StudiosHandler.cs index d379b45fb4..7e85e5558c 100644 --- a/MediaBrowser.Api/HttpHandlers/StudiosHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/StudiosHandler.cs @@ -11,13 +11,13 @@ namespace MediaBrowser.Api.HttpHandlers { public class StudiosHandler : BaseJsonHandler>> { - protected override async Task>> GetObjectToSerialize() + protected override Task>> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); User user = Kernel.Instance.Users.First(u => u.Id == userId); - return await GetAllStudios(parent, user); + return GetAllStudios(parent, user); } /// @@ -53,7 +53,7 @@ namespace MediaBrowser.Api.HttpHandlers } } - IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetStudio(key); })); + IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetStudio(key); })).ConfigureAwait(false); return entities.Select(e => new IBNItem() { Item = e, BaseItemCount = data[e.Name] }); } diff --git a/MediaBrowser.Api/HttpHandlers/UsersHandler.cs b/MediaBrowser.Api/HttpHandlers/UsersHandler.cs index 1368735740..ad9ffec980 100644 --- a/MediaBrowser.Api/HttpHandlers/UsersHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/UsersHandler.cs @@ -10,10 +10,7 @@ namespace MediaBrowser.Api.HttpHandlers { protected override Task> GetObjectToSerialize() { - return Task.Run(() => - { - return Kernel.Instance.Users; - }); + return Task.FromResult>(Kernel.Instance.Users); } } } diff --git a/MediaBrowser.Api/HttpHandlers/YearHandler.cs b/MediaBrowser.Api/HttpHandlers/YearHandler.cs index dfde600e78..5e31c9689f 100644 --- a/MediaBrowser.Api/HttpHandlers/YearHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/YearHandler.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Api.HttpHandlers /// public class YearHandler : BaseJsonHandler> { - protected override async Task> GetObjectToSerialize() + protected override Task> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); @@ -22,7 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers string year = QueryString["year"]; - return await GetYear(parent, user, int.Parse(year)); + return GetYear(parent, user, int.Parse(year)); } /// @@ -46,7 +46,7 @@ namespace MediaBrowser.Api.HttpHandlers // Get the original entity so that we can also supply the PrimaryImagePath return new IBNItem() { - Item = await Kernel.Instance.ItemController.GetYear(year), + Item = await Kernel.Instance.ItemController.GetYear(year).ConfigureAwait(false), BaseItemCount = count }; } diff --git a/MediaBrowser.Api/HttpHandlers/YearsHandler.cs b/MediaBrowser.Api/HttpHandlers/YearsHandler.cs index 6ce087f857..dcbbf6150e 100644 --- a/MediaBrowser.Api/HttpHandlers/YearsHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/YearsHandler.cs @@ -11,13 +11,13 @@ namespace MediaBrowser.Api.HttpHandlers { public class YearsHandler : BaseJsonHandler>> { - protected override async Task>> GetObjectToSerialize() + protected override Task>> GetObjectToSerialize() { Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; Guid userId = Guid.Parse(QueryString["userid"]); User user = Kernel.Instance.Users.First(u => u.Id == userId); - return await GetAllYears(parent, user); + return GetAllYears(parent, user); } /// @@ -50,7 +50,7 @@ namespace MediaBrowser.Api.HttpHandlers } } - IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetYear(key); })); + IEnumerable entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetYear(key); })).ConfigureAwait(false); return entities.Select(e => new IBNItem() { Item = e, BaseItemCount = data[int.Parse(e.Name)] }); } diff --git a/MediaBrowser.Api/Plugin.cs b/MediaBrowser.Api/Plugin.cs index 7f764d6fb1..97d4a58652 100644 --- a/MediaBrowser.Api/Plugin.cs +++ b/MediaBrowser.Api/Plugin.cs @@ -22,13 +22,13 @@ namespace MediaBrowser.Api { var httpServer = Kernel.Instance.HttpServer; - httpServer.Where(ctx => ctx.Request.Url.LocalPath.IndexOf("/api/", StringComparison.OrdinalIgnoreCase) != -1).Subscribe(async (ctx) => + httpServer.Where(ctx => ctx.Request.Url.LocalPath.IndexOf("/api/", StringComparison.OrdinalIgnoreCase) != -1).Subscribe((ctx) => { BaseHandler handler = GetHandler(ctx); if (handler != null) { - await handler.ProcessRequest(ctx); + handler.ProcessRequest(ctx); } }); } diff --git a/MediaBrowser.ApiInteraction/ApiClient.cs b/MediaBrowser.ApiInteraction/ApiClient.cs index 58ccb627c0..f715e842e3 100644 --- a/MediaBrowser.ApiInteraction/ApiClient.cs +++ b/MediaBrowser.ApiInteraction/ApiClient.cs @@ -152,9 +152,9 @@ namespace MediaBrowser.ApiInteraction /// /// Gets an image stream based on a url /// - public async Task GetImageStreamAsync(string url) + public Task GetImageStreamAsync(string url) { - return await HttpClient.GetStreamAsync(url); + return HttpClient.GetStreamAsync(url); } /// @@ -169,7 +169,7 @@ namespace MediaBrowser.ApiInteraction url += "&id=" + id.ToString(); } - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream(stream); } @@ -182,7 +182,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/users"; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -195,7 +195,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/genres?userId=" + userId.ToString(); - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>>(stream); } @@ -208,7 +208,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/years?userId=" + userId.ToString(); - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>>(stream); } @@ -221,7 +221,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/itemlist?listtype=itemswithyear&userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -234,7 +234,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/itemlist?listtype=itemswithgenre&userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -247,7 +247,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/itemlist?listtype=itemswithperson&userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -262,7 +262,7 @@ namespace MediaBrowser.ApiInteraction url += "&persontype=" + personType; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -275,7 +275,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/studios?userId=" + userId.ToString(); - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>>(stream); } @@ -288,7 +288,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/itemlist?listtype=itemswithstudio&userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -301,7 +301,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/studio?userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -314,7 +314,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/genre?userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -327,7 +327,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/person?userId=" + userId.ToString() + "&name=" + name; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } @@ -340,7 +340,7 @@ namespace MediaBrowser.ApiInteraction { string url = ApiUrl + "/year?userId=" + userId.ToString() + "&year=" + year; - using (Stream stream = await HttpClient.GetStreamAsync(url)) + using (Stream stream = await HttpClient.GetStreamAsync(url).ConfigureAwait(false)) { return JsonSerializer.DeserializeFromStream>(stream); } diff --git a/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs index a8c7090f7d..9d9e2a0e03 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using System.Threading.Tasks; namespace MediaBrowser.Common.Net.Handlers @@ -16,37 +15,7 @@ namespace MediaBrowser.Common.Net.Handlers public override Task GetContentType() { - return Task.Run(() => - { - string extension = Path.GetExtension(ResourcePath); - - if (extension.EndsWith("jpeg", StringComparison.OrdinalIgnoreCase) || extension.EndsWith("jpg", StringComparison.OrdinalIgnoreCase)) - { - return "image/jpeg"; - } - else if (extension.EndsWith("png", StringComparison.OrdinalIgnoreCase)) - { - return "image/png"; - } - else if (extension.EndsWith("ico", StringComparison.OrdinalIgnoreCase)) - { - return "image/ico"; - } - else if (extension.EndsWith("js", StringComparison.OrdinalIgnoreCase)) - { - return "application/x-javascript"; - } - else if (extension.EndsWith("css", StringComparison.OrdinalIgnoreCase)) - { - return "text/css"; - } - else if (extension.EndsWith("html", StringComparison.OrdinalIgnoreCase)) - { - return "text/html; charset=utf-8"; - } - - return "text/plain; charset=utf-8"; - }); + return Task.FromResult(MimeTypes.GetMimeType(ResourcePath)); } protected override Task WriteResponseToOutputStream(Stream stream) diff --git a/MediaBrowser.Common/Net/Handlers/BaseHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs index 7a4efdaf2b..19a1e7af7b 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs @@ -185,11 +185,11 @@ namespace MediaBrowser.Common.Net.Handlers // When serving a range request, we need to return status code 206 to indicate a partial response body StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200; - ctx.Response.ContentType = await GetContentType(); + ctx.Response.ContentType = await GetContentType().ConfigureAwait(false); TimeSpan cacheDuration = CacheDuration; - DateTime? lastDateModified = await GetLastDateModified(); + DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false); if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since")) { @@ -205,13 +205,13 @@ namespace MediaBrowser.Common.Net.Handlers } } - await PrepareResponse(); + await PrepareResponse().ConfigureAwait(false); if (IsResponseValid) { bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression; - await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified); + await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false); } else { @@ -285,7 +285,7 @@ namespace MediaBrowser.Common.Net.Handlers outputStream = CompressedStream; } - await WriteResponseToOutputStream(outputStream); + await WriteResponseToOutputStream(outputStream).ConfigureAwait(false); } else { @@ -307,7 +307,7 @@ namespace MediaBrowser.Common.Net.Handlers /// protected virtual Task PrepareResponse() { - return Task.Run(() => { }); + return Task.FromResult(null); } protected abstract Task WriteResponseToOutputStream(Stream stream); @@ -359,7 +359,7 @@ namespace MediaBrowser.Common.Net.Handlers { DateTime? value = null; - return Task.Run(() => { return value; }); + return Task.FromResult(value); } private bool IsResponseValid diff --git a/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs index a3a47a4a33..6508535376 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs @@ -8,10 +8,7 @@ namespace MediaBrowser.Common.Net.Handlers { public override Task GetContentType() { - return Task.Run(() => - { - return MimeTypes.JsonMimeType; - }); + return Task.FromResult(MimeTypes.JsonMimeType); } private bool _ObjectToSerializeEnsured = false; @@ -21,7 +18,7 @@ namespace MediaBrowser.Common.Net.Handlers { if (!_ObjectToSerializeEnsured) { - _ObjectToSerialize = await GetObjectToSerialize(); + _ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false); if (_ObjectToSerialize == null) { @@ -34,9 +31,9 @@ namespace MediaBrowser.Common.Net.Handlers protected abstract Task GetObjectToSerialize(); - protected override async Task PrepareResponse() + protected override Task PrepareResponse() { - await EnsureObjectToSerialize(); + return EnsureObjectToSerialize(); } protected async override Task WriteResponseToOutputStream(Stream stream) diff --git a/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs b/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs index d8971dd97d..799abea9b4 100644 --- a/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs @@ -102,33 +102,30 @@ namespace MediaBrowser.Common.Net.Handlers protected override Task GetLastDateModified() { - return Task.Run(() => - { - EnsureSourceStream(); + DateTime? value = null; - if (SourceStream == null) - { - return null; - } + EnsureSourceStream(); - return File.GetLastWriteTime(Path); - }); + if (SourceStream != null) + { + value = File.GetLastWriteTime(Path); + } + + return Task.FromResult(value); } public override Task GetContentType() { - return Task.Run(() => - { - return MimeTypes.GetMimeType(Path); - }); + return Task.FromResult(MimeTypes.GetMimeType(Path)); } protected override Task PrepareResponse() { - return Task.Run(() => { EnsureSourceStream(); }); + EnsureSourceStream(); + return Task.FromResult(null); } - protected async override Task WriteResponseToOutputStream(Stream stream) + protected override Task WriteResponseToOutputStream(Stream stream) { if (IsRangeRequest) { @@ -137,22 +134,22 @@ namespace MediaBrowser.Common.Net.Handlers // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory if (requestedRange.Value == null && TotalContentLength != null) { - await ServeCompleteRangeRequest(requestedRange, stream); + return ServeCompleteRangeRequest(requestedRange, stream); } else if (TotalContentLength.HasValue) { // This will have to buffer a portion of the content into memory - await ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream); + return ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream); } else { // This will have to buffer the entire content into memory - await ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream); + return ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream); } } else { - await SourceStream.CopyToAsync(stream); + return SourceStream.CopyToAsync(stream); } } @@ -170,7 +167,7 @@ namespace MediaBrowser.Common.Net.Handlers /// Handles a range request of "bytes=0-" /// This will serve the complete content and add the content-range header /// - private async Task ServeCompleteRangeRequest(KeyValuePair requestedRange, Stream responseStream) + private Task ServeCompleteRangeRequest(KeyValuePair requestedRange, Stream responseStream) { long totalContentLength = TotalContentLength.Value; @@ -187,7 +184,7 @@ namespace MediaBrowser.Common.Net.Handlers SourceStream.Position = rangeStart; } - await SourceStream.CopyToAsync(responseStream); + return SourceStream.CopyToAsync(responseStream); } /// @@ -196,7 +193,7 @@ namespace MediaBrowser.Common.Net.Handlers private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair requestedRange, Stream responseStream) { // Read the entire stream so that we can determine the length - byte[] bytes = await ReadBytes(SourceStream, 0, null); + byte[] bytes = await ReadBytes(SourceStream, 0, null).ConfigureAwait(false); long totalContentLength = bytes.LongLength; @@ -208,7 +205,7 @@ namespace MediaBrowser.Common.Net.Handlers HttpListenerContext.Response.ContentLength64 = rangeLength; HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength); - await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)); + await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false); } /// @@ -222,14 +219,14 @@ namespace MediaBrowser.Common.Net.Handlers long rangeLength = 1 + rangeEnd - rangeStart; // Only read the bytes we need - byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)); + byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false); // Content-Length is the length of what we're serving, not the original content HttpListenerContext.Response.ContentLength64 = rangeLength; HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength); - await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)); + await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false); } /// @@ -252,9 +249,9 @@ namespace MediaBrowser.Common.Net.Handlers using (MemoryStream ms = new MemoryStream()) { int read; - while ((read = await input.ReadAsync(buffer, 0, buffer.Length)) > 0) + while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { - await ms.WriteAsync(buffer, 0, read); + await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false); } return ms.ToArray(); } @@ -265,9 +262,9 @@ namespace MediaBrowser.Common.Net.Handlers using (MemoryStream ms = new MemoryStream()) { - int read = await input.ReadAsync(buffer, 0, buffer.Length); + int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - await ms.WriteAsync(buffer, 0, read); + await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false); return ms.ToArray(); } diff --git a/MediaBrowser.Common/UI/BaseApplication.cs b/MediaBrowser.Common/UI/BaseApplication.cs index 9ad2a749b6..27c64f4519 100644 --- a/MediaBrowser.Common/UI/BaseApplication.cs +++ b/MediaBrowser.Common/UI/BaseApplication.cs @@ -17,15 +17,15 @@ namespace MediaBrowser.Common.UI protected abstract IKernel InstantiateKernel(); protected abstract Window InstantiateMainWindow(); - protected async override void OnStartup(StartupEventArgs e) + protected override void OnStartup(StartupEventArgs e) { // Without this the app will shutdown after the splash screen closes this.ShutdownMode = ShutdownMode.OnExplicitShutdown; - await LoadKernel().ConfigureAwait(false); + LoadKernel(); } - private async Task LoadKernel() + private async void LoadKernel() { Kernel = InstantiateKernel(); @@ -40,9 +40,7 @@ namespace MediaBrowser.Common.UI await Kernel.Init(progress); - double seconds = (DateTime.Now - now).TotalSeconds; - - Logger.LogInfo("Kernel.Init completed in {0} seconds.", seconds); + Logger.LogInfo("Kernel.Init completed in {0} seconds.", (DateTime.Now - now).TotalSeconds); splash.Close(); this.ShutdownMode = System.Windows.ShutdownMode.OnLastWindowClose; diff --git a/MediaBrowser.Controller/FFMpeg/FFProbe.cs b/MediaBrowser.Controller/FFMpeg/FFProbe.cs index f5364821ce..1a0685a7a6 100644 --- a/MediaBrowser.Controller/FFMpeg/FFProbe.cs +++ b/MediaBrowser.Controller/FFMpeg/FFProbe.cs @@ -18,10 +18,7 @@ namespace MediaBrowser.Controller.FFMpeg // Use try catch to avoid having to use File.Exists try { - using (FileStream stream = File.OpenRead(outputCachePath)) - { - return JsonSerializer.DeserializeFromStream(stream); - } + return GetCachedResult(outputCachePath); } catch (FileNotFoundException) { @@ -29,7 +26,12 @@ namespace MediaBrowser.Controller.FFMpeg await Run(item.Path, outputCachePath).ConfigureAwait(false); - using (FileStream stream = File.OpenRead(outputCachePath)) + return GetCachedResult(item.Path); + } + + public static FFProbeResult GetCachedResult(string path) + { + using (FileStream stream = File.OpenRead(path)) { return JsonSerializer.DeserializeFromStream(stream); } @@ -40,10 +42,7 @@ namespace MediaBrowser.Controller.FFMpeg // Use try catch to avoid having to use File.Exists try { - using (FileStream stream = File.OpenRead(outputCachePath)) - { - return JsonSerializer.DeserializeFromStream(stream); - } + return GetCachedResult(outputCachePath); } catch (FileNotFoundException) { @@ -51,10 +50,7 @@ namespace MediaBrowser.Controller.FFMpeg await Run(item.Path, outputCachePath).ConfigureAwait(false); - using (FileStream stream = File.OpenRead(outputCachePath)) - { - return JsonSerializer.DeserializeFromStream(stream); - } + return GetCachedResult(item.Path); } private async static Task Run(string input, string output) diff --git a/MediaBrowser.Controller/IO/DirectoryWatchers.cs b/MediaBrowser.Controller/IO/DirectoryWatchers.cs index 0a96990bfe..10d11385ee 100644 --- a/MediaBrowser.Controller/IO/DirectoryWatchers.cs +++ b/MediaBrowser.Controller/IO/DirectoryWatchers.cs @@ -86,7 +86,7 @@ namespace MediaBrowser.Controller.IO await ProcessPathChanges(paths).ConfigureAwait(false); } - private async Task ProcessPathChanges(IEnumerable paths) + private Task ProcessPathChanges(IEnumerable paths) { List itemsToRefresh = new List(); @@ -105,11 +105,11 @@ namespace MediaBrowser.Controller.IO return folder != null && folder.IsRoot; })) { - await Kernel.Instance.ReloadRoot().ConfigureAwait(false); + return Kernel.Instance.ReloadRoot(); } else { - await Task.WhenAll(itemsToRefresh.Select(i => Kernel.Instance.ReloadItem(i))).ConfigureAwait(false); + return Task.WhenAll(itemsToRefresh.Select(i => Kernel.Instance.ReloadItem(i))); } } diff --git a/MediaBrowser.Controller/Kernel.cs b/MediaBrowser.Controller/Kernel.cs index a24571d87a..fa2baafbcf 100644 --- a/MediaBrowser.Controller/Kernel.cs +++ b/MediaBrowser.Controller/Kernel.cs @@ -68,21 +68,17 @@ namespace MediaBrowser.Controller public async override Task Init(IProgress progress) { - await Task.Run(async () => - { - await base.Init(progress).ConfigureAwait(false); + ExtractFFMpeg(); + + await base.Init(progress).ConfigureAwait(false); - progress.Report(new TaskProgress() { Description = "Loading Users", PercentComplete = 15 }); - ReloadUsers(); + progress.Report(new TaskProgress() { Description = "Loading Users", PercentComplete = 15 }); + ReloadUsers(); - progress.Report(new TaskProgress() { Description = "Extracting FFMpeg", PercentComplete = 20 }); - await ExtractFFMpeg().ConfigureAwait(false); + progress.Report(new TaskProgress() { Description = "Loading Media Library", PercentComplete = 25 }); + await ReloadRoot().ConfigureAwait(false); - progress.Report(new TaskProgress() { Description = "Loading Media Library", PercentComplete = 25 }); - await ReloadRoot().ConfigureAwait(false); - - progress.Report(new TaskProgress() { Description = "Loading Complete", PercentComplete = 100 }); - }).ConfigureAwait(false); + progress.Report(new TaskProgress() { Description = "Loading Complete", PercentComplete = 100 }); } protected override void OnComposablePartsLoaded() @@ -245,22 +241,21 @@ namespace MediaBrowser.Controller continue; } - await provider.Fetch(item, args).ConfigureAwait(false); + await provider.FetchAsync(item, args).ConfigureAwait(false); } } + private void ExtractFFMpeg() + { + ExtractFFMpeg(ApplicationPaths.FFMpegPath); + ExtractFFMpeg(ApplicationPaths.FFProbePath); + } + /// /// Run these during Init. /// Can't run do this on-demand because there will be multiple workers accessing them at once and we'd have to lock them /// - private async Task ExtractFFMpeg() - { - // FFMpeg.exe - await ExtractFFMpeg(ApplicationPaths.FFMpegPath).ConfigureAwait(false); - await ExtractFFMpeg(ApplicationPaths.FFProbePath).ConfigureAwait(false); - } - - private async Task ExtractFFMpeg(string exe) + private async void ExtractFFMpeg(string exe) { if (File.Exists(exe)) { diff --git a/MediaBrowser.Controller/Library/ItemController.cs b/MediaBrowser.Controller/Library/ItemController.cs index 9fd77fb0d9..f182f43f01 100644 --- a/MediaBrowser.Controller/Library/ItemController.cs +++ b/MediaBrowser.Controller/Library/ItemController.cs @@ -116,14 +116,17 @@ namespace MediaBrowser.Controller.Library if (item != null) { - await Kernel.Instance.ExecuteMetadataProviders(item, args); + await Kernel.Instance.ExecuteMetadataProviders(item, args).ConfigureAwait(false); - var folder = item as Folder; - - if (folder != null) + if (item.IsFolder) { // If it's a folder look for child entities - await AttachChildren(folder, fileSystemChildren).ConfigureAwait(false); + (item as Folder).Children = (await Task.WhenAll(GetChildren(item as Folder, fileSystemChildren)).ConfigureAwait(false)) + .Where(i => i != null).OrderBy(f => + { + return string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName; + + }); } } @@ -133,27 +136,18 @@ namespace MediaBrowser.Controller.Library /// /// Finds child BaseItems for a given Folder /// - private async Task AttachChildren(Folder folder, LazyFileInfo[] fileSystemChildren) + private Task[] GetChildren(Folder folder, LazyFileInfo[] fileSystemChildren) { - int count = fileSystemChildren.Length; - - Task[] tasks = new Task[count]; + Task[] tasks = new Task[fileSystemChildren.Length]; - for (int i = 0; i < count; i++) + for (int i = 0; i < fileSystemChildren.Length; i++) { var child = fileSystemChildren[i]; tasks[i] = GetItem(child.Path, folder, child.FileInfo); } - BaseItem[] baseItemChildren = await Task.WhenAll(tasks).ConfigureAwait(false); - - // Sort them - folder.Children = baseItemChildren.Where(i => i != null).OrderBy(f => - { - return string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName; - - }); + return tasks; } /// @@ -216,41 +210,41 @@ namespace MediaBrowser.Controller.Library /// /// Gets a Person /// - public async Task GetPerson(string name) + public Task GetPerson(string name) { string path = Path.Combine(Kernel.Instance.ApplicationPaths.PeoplePath, name); - return await GetImagesByNameItem(path, name).ConfigureAwait(false); + return GetImagesByNameItem(path, name); } /// /// Gets a Studio /// - public async Task GetStudio(string name) + public Task GetStudio(string name) { string path = Path.Combine(Kernel.Instance.ApplicationPaths.StudioPath, name); - return await GetImagesByNameItem(path, name).ConfigureAwait(false); + return GetImagesByNameItem(path, name); } /// /// Gets a Genre /// - public async Task GetGenre(string name) + public Task GetGenre(string name) { string path = Path.Combine(Kernel.Instance.ApplicationPaths.GenrePath, name); - return await GetImagesByNameItem(path, name).ConfigureAwait(false); + return GetImagesByNameItem(path, name); } /// /// Gets a Year /// - public async Task GetYear(int value) + public Task GetYear(int value) { string path = Path.Combine(Kernel.Instance.ApplicationPaths.YearPath, value.ToString()); - return await GetImagesByNameItem(path, value.ToString()).ConfigureAwait(false); + return GetImagesByNameItem(path, value.ToString()); } private ConcurrentDictionary ImagesByNameItemCache = new ConcurrentDictionary(); @@ -258,7 +252,7 @@ namespace MediaBrowser.Controller.Library /// /// Generically retrieves an IBN item /// - private async Task GetImagesByNameItem(string path, string name) + private Task GetImagesByNameItem(string path, string name) where T : BaseEntity, new() { string key = path.ToLower(); @@ -266,12 +260,10 @@ namespace MediaBrowser.Controller.Library // Look for it in the cache, if it's not there, create it if (!ImagesByNameItemCache.ContainsKey(key)) { - T obj = await CreateImagesByNameItem(path, name).ConfigureAwait(false); - ImagesByNameItemCache[key] = obj; - return obj; + ImagesByNameItemCache[key] = CreateImagesByNameItem(path, name); } - return ImagesByNameItemCache[key] as T; + return ImagesByNameItemCache[key] as Task; } /// diff --git a/MediaBrowser.Controller/Providers/AudioInfoProvider.cs b/MediaBrowser.Controller/Providers/AudioInfoProvider.cs index 85a030ddf5..64b397a697 100644 --- a/MediaBrowser.Controller/Providers/AudioInfoProvider.cs +++ b/MediaBrowser.Controller/Providers/AudioInfoProvider.cs @@ -23,16 +23,22 @@ namespace MediaBrowser.Controller.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public async override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { Audio audio = item as Audio; - string outputDirectory = Path.Combine(Kernel.Instance.ApplicationPaths.FFProbeAudioCacheDirectory, item.Id.ToString().Substring(0, 1)); + Fetch(audio, await FFProbe.Run(audio, GetFFProbeOutputPath(item)).ConfigureAwait(false)); + } - string outputPath = Path.Combine(outputDirectory, item.Id + "-" + item.DateModified.Ticks + ".js"); + private string GetFFProbeOutputPath(BaseEntity item) + { + string outputDirectory = Path.Combine(Kernel.Instance.ApplicationPaths.FFProbeAudioCacheDirectory, item.Id.ToString().Substring(0, 1)); - FFProbeResult data = await FFProbe.Run(audio, outputPath).ConfigureAwait(false); + return Path.Combine(outputDirectory, item.Id + "-" + item.DateModified.Ticks + ".js"); + } + private void Fetch(Audio audio, FFProbeResult data) + { MediaStream stream = data.streams.First(s => s.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase)); string bitrate = null; diff --git a/MediaBrowser.Controller/Providers/BaseMetadataProvider.cs b/MediaBrowser.Controller/Providers/BaseMetadataProvider.cs index 6222eec5f7..5c536913ec 100644 --- a/MediaBrowser.Controller/Providers/BaseMetadataProvider.cs +++ b/MediaBrowser.Controller/Providers/BaseMetadataProvider.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.Providers } } - public abstract Task Fetch(BaseEntity item, ItemResolveEventArgs args); + public abstract Task FetchAsync(BaseEntity item, ItemResolveEventArgs args); public abstract MetadataProviderPriority Priority { get; } } diff --git a/MediaBrowser.Controller/Providers/FolderProviderFromXml.cs b/MediaBrowser.Controller/Providers/FolderProviderFromXml.cs index cba41f780a..2249fb6a50 100644 --- a/MediaBrowser.Controller/Providers/FolderProviderFromXml.cs +++ b/MediaBrowser.Controller/Providers/FolderProviderFromXml.cs @@ -19,14 +19,16 @@ namespace MediaBrowser.Controller.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { var metadataFile = args.GetFileSystemEntryByName("folder.xml"); if (metadataFile.HasValue) { - await Task.Run(() => { new FolderXmlParser().Fetch(item as Folder, metadataFile.Value.Path); }).ConfigureAwait(false); + return Task.Run(() => { new FolderXmlParser().Fetch(item as Folder, metadataFile.Value.Path); }); } + + return Task.FromResult(null); } } } diff --git a/MediaBrowser.Controller/Providers/ImageFromMediaLocationProvider.cs b/MediaBrowser.Controller/Providers/ImageFromMediaLocationProvider.cs index 2a5e0394c4..59b58474fc 100644 --- a/MediaBrowser.Controller/Providers/ImageFromMediaLocationProvider.cs +++ b/MediaBrowser.Controller/Providers/ImageFromMediaLocationProvider.cs @@ -21,24 +21,23 @@ namespace MediaBrowser.Controller.Providers get { return MetadataProviderPriority.First; } } - public override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { - return Task.Run(() => + if (args.IsDirectory) { - if (args.IsDirectory) + var baseItem = item as BaseItem; + + if (baseItem != null) + { + return Task.Run(() => { PopulateImages(baseItem, args); }); + } + else { - var baseItem = item as BaseItem; - - if (baseItem != null) - { - PopulateImages(baseItem, args); - } - else - { - PopulateImages(item, args); - } + return Task.Run(() => { PopulateImages(item, args); }); } - }); + } + + return Task.FromResult(null); } /// @@ -49,7 +48,7 @@ namespace MediaBrowser.Controller.Providers for (int i = 0; i < args.FileSystemChildren.Length; i++) { var file = args.FileSystemChildren[i]; - + string filePath = file.Path; string ext = Path.GetExtension(filePath); diff --git a/MediaBrowser.Controller/Providers/LocalTrailerProvider.cs b/MediaBrowser.Controller/Providers/LocalTrailerProvider.cs index c023edb9af..18ca261dca 100644 --- a/MediaBrowser.Controller/Providers/LocalTrailerProvider.cs +++ b/MediaBrowser.Controller/Providers/LocalTrailerProvider.cs @@ -20,10 +20,8 @@ namespace MediaBrowser.Controller.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public async override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { - BaseItem baseItem = item as BaseItem; - var trailerPath = args.GetFileSystemEntryByName("trailers", true); if (trailerPath.HasValue) @@ -36,9 +34,7 @@ namespace MediaBrowser.Controller.Providers { string file = allFiles[i]; - BaseItem child = await Kernel.Instance.ItemController.GetItem(file).ConfigureAwait(false); - - Video video = child as Video; + Video video = await Kernel.Instance.ItemController.GetItem(file).ConfigureAwait(false) as Video; if (video != null) { @@ -46,7 +42,7 @@ namespace MediaBrowser.Controller.Providers } } - baseItem.LocalTrailers = localTrailers; + (item as BaseItem).LocalTrailers = localTrailers; } } } diff --git a/MediaBrowser.Controller/Providers/VideoInfoProvider.cs b/MediaBrowser.Controller/Providers/VideoInfoProvider.cs index 5f88aa1cbb..96ca8ed358 100644 --- a/MediaBrowser.Controller/Providers/VideoInfoProvider.cs +++ b/MediaBrowser.Controller/Providers/VideoInfoProvider.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.Providers get { return MetadataProviderPriority.Second; } } - public override async Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { Video video = item as Video; @@ -39,11 +39,14 @@ namespace MediaBrowser.Controller.Providers return; } - string outputDirectory = Path.Combine(Kernel.Instance.ApplicationPaths.FFProbeVideoCacheDirectory, item.Id.ToString().Substring(0, 1)); + Fetch(video, await FFProbe.Run(video, GetFFProbeOutputPath(video)).ConfigureAwait(false)); + } - string outputPath = Path.Combine(outputDirectory, item.Id + "-" + item.DateModified.Ticks + ".js"); + private string GetFFProbeOutputPath(Video item) + { + string outputDirectory = Path.Combine(Kernel.Instance.ApplicationPaths.FFProbeVideoCacheDirectory, item.Id.ToString().Substring(0, 1)); - FFProbeResult data = await FFProbe.Run(video, outputPath).ConfigureAwait(false); + return Path.Combine(outputDirectory, item.Id + "-" + item.DateModified.Ticks + ".js"); } private void Fetch(Video video, FFProbeResult data) diff --git a/MediaBrowser.Controller/Xml/BaseItemXmlParser.cs b/MediaBrowser.Controller/Xml/BaseItemXmlParser.cs index f5eecbcde9..d39ec60829 100644 --- a/MediaBrowser.Controller/Xml/BaseItemXmlParser.cs +++ b/MediaBrowser.Controller/Xml/BaseItemXmlParser.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Threading.Tasks; using System.Xml; using MediaBrowser.Model.Entities; diff --git a/MediaBrowser.Movies/Providers/MovieProviderFromXml.cs b/MediaBrowser.Movies/Providers/MovieProviderFromXml.cs index 8d7a9af7de..b977a46e72 100644 --- a/MediaBrowser.Movies/Providers/MovieProviderFromXml.cs +++ b/MediaBrowser.Movies/Providers/MovieProviderFromXml.cs @@ -21,14 +21,16 @@ namespace MediaBrowser.Movies.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { var metadataFile = args.GetFileSystemEntryByName("movie.xml"); if (metadataFile.HasValue) { - await Task.Run(() => { new BaseItemXmlParser().Fetch(item as Movie, metadataFile.Value.Path); }).ConfigureAwait(false); + return Task.Run(() => { new BaseItemXmlParser().Fetch(item as Movie, metadataFile.Value.Path); }); } + + return Task.FromResult(null); } } } diff --git a/MediaBrowser.TV/Providers/EpisodeImageFromMediaLocationProvider.cs b/MediaBrowser.TV/Providers/EpisodeImageFromMediaLocationProvider.cs index b98cee2efe..300adb7e1b 100644 --- a/MediaBrowser.TV/Providers/EpisodeImageFromMediaLocationProvider.cs +++ b/MediaBrowser.TV/Providers/EpisodeImageFromMediaLocationProvider.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel.Composition; +using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -23,7 +22,7 @@ namespace MediaBrowser.TV.Providers get { return MetadataProviderPriority.First; } } - public override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { return Task.Run(() => { diff --git a/MediaBrowser.TV/Providers/EpisodeProviderFromXml.cs b/MediaBrowser.TV/Providers/EpisodeProviderFromXml.cs index 077096859d..bab746e4b7 100644 --- a/MediaBrowser.TV/Providers/EpisodeProviderFromXml.cs +++ b/MediaBrowser.TV/Providers/EpisodeProviderFromXml.cs @@ -22,24 +22,21 @@ namespace MediaBrowser.TV.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { - await Task.Run(() => - { - string metadataFolder = Path.Combine(args.Parent.Path, "metadata"); - - Episode episode = item as Episode; - - string episodeFileName = Path.GetFileName(episode.Path); + return Fetch(item, args); + } - string metadataFile = Path.Combine(metadataFolder, Path.ChangeExtension(episodeFileName, ".xml")); + private Task Fetch(BaseEntity item, ItemResolveEventArgs args) + { + string metadataFolder = Path.Combine(args.Parent.Path, "metadata"); - FetchMetadata(episode, args.Parent as Season, metadataFile); + string metadataFile = Path.Combine(metadataFolder, Path.ChangeExtension(Path.GetFileName(args.Path), ".xml")); - }).ConfigureAwait(false); + return FetchMetadata(item as Episode, args.Parent as Season, metadataFile); } - private void FetchMetadata(Episode item, Season season, string metadataFile) + private Task FetchMetadata(Episode item, Season season, string metadataFile) { if (season == null) { @@ -47,18 +44,18 @@ namespace MediaBrowser.TV.Providers // Need to validate it the slow way if (!File.Exists(metadataFile)) { - return; + return Task.FromResult(null); } } else { if (!season.ContainsMetadataFile(metadataFile)) { - return; + return Task.FromResult(null); } } - new EpisodeXmlParser().Fetch(item, metadataFile); + return Task.Run(() => { new EpisodeXmlParser().Fetch(item, metadataFile); }); } } } diff --git a/MediaBrowser.TV/Providers/SeriesProviderFromXml.cs b/MediaBrowser.TV/Providers/SeriesProviderFromXml.cs index f28b0c1d02..d2f60461df 100644 --- a/MediaBrowser.TV/Providers/SeriesProviderFromXml.cs +++ b/MediaBrowser.TV/Providers/SeriesProviderFromXml.cs @@ -21,14 +21,16 @@ namespace MediaBrowser.TV.Providers get { return MetadataProviderPriority.First; } } - public async override Task Fetch(BaseEntity item, ItemResolveEventArgs args) + public override Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) { var metadataFile = args.GetFileSystemEntryByName("series.xml"); if (metadataFile.HasValue) { - await Task.Run(() => { new SeriesXmlParser().Fetch(item as Series, metadataFile.Value.Path); }).ConfigureAwait(false); + return Task.Run(() => { new SeriesXmlParser().Fetch(item as Series, metadataFile.Value.Path); }); } + + return Task.FromResult(null); } } }