Ejemplo n.º 1
0
        public void QueueItem(RequestedModel request, string id, RequestType type, FaultType faultType)
        {
            //Ensure there is not a duplicate queued item
            var existingItem = RequestQueue.Custom(
                connection =>
            {
                connection.Open();
                var result = connection.Query <RequestQueue>("select * from RequestQueue where PrimaryIdentifier = @ProviderId", new { ProviderId = id });

                return(result);
            }).FirstOrDefault();

            if (existingItem != null)
            {
                // It's already in the queue
                return;
            }

            var queue = new RequestQueue
            {
                Type              = type,
                Content           = ByteConverterHelper.ReturnBytes(request),
                PrimaryIdentifier = id,
                FaultType         = faultType
            };

            RequestQueue.Insert(queue);
        }
Ejemplo n.º 2
0
        public async Task QueueItemAsync(RequestedModel request, string id, RequestType type, FaultType faultType, string description = null)
        {
            //Ensure there is not a duplicate queued item
            var existingItem = await RequestQueue.CustomAsync(async connection =>
            {
                connection.Open();
                var result = await connection.QueryAsync <RequestQueue>("select * from RequestFaultQueue where PrimaryIdentifier = @ProviderId", new { ProviderId = id });

                return(result);
            });

            if (existingItem.FirstOrDefault() != null)
            {
                // It's already in the queue
                return;
            }

            var queue = new RequestQueue
            {
                Type              = type,
                Content           = ByteConverterHelper.ReturnBytes(request),
                PrimaryIdentifier = id,
                FaultType         = faultType,
                Message           = description ?? string.Empty
            };
            await RequestQueue.InsertAsync(queue);
        }
Ejemplo n.º 3
0
        public async Task <bool> UpdateRequestAsync(RequestedModel model)
        {
            var entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId, Id = model.Id
            };

            return(await Repo.UpdateAsync(entity).ConfigureAwait(false));
        }
Ejemplo n.º 4
0
        public async Task DeleteIssueAsync(IssuesModel model)
        {
            var entity = new IssueBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), RequestId = model.RequestId, Id = model.Id
            };

            await Repo.DeleteAsync(entity).ConfigureAwait(false);
        }
Ejemplo n.º 5
0
        public bool BatchUpdate(List <RequestedModel> model)
        {
            var entities = model.Select(m => new RequestBlobs {
                Type = m.Type, Content = ByteConverterHelper.ReturnBytes(m), ProviderId = m.ProviderId, Id = m.Id
            }).ToList();

            return(Repo.UpdateAll(entities));
        }
Ejemplo n.º 6
0
        public bool UpdateRequest(RequestedModel model)
        {
            var entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId, Id = model.Id
            };

            return(Repo.Update(entity));
        }
Ejemplo n.º 7
0
        public async Task <bool> BatchDeleteAsync(IEnumerable <RequestedModel> model)
        {
            var entities = model.Select(m => new RequestBlobs {
                Type = m.Type, Content = ByteConverterHelper.ReturnBytes(m), ProviderId = m.ProviderId, Id = m.Id
            }).ToList();

            return(await Repo.DeleteAllAsync(entities).ConfigureAwait(false));
        }
