diff --git a/Ombi.Api/ApiRequest.cs b/Ombi.Api/ApiRequest.cs index 2de72101d..c399eae45 100644 --- a/Ombi.Api/ApiRequest.cs +++ b/Ombi.Api/ApiRequest.cs @@ -56,65 +56,46 @@ namespace Ombi.Api public T Execute(IRestRequest request, Uri baseUri) where T : new() { var client = new RestClient { BaseUrl = baseUri }; - var response = client.Execute(request); - Log.Trace("Api Content Response:"); - Log.Trace(response.Content); - + Log.Trace($"Request made to {response.ResponseUri} with status code {response.StatusCode}. The response was {response.Content}"); - if (response.ErrorException != null) - { - var message = "Error retrieving response. Check inner details for more info."; - Log.Error(response.ErrorException); - throw new ApiRequestException(message, response.ErrorException); - } + if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) + return response.Data; + else + throw new ApiRequestException($"Got StatusCode={response.StatusCode} for {response.ResponseUri}."); - return response.Data; } public IRestResponse Execute(IRestRequest request, Uri baseUri) { var client = new RestClient { BaseUrl = baseUri }; - var response = client.Execute(request); - return response; } public T ExecuteXml(IRestRequest request, Uri baseUri) where T : class { var client = new RestClient { BaseUrl = baseUri }; - var response = client.Execute(request); + Log.Trace($"Request made to {response.ResponseUri} with status code {response.StatusCode}. The response was {response.Content}"); - if (response.ErrorException != null) - { - Log.Error(response.ErrorException); - var message = "Error retrieving response. Check inner details for more info."; - throw new ApiRequestException(message, response.ErrorException); - } + if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) + return DeserializeXml(response.Content); + else + throw new ApiRequestException($"Got StatusCode={response.StatusCode} for {response.ResponseUri}."); - var result = DeserializeXml(response.Content); - return result;} + } public T ExecuteJson(IRestRequest request, Uri baseUri) where T : new() { var client = new RestClient { BaseUrl = baseUri }; var response = client.Execute(request); - Log.Trace("Api Content Response:"); - Log.Trace(response.Content); - if (response.ErrorException != null) - { - Log.Error(response.ErrorException); - var message = "Error retrieving response. Check inner details for more info."; - throw new ApiRequestException(message, response.ErrorException); - } - - Log.Trace("Deserialzing Object"); - var json = JsonConvert.DeserializeObject(response.Content, _settings); - Log.Trace("Finished Deserialzing Object"); + Log.Trace($"Request made to {response.ResponseUri} with status code {response.StatusCode}. The response was {response.Content}"); - return json; + if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) + return JsonConvert.DeserializeObject(response.Content, _settings); + else + throw new ApiRequestException($"Got StatusCode={response.StatusCode} for {response.ResponseUri}."); } private T DeserializeXml(string input) diff --git a/Ombi.Core/HeadphonesSender.cs b/Ombi.Core/HeadphonesSender.cs index 043ea4e2a..c96fefa06 100644 --- a/Ombi.Core/HeadphonesSender.cs +++ b/Ombi.Core/HeadphonesSender.cs @@ -79,7 +79,7 @@ namespace Ombi.Core request.Approved = true; // Update the record - var updated = RequestService.UpdateRequest(request); + bool updated = RequestService.UpdateRequest(request); return updated; } @@ -88,87 +88,20 @@ namespace Ombi.Core { var index = await Api.GetIndex(Settings.ApiKey, Settings.FullUri); var artistExists = index.Any(x => x.ArtistID == request.ArtistId); + bool artistAdd = false; if (!artistExists) { - var artistAdd = Api.AddArtist(Settings.ApiKey, Settings.FullUri, request.ArtistId); - Log.Info("Artist add result : {0}", artistAdd); + artistAdd = await Api.AddArtist(Settings.ApiKey, Settings.FullUri, request.ArtistId); + Log.Info("Artist add result for {1}: {0}", artistAdd, request.ArtistName); } - var counter = 0; - while (index.All(x => x.ArtistID != request.ArtistId)) - { - Thread.Sleep(WaitTime); - counter++; - Log.Trace("Artist is still not present in the index. Counter = {0}", counter); - index = await Api.GetIndex(Settings.ApiKey, Settings.FullUri); - - if (counter > CounterMax) - { - Log.Trace("Artist is still not present in the index. Counter = {0}. Returning false", counter); - Log.Warn("We have tried adding the artist but it seems they are still not in headphones."); - return false; - } - } - - counter = 0; - var artistStatus = index.Where(x => x.ArtistID == request.ArtistId).Select(x => x.Status).FirstOrDefault(); - while (artistStatus != "Active") - { - Thread.Sleep(WaitTime); - counter++; - Log.Trace("Artist status {1}. Counter = {0}", counter, artistStatus); - index = await Api.GetIndex(Settings.ApiKey, Settings.FullUri); - artistStatus = index.Where(x => x.ArtistID == request.ArtistId).Select(x => x.Status).FirstOrDefault(); - if (counter > CounterMax) - { - Log.Trace("Artist status is still not active. Counter = {0}. Returning false", counter); - Log.Warn("The artist status is still not Active. We have waited long enough, seems to be a big delay in headphones."); - return false; - } - } - - var addedArtist = index.FirstOrDefault(x => x.ArtistID == request.ArtistId); - var artistName = addedArtist?.ArtistName ?? string.Empty; - counter = 0; - while (artistName.Contains("Fetch failed")) - { - Thread.Sleep(WaitTime); - await Api.RefreshArtist(Settings.ApiKey, Settings.FullUri, request.ArtistId); - - index = await Api.GetIndex(Settings.ApiKey, Settings.FullUri); - - artistName = index?.FirstOrDefault(x => x.ArtistID == request.ArtistId)?.ArtistName ?? string.Empty; - counter++; - if (counter > CounterMax) - { - Log.Trace("Artist fetch has failed. Counter = {0}. Returning false", counter); - Log.Warn("Artist in headphones fetch has failed, we have tried refreshing the artist but no luck."); - return false; - } - } - - return true; + return artistExists || artistAdd; } private async Task SetAlbumStatus(RequestedModel request) { - var counter = 0; - var setStatus = await Api.QueueAlbum(Settings.ApiKey, Settings.FullUri, request.MusicBrainzId); - - while (!setStatus) - { - Thread.Sleep(WaitTime); - counter++; - Log.Trace("Setting Album status. Counter = {0}", counter); - setStatus = await Api.QueueAlbum(Settings.ApiKey, Settings.FullUri, request.MusicBrainzId); - if (counter > CounterMax) - { - Log.Trace("Album status is still not active. Counter = {0}. Returning false", counter); - Log.Warn("We tried to se the status for the album but headphones didn't want to snatch it."); - return false; - } - } - return true; + bool setStatus = await Api.QueueAlbum(Settings.ApiKey, Settings.FullUri, request.ReleaseId); + return setStatus; } } } \ No newline at end of file diff --git a/Ombi.UI/Modules/UserLoginModule.cs b/Ombi.UI/Modules/UserLoginModule.cs index 1fd82cb2e..cd234ca57 100644 --- a/Ombi.UI/Modules/UserLoginModule.cs +++ b/Ombi.UI/Modules/UserLoginModule.cs @@ -65,7 +65,7 @@ namespace Ombi.UI.Modules AuthService = auth; LandingPageSettings = lp; Analytics = a; - Api = api; + PlexApi = api; PlexSettings = plexSettings; Linker = linker; UserLogins = userLogins; @@ -126,7 +126,7 @@ namespace Ombi.UI.Modules private ISettingsService LandingPageSettings { get; } private ISettingsService PlexSettings { get; } private ISettingsService EmbySettings { get; } - private IPlexApi Api { get; } + private IPlexApi PlexApi { get; } private IEmbyApi EmbyApi { get; } private IResourceLinker Linker { get; } private IAnalytics Analytics { get; } @@ -301,12 +301,18 @@ namespace Ombi.UI.Modules var plexSettings = await PlexSettings.GetSettingsAsync(); var embySettings = await EmbySettings.GetSettingsAsync(); - if (plexSettings.Enable) + // attempt local login first as it has the least amount of overhead + userId = CustomUserMapper.ValidateUser(username, password)?.ToString(); + if (userId != null) + { + authenticated = true; + } + else if (userId == null && plexSettings.Enable) { if (settings.UserAuthentication) // Authenticate with Plex { Log.Debug("Need to auth and also provide pass"); - var signedIn = (PlexAuthentication) Api.SignIn(username, password); + var signedIn = (PlexAuthentication) PlexApi.SignIn(username, password); if (signedIn.user?.authentication_token != null) { Log.Debug("Correct credentials, checking if the user is account owner or in the friends list"); @@ -325,9 +331,9 @@ namespace Ombi.UI.Modules } } } - if (embySettings.Enable) + else if (userId == null && embySettings.Enable) { - if (settings.UserAuthentication) // Authenticate with Plex + if (settings.UserAuthentication) // Authenticate with Emby { Log.Debug("Need to auth and also provide pass"); EmbyUser signedIn = null; @@ -358,22 +364,11 @@ namespace Ombi.UI.Modules } } - if (string.IsNullOrEmpty(userId)) - { - // Local user? - userId = CustomUserMapper.ValidateUser(username, password)?.ToString(); - if (userId != null) - { - authenticated = true; - } - } - if (!authenticated) { return Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }); } - var m = await AuthenticationSetup(userId, username, dateTimeOffset, loginGuid, isOwner, plexSettings.Enable, embySettings.Enable); var landingSettings = await LandingPageSettings.GetSettingsAsync(); @@ -397,7 +392,6 @@ namespace Ombi.UI.Modules return CustomModuleExtensions.LoginAndRedirect(this, m.LoginGuid, null, retVal.ToString()); } return Response.AsJson(new { result = true, url = retVal.ToString() }); - } private async Task LoginUser() @@ -442,7 +436,7 @@ namespace Ombi.UI.Modules if (settings.UserAuthentication && settings.UsePassword) // Authenticate with Plex { Log.Debug("Need to auth and also provide pass"); - var signedIn = (PlexAuthentication)Api.SignIn(username, password); + var signedIn = (PlexAuthentication)PlexApi.SignIn(username, password); if (signedIn.user?.authentication_token != null) { Log.Debug("Correct credentials, checking if the user is account owner or in the friends list"); @@ -713,7 +707,7 @@ namespace Ombi.UI.Modules private bool CheckIfUserIsOwner(string authToken, string userName) { - var userAccount = Api.GetAccount(authToken); + var userAccount = PlexApi.GetAccount(authToken); if (userAccount == null) { return false; @@ -723,7 +717,7 @@ namespace Ombi.UI.Modules private string GetOwnerId(string authToken, string userName) { - var userAccount = Api.GetAccount(authToken); + var userAccount = PlexApi.GetAccount(authToken); if (userAccount == null) { return string.Empty; @@ -733,7 +727,7 @@ namespace Ombi.UI.Modules private bool CheckIfUserIsInPlexFriends(string username, string authToken) { - var users = Api.GetUsers(authToken); + var users = PlexApi.GetUsers(authToken); var allUsers = users?.User?.Where(x => !string.IsNullOrEmpty(x.Title)); return allUsers != null && allUsers.Any(x => x.Title.Equals(username, StringComparison.CurrentCultureIgnoreCase)); } @@ -771,7 +765,7 @@ namespace Ombi.UI.Modules private string GetUserIdIsInPlexFriends(string username, string authToken) { - var users = Api.GetUsers(authToken); + var users = PlexApi.GetUsers(authToken); var allUsers = users?.User?.Where(x => !string.IsNullOrEmpty(x.Title)); return allUsers?.Where(x => x.Title.Equals(username, StringComparison.CurrentCultureIgnoreCase)).Select(x => x.Id).FirstOrDefault(); } diff --git a/Ombi.UI/Program.cs b/Ombi.UI/Program.cs index b454550c5..2dc1ef5a8 100644 --- a/Ombi.UI/Program.cs +++ b/Ombi.UI/Program.cs @@ -75,7 +75,7 @@ namespace Ombi.UI var s = new Setup(); var cn = s.SetupDb(baseUrl); s.CacheQualityProfiles(); - ConfigureTargets(cn); + ConfigureTargets(cn); SetupLogging(); if (port == -1 || port == 3579) @@ -110,7 +110,7 @@ namespace Ombi.UI { Log.Info("This is not Mono"); Console.WriteLine("Press any key to exit"); - Console.ReadLine(); + Console.ReadLine(); } } }