Ejemplo n.º 8
0
        private void ProcessMissingInformation(List <RequestQueue> requests)
        {
            if (!requests.Any())
            {
                return;
            }

            var sonarrSettings   = SonarrSettings.GetSettings();
            var sickrageSettings = SickrageSettings.GetSettings();

            var tv = requests.Where(x => x.Type == RequestType.TvShow);

            // TV
            var tvApi = new TvMazeApi();

            foreach (var t in tv)
            {
                var providerId = int.Parse(t.PrimaryIdentifier);
                var showInfo   = tvApi.ShowLookup(providerId);

                if (showInfo.externals?.thetvdb != null)
                {
                    // We now have the info
                    var tvModel = ByteConverterHelper.ReturnObject <RequestedModel>(t.Content);
                    tvModel.ProviderId = showInfo.externals.thetvdb.Value;
                    var result = ProcessTvShow(tvModel, sonarrSettings, sickrageSettings);

                    if (!result)
                    {
                        // we now have the info but couldn't add it, so add it back into the queue but with a different fault
                        t.Content   = ByteConverterHelper.ReturnBytes(tvModel);
                        t.FaultType = FaultType.RequestFault;
                        t.LastRetry = DateTime.UtcNow;
                        Repo.Update(t);
                    }
                    else
                    {
                        // Make sure it's been requested
                        var existingRequests = RequestService.GetAll();
                        var thisItem         = existingRequests.Any(x => x.Title.Equals(tvModel.Title));
                        if (!thisItem)
                        {
                            tvModel.Approved = true;
                            RequestService.AddRequest(tvModel);
                        }

                        // Successful, remove from the fault queue
                        Repo.Delete(t);
                    }
                }
            }
        }
        private Response UpdateUser()
        {
            var body = Request.Body.AsString();

            if (string.IsNullOrEmpty(body))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Could not save user, invalid JSON body"
                }));
            }

            var model = JsonConvert.DeserializeObject <UserManagementUpdateModel>(body);

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = true,
                    Message = "Couldn't find the user"
                }));
            }

            var claims = new List <string>();

            foreach (var c in model.Claims)
            {
                if (c.Selected)
                {
                    claims.Add(c.Name);
                }
            }

            var userFound = UserMapper.GetUser(new Guid(model.Id));

            userFound.Claims = ByteConverterHelper.ReturnBytes(claims.ToArray());
            var currentProps = ByteConverterHelper.ReturnObject <UserProperties>(userFound.UserProperties);

            currentProps.UserAlias    = model.Alias;
            currentProps.EmailAddress = model.EmailAddress;

            userFound.UserProperties = ByteConverterHelper.ReturnBytes(currentProps);

            var user    = UserMapper.EditUser(userFound);
            var dbUser  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == user.UserGuid);
            var retUser = MapLocalUser(user, dbUser?.LastLoggedIn ?? DateTime.MinValue);

            return(Response.AsJson(retUser));
        }
Ejemplo n.º 10
0
        public async Task <int> AddRequestAsync(RequestedModel model)
        {
            var entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId
            };
            var id = await Repo.InsertAsync(entity).ConfigureAwait(false);

            model.Id = id;

            entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId, Id = id, MusicId = model.MusicBrainzId
            };
            var result = await Repo.UpdateAsync(entity).ConfigureAwait(false);

            return(result ? id : -1);
        }
Ejemplo n.º 11
0
        public async Task <int> AddIssueAsync(IssuesModel model)
        {
            var entity = new IssueBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), RequestId = model.RequestId
            };
            var id = await Repo.InsertAsync(entity);

            model.Id = id;

            entity = new IssueBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), RequestId = model.RequestId, Id = id
            };
            var result = await Repo.UpdateAsync(entity).ConfigureAwait(false);

            return(result ? id : -1);
        }
Ejemplo n.º 12
0
        public long AddRequest(RequestedModel model)
        {
            var entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId
            };
            var id = Repo.Insert(entity);

            model.Id = (int)id;

            entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId, Id = (int)id, MusicId = model.MusicBrainzId
            };
            var result = Repo.Update(entity);

            return(result ? id : -1);
        }
Ejemplo n.º 13
0
        public long AddRequest(RequestedModel model)
        {
            var entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId
            };
            var id = Repo.Insert(entity);

            // TODO Keep an eye on this, since we are now doing 2 DB update for 1 single request, inserting and then updating
            model.Id = (int)id;

            entity = new RequestBlobs {
                Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId, Id = (int)id, MusicId = model.MusicBrainzId
            };
            var result = Repo.Update(entity);

            return(result ? id : -1);
        }
Ejemplo n.º 14
0
        public Guid?CreateUser(string username, string password, UserProperties properties = null)
        {
            var salt = PasswordHasher.GenerateSalt();

            var userModel = new UsersModel
            {
                UserName       = username,
                UserGuid       = Guid.NewGuid().ToString(),
                Salt           = salt,
                Hash           = PasswordHasher.ComputeHash(password, salt),
                Claims         = new byte[] { 0 },
                UserProperties = ByteConverterHelper.ReturnBytes(properties ?? new UserProperties()),
            };

            Repo.Insert(userModel);
            var userRecord = Repo.Get(userModel.UserGuid);

            return(new Guid(userRecord.UserGuid));
        }
Ejemplo n.º 15
0
        private Guid?CreateUser(string username, string password, string[] claims = default(string[]))
        {
            var salt = PasswordHasher.GenerateSalt();

            var userModel = new UsersModel
            {
                UserName       = username,
                UserGuid       = Guid.NewGuid().ToString(),
                Salt           = salt,
                Hash           = PasswordHasher.ComputeHash(password, salt),
                Claims         = ByteConverterHelper.ReturnBytes(claims),
                UserProperties = ByteConverterHelper.ReturnBytes(new UserProperties())
            };

            Repo.Insert(userModel);

            var userRecord = Repo.Get(userModel.UserGuid);

            return(new Guid(userRecord.UserGuid));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Migrates to version 1.8.
        /// <para>This includes updating the admin account to have all roles.</para>
        /// <para>Set the log level to info</para>
        /// </summary>
        private void MigrateToVersion1800()
        {
            try
            {
                var userMapper = new UserMapper(new UserRepository <UsersModel>(Db, new MemoryCacheProvider()));
                var users      = userMapper.GetUsers();

                foreach (var u in users)
                {
                    var claims = new[] { UserClaims.User, UserClaims.Admin, UserClaims.PowerUser };
                    u.Claims = ByteConverterHelper.ReturnBytes(claims);

                    userMapper.EditUser(u);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }

            try
            {
                var settingsService = new SettingsServiceV2 <LogSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
                var logSettings     = settingsService.GetSettings();
                logSettings.Level = LogLevel.Info.Ordinal;
                settingsService.SaveSettings(logSettings);

                LoggingHelper.ReconfigureLogLevel(LogLevel.FromOrdinal(logSettings.Level));
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
Ejemplo n.º 17
0
        private List <PlexSearch> CachedLibraries(PlexSettings plexSettings)
        {
            var results = new List <PlexSearch>();

            if (!ValidateSettings(plexSettings))
            {
                Log.Warn("The settings are not configured");
                return(results); // don't error out here, just let it go! let it goo!!!
            }

            try
            {
                results = GetLibraries(plexSettings);
                if (plexSettings.AdvancedSearch)
                {
                    foreach (PlexSearch t in results)
                    {
                        foreach (Directory1 t1 in t.Directory)
                        {
                            var currentItem = t1;
                            var metaData    = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                  currentItem.RatingKey);

                            // Get the seasons for each show
                            if (currentItem.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase))
                            {
                                var seasons = PlexApi.GetSeasons(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                 currentItem.RatingKey);

                                // We do not want "all episodes" this as a season
                                var filtered = seasons.Directory.Where(x => !x.Title.Equals("All episodes", StringComparison.CurrentCultureIgnoreCase));

                                t1.Seasons.AddRange(filtered);
                            }

                            var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid);
                            t1.ProviderId = providerId;
                        }
                        foreach (Video t1 in t.Video)
                        {
                            var currentItem = t1;
                            var metaData    = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                  currentItem.RatingKey);
                            var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid);
                            t1.ProviderId = providerId;
                        }
                    }
                }
                if (results != null)
                {
                    var movies = GetPlexMovies(results);

                    // Time to destroy the plex movies from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 0 });
                        return(new List <PlexContent>());
                    });

                    foreach (var m in movies)
                    {
                        PlexContent.Insert(new PlexContent
                        {
                            ProviderId  = m.ProviderId,
                            ReleaseYear = m.ReleaseYear ?? string.Empty,
                            Title       = m.Title,
                            Type        = Store.Models.Plex.PlexMediaType.Movie,
                            Url         = m.Url
                        });
                    }
                    var tv = GetPlexTvShows(results);
                    // Time to destroy the plex tv from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 1 });
                        return(new List <PlexContent>());
                    });
                    foreach (var t in tv)
                    {
                        PlexContent.Insert(new PlexContent
                        {
                            ProviderId  = t.ProviderId,
                            ReleaseYear = t.ReleaseYear ?? string.Empty,
                            Title       = t.Title,
                            Type        = Store.Models.Plex.PlexMediaType.Show,
                            Url         = t.Url,
                            Seasons     = ByteConverterHelper.ReturnBytes(t.Seasons)
                        });
                    }

                    var albums = GetPlexAlbums(results);
                    // Time to destroy the plex movies from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 2 });
                        return(new List <PlexContent>());
                    });
                    foreach (var a in albums)
                    {
                        PlexContent.Insert(new PlexContent
                        {
                            ProviderId  = a.ProviderId,
                            ReleaseYear = a.ReleaseYear ?? string.Empty,
                            Title       = a.Title,
                            Type        = Store.Models.Plex.PlexMediaType.Artist,
                            Url         = a.Url
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to obtain Plex libraries");
            }

            return(results);
        }
Ejemplo n.º 18
0
        private List <PlexSearch> CachedLibraries(PlexSettings plexSettings)
        {
            var results = new List <PlexSearch>();

            if (!ValidateSettings(plexSettings))
            {
                Log.Warn("The settings are not configured");
                return(results); // don't error out here, just let it go! let it goo!!!
            }

            try
            {
                results = GetLibraries(plexSettings);
                if (plexSettings.AdvancedSearch)
                {
                    Log.Debug("Going through all the items now");
                    Log.Debug($"Item count {results.Count}");
                    foreach (PlexSearch t in results)
                    {
                        foreach (Directory1 t1 in t.Directory)
                        {
                            var currentItem = t1;
                            var metaData    = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                  currentItem.RatingKey);

                            // Get the seasons for each show
                            if (currentItem.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase))
                            {
                                var seasons = PlexApi.GetSeasons(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                 currentItem.RatingKey);

                                // We do not want "all episodes" this as a season
                                var filtered = seasons.Directory.Where(x => !x.Title.Equals("All episodes", StringComparison.CurrentCultureIgnoreCase));

                                t1.Seasons.AddRange(filtered);
                            }

                            var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid);
                            t1.ProviderId = providerId;
                        }
                        foreach (Video t1 in t.Video)
                        {
                            var currentItem = t1;
                            var metaData    = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                                  currentItem.RatingKey);
                            var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid);
                            t1.ProviderId = providerId;
                        }
                    }
                }
                if (results != null)
                {
                    Log.Debug("done all that, moving onto the DB now");
                    var movies = GetPlexMovies(results);

                    // Time to destroy the plex movies from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 0 });
                        return(new List <PlexContent>());
                    });

                    foreach (var m in movies)
                    {
                        if (string.IsNullOrEmpty(m.ProviderId))
                        {
                            Log.Error("Provider Id on movie {0} is null", m.Title);
                            continue;
                        }

                        // Check if it exists
                        var item = PlexContent.Custom(connection =>
                        {
                            connection.Open();
                            var media = connection.QueryFirstOrDefault <PlexContent>("select * from PlexContent where ProviderId = @ProviderId and type = @type", new { m.ProviderId, type = 0 });
                            connection.Dispose();
                            return(media);
                        });

                        if (item == null && !string.IsNullOrEmpty(m.ItemId))
                        {
                            // Doesn't exist, insert it
                            PlexContent.Insert(new PlexContent
                            {
                                ProviderId  = m.ProviderId,
                                ReleaseYear = m.ReleaseYear ?? string.Empty,
                                Title       = m.Title,
                                Type        = Store.Models.Plex.PlexMediaType.Movie,
                                Url         = m.Url,
                                ItemId      = m.ItemId,
                                AddedAt     = DateTime.UtcNow,
                            });
                        }
                    }

                    Log.Debug("Done movies");
                    var tv = GetPlexTvShows(results);
                    // Time to destroy the plex tv from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 1 });
                        return(new List <PlexContent>());
                    });
                    foreach (var t in tv)
                    {
                        if (string.IsNullOrEmpty(t.ProviderId))
                        {
                            Log.Error("Provider Id on tv {0} is null", t.Title);
                            continue;
                        }


                        // Check if it exists
                        var item = PlexContent.Custom(connection =>
                        {
                            connection.Open();
                            var media = connection.QueryFirstOrDefault <PlexContent>("select * from PlexContent where ProviderId = @ProviderId and type = @type", new { t.ProviderId, type = 1 });
                            connection.Dispose();
                            return(media);
                        });

                        if (item == null && !string.IsNullOrEmpty(t.ItemId))
                        {
                            PlexContent.Insert(new PlexContent
                            {
                                ProviderId  = t.ProviderId,
                                ReleaseYear = t.ReleaseYear ?? string.Empty,
                                Title       = t.Title,
                                Type        = Store.Models.Plex.PlexMediaType.Show,
                                Url         = t.Url,
                                Seasons     = ByteConverterHelper.ReturnBytes(t.Seasons),
                                ItemId      = t.ItemId,
                                AddedAt     = DateTime.UtcNow,
                            });
                        }
                    }
                    Log.Debug("Done TV");
                    var albums = GetPlexAlbums(results);
                    // Time to destroy the plex movies from the DB
                    PlexContent.Custom(connection =>
                    {
                        connection.Open();
                        connection.Query("delete from PlexContent where type = @type", new { type = 2 });
                        return(new List <PlexContent>());
                    });

                    foreach (var a in albums)
                    {
                        if (string.IsNullOrEmpty(a.ProviderId))
                        {
                            Log.Error("Provider Id on album {0} is null", a.Title);
                            continue;
                        }


                        // Check if it exists
                        var item = PlexContent.Custom(connection =>
                        {
                            connection.Open();
                            var media = connection.QueryFirstOrDefault <PlexContent>("select * from PlexContent where ProviderId = @ProviderId and type = @type", new { a.ProviderId, type = 2 });
                            connection.Dispose();
                            return(media);
                        });

                        if (item == null)
                        {
                            PlexContent.Insert(new PlexContent
                            {
                                ProviderId  = a.ProviderId,
                                ReleaseYear = a.ReleaseYear ?? string.Empty,
                                Title       = a.Title,
                                Type        = Store.Models.Plex.PlexMediaType.Artist,
                                Url         = a.Url,
                                ItemId      = "album",
                                AddedAt     = DateTime.UtcNow,
                            });
                        }
                    }
                    Log.Debug("Done albums");
                }
            }
            catch (Exception ex)
            {
                Log.Debug("Exception:");
                Log.Debug(ex);
                Log.Error(ex, "Failed to obtain Plex libraries");
            }

            return(results);
        }
Ejemplo n.º 19
0
        private async Task <Response> UpdateUser()
        {
            Analytics.TrackEventAsync(Category.UserManagement, Action.Update, "Updated User", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var body = Request.Body.AsString();

            if (string.IsNullOrEmpty(body))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Could not save user, invalid JSON body"
                }));
            }

            var model = JsonConvert.DeserializeObject <UserManagementUpdateModel>(body);

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = true,
                    Message = "Couldn't find the user"
                }));
            }

            var permissionsValue = model.Permissions.Where(c => c.Selected).Sum(c => c.Value);
            var featuresValue    = model.Features.Where(c => c.Selected).Sum(c => c.Value);

            Guid outId;

            Guid.TryParse(model.Id, out outId);
            var localUser = UserMapper.GetUser(outId);

            // Update Local User
            if (localUser != null)
            {
                localUser.Permissions = permissionsValue;
                localUser.Features    = featuresValue;

                var currentProps = ByteConverterHelper.ReturnObject <UserProperties>(localUser.UserProperties);

                // Let's check if the alias has changed, if so we need to change all the requests associated with this
                await UpdateRequests(localUser.UserName, currentProps.UserAlias, model.Alias);

                currentProps.UserAlias    = model.Alias;
                currentProps.EmailAddress = model.EmailAddress;

                localUser.UserProperties = ByteConverterHelper.ReturnBytes(currentProps);

                var user    = UserMapper.EditUser(localUser);
                var dbUser  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == user.UserGuid);
                var retUser = MapLocalUser(user, dbUser?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            var plexDbUsers = await PlexUsersRepository.GetAllAsync();

            var plexUsers  = PlexApi.GetUsers(plexSettings.PlexAuthToken);
            var plexDbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == model.Id);
            var plexUser   = plexUsers.User.FirstOrDefault(x => x.Id == model.Id);
            var userLogin  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == model.Id);

            if (plexDbUser != null && plexUser != null)
            {
                // We have a user in the DB for this Plex Account
                plexDbUser.Permissions = permissionsValue;
                plexDbUser.Features    = featuresValue;

                await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                plexDbUser.UserAlias    = model.Alias;
                plexDbUser.EmailAddress = model.EmailAddress;

                await PlexUsersRepository.UpdateAsync(plexDbUser);

                var retUser = MapPlexUser(plexUser, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            // So it could actually be the admin
            var account = PlexApi.GetAccount(plexSettings.PlexAuthToken);

            if (plexDbUser != null && account != null)
            {
                // We have a user in the DB for this Plex Account
                plexDbUser.Permissions = permissionsValue;
                plexDbUser.Features    = featuresValue;

                await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                plexDbUser.UserAlias = model.Alias;

                await PlexUsersRepository.UpdateAsync(plexDbUser);

                var retUser = MapPlexAdmin(account, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            // We have a Plex Account but he's not in the DB
            if (plexUser != null)
            {
                var user = new PlexUsers
                {
                    Permissions  = permissionsValue,
                    Features     = featuresValue,
                    UserAlias    = model.Alias,
                    PlexUserId   = plexUser.Id,
                    EmailAddress = plexUser.Email,
                    Username     = plexUser.Title,
                    LoginId      = Guid.NewGuid().ToString()
                };

                await PlexUsersRepository.InsertAsync(user);

                var retUser = MapPlexUser(plexUser, user, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }
            return(null); // We should never end up here.
        }