Exemplo n.º 1
0
        private string GetUserIdIsInPlexFriends(string username, string 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());
        }
Exemplo n.º 2
0
        private bool CheckIfUserIsInPlexFriends(string username, string 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)));
        }
Exemplo n.º 3
0
        private Response GetUsers()
        {
            var settings = AuthService.GetSettings();

            var token = settings?.PlexAuthToken;

            if (token == null)
            {
                return(Response.AsJson(new { Result = true, Users = string.Empty }));
            }

            try {
                var users = PlexApi.GetUsers(token);
                if (users == null)
                {
                    return(Response.AsJson(string.Empty));
                }
                if (users.User == null || users.User?.Length == 0)
                {
                    return(Response.AsJson(string.Empty));
                }

                var usernames = users.User.Select(x => x.Title);
                return(Response.AsJson(new { Result = true, Users = usernames }));
            } catch (Exception ex) {
                Log.Error(ex);
                if (ex is WebException || ex is ApiRequestException)
                {
                    return(Response.AsJson(new { Result = false, Message = "Could not load the user list! We have connectivity problems connecting to Plex, Please ensure we can access Plex.Tv, The error has been logged." }));
                }

                return(Response.AsJson(new { Result = false, Message = ex.Message }));
            }
        }
        private Response GetUsers()
        {
            var settings = AuthService.GetSettings();

            var token = settings?.PlexAuthToken;

            if (token == null)
            {
                return(Response.AsJson(string.Empty));
            }

            var users = PlexApi.GetUsers(token);

            if (users == null)
            {
                return(Response.AsJson(string.Empty));
            }
            if (users.User == null || users.User?.Length == 0)
            {
                return(Response.AsJson(string.Empty));
            }

            var usernames = users.User.Select(x => x.Username);

            return(Response.AsJson(usernames));
        }
Exemplo n.º 5
0
        public async Task NotifyUsers(IEnumerable <RequestedModel> modelChanged, string apiKey, NotificationType type)
        {
            try
            {
                var plexUser    = PlexApi.GetUsers(apiKey);
                var userAccount = PlexApi.GetAccount(apiKey);

                var adminUsername = userAccount.Username ?? string.Empty;

                var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList();
                Log.Debug("Notifying Users Count {0}", users.Count);
                foreach (var model in modelChanged)
                {
                    var selectedUsers = new List <string>();

                    foreach (var u in users)
                    {
                        var requestUser = model.RequestedUsers.FirstOrDefault(
                            x => x.Equals(u.Username, StringComparison.CurrentCultureIgnoreCase) || x.Equals(u.UserAlias, StringComparison.CurrentCultureIgnoreCase));
                        if (string.IsNullOrEmpty(requestUser))
                        {
                            continue;
                        }

                        selectedUsers.Add(requestUser);
                    }

                    //var selectedUsers = users.Select(x => x.Username).Intersect(model.RequestedUsers, StringComparer.CurrentCultureIgnoreCase);
                    foreach (var user in selectedUsers)
                    {
                        Log.Info("Notifying user {0}", user);
                        if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
                        {
                            Log.Info("This user is the Plex server owner");
                            await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath, type);

                            return;
                        }

                        var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
                        if (string.IsNullOrEmpty(email?.Email))
                        {
                            Log.Info("There is no email address for this Plex user, cannot send notification");
                            // We do not have a plex user that requested this!
                            continue;
                        }

                        Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Username, email.Email, model.Title);
                        await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath, type);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Exemplo n.º 6
0
        private async Task <Response> LoadUsers()
        {
            var localUsers = await UserMapper.GetUsersAsync();

            var plexDbUsers = await PlexUsersRepository.GetAllAsync();

            var model = new List <UserManagementUsersViewModel>();

            var userLogins = UserLoginsRepo.GetAll().ToList();

            foreach (var user in localUsers)
            {
                var userDb = userLogins.FirstOrDefault(x => x.UserId == user.UserGuid);
                model.Add(MapLocalUser(user, userDb?.LastLoggedIn ?? DateTime.MinValue));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);
                if (plexUsers != null && plexUsers.User != null)
                {
                    foreach (var u in plexUsers.User)
                    {
                        var dbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == u.Id);
                        var userDb = userLogins.FirstOrDefault(x => x.UserId == u.Id);

                        // We don't have the user in the database yet
                        if (dbUser == null)
                        {
                            model.Add(MapPlexUser(u, null, userDb?.LastLoggedIn ?? DateTime.MinValue));
                        }
                        else
                        {
                            // The Plex User is in the database
                            model.Add(MapPlexUser(u, dbUser, userDb?.LastLoggedIn ?? DateTime.MinValue));
                        }
                    }
                }

                // Also get the server admin
                var account = PlexApi.GetAccount(plexSettings.PlexAuthToken);
                if (account != null)
                {
                    var dbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == account.Id);
                    var userDb = userLogins.FirstOrDefault(x => x.UserId == account.Id);
                    model.Add(MapPlexAdmin(account, dbUser, userDb?.LastLoggedIn ?? DateTime.MinValue));
                }
            }
            return(Response.AsJson(model));
        }
        private async Task<Response> LoadUsers()
        {
            var localUsers = await UserMapper.GetUsersAsync();
            var model = new List<UserManagementUsersViewModel>();
            foreach (var user in localUsers)
            {
                var claims = ByteConverterHelper.ReturnObject<string[]>(user.Claims);
                var claimsString = string.Join(", ", claims);

                var userProps = ByteConverterHelper.ReturnObject<UserProperties>(user.UserProperties);

                model.Add(new UserManagementUsersViewModel
                {
                    Id = user.UserGuid,
                    Claims = claimsString,
                    Username = user.UserName,
                    Type = UserType.LocalUser,
                    EmailAddress = userProps.EmailAddress,
                    ClaimsArray = claims
                });
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();
            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);

                foreach (var u in plexUsers.User)
                {

                    model.Add(new UserManagementUsersViewModel
                    {
                        Username = u.Username,
                        Type = UserType.PlexUser,
                        Id = u.Id,
                        Claims = "Requestor",
                        EmailAddress = u.Email,
                        PlexInfo = new UserManagementPlexInformation
                        {
                            Thumb = u.Thumb
                        }
                    });
                }
            }
            return Response.AsJson(model);
        }
Exemplo n.º 8
0
        private async Task <Response> PlexDetails(string id)
        {
            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);

                var selectedUser = plexUsers.User?.FirstOrDefault(x => x.Id.ToString() == id);
                if (selectedUser != null)
                {
                    return(Response.AsJson(selectedUser));
                }
            }

            return(Nancy.Response.NoBody);
        }
        private void NotifyUsers(IEnumerable <RequestedModel> modelChanged, string apiKey)
        {
            try
            {
                var plexUser    = PlexApi.GetUsers(apiKey);
                var userAccount = PlexApi.GetAccount(apiKey);

                var adminUsername = userAccount.Username ?? string.Empty;

                var users = UserNotifyRepo.GetAll().ToList();
                Log.Debug("Notifying Users Count {0}", users.Count);
                foreach (var model in modelChanged)
                {
                    var selectedUsers = users.Select(x => x.Username).Intersect(model.RequestedUsers);
                    Log.Debug("Selected Users {0}", selectedUsers.DumpJson());
                    foreach (var user in selectedUsers)
                    {
                        Log.Info("Notifying user {0}", user);
                        if (user == adminUsername)
                        {
                            Log.Info("This user is the Plex server owner");
                            PublishUserNotification(userAccount.Username, userAccount.Email, model.Title);
                            return;
                        }

                        var email = plexUser.User.FirstOrDefault(x => x.Username == user);
                        if (email == null)
                        {
                            Log.Info("There is no email address for this Plex user, cannot send notification");
                            // We do not have a plex user that requested this!
                            continue;
                        }

                        Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Username, email.Email, model.Title);
                        PublishUserNotification(email.Username, email.Email, model.Title);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Exemplo n.º 10
0
        public async Task NotifyUsers(RequestedModel model, string apiKey)
        {
            try
            {
                var plexUser    = PlexApi.GetUsers(apiKey);
                var userAccount = PlexApi.GetAccount(apiKey);

                var adminUsername = userAccount.Username ?? string.Empty;

                var users = UserNotifyRepo.GetAll().ToList();
                Log.Debug("Notifying Users Count {0}", users.Count);

                var selectedUsers = users.Select(x => x.Username).Intersect(model.RequestedUsers, StringComparer.CurrentCultureIgnoreCase);
                foreach (var user in selectedUsers)
                {
                    Log.Info("Notifying user {0}", user);
                    if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Log.Info("This user is the Plex server owner");
                        await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath);

                        return;
                    }

                    var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
                    if (email == null)
                    {
                        Log.Info("There is no email address for this Plex user, cannot send notification");
                        // We do not have a plex user that requested this!
                        continue;
                    }

                    Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Username, email.Email, model.Title);
                    await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
        private async Task <Response> LoadUsers()
        {
            var localUsers = await UserMapper.GetUsersAsync();

            var model = new List <UserManagementUsersViewModel>();

            var usersDb = UserLoginsRepo.GetAll().ToList();

            foreach (var user in localUsers)
            {
                var userDb = usersDb.FirstOrDefault(x => x.UserId == user.UserGuid);
                model.Add(MapLocalUser(user, userDb?.LastLoggedIn ?? DateTime.MinValue));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);

                foreach (var u in plexUsers.User)
                {
                    var userDb = usersDb.FirstOrDefault(x => x.UserId == u.Id);
                    model.Add(new UserManagementUsersViewModel
                    {
                        Username     = u.Username,
                        Type         = UserType.PlexUser,
                        Id           = u.Id,
                        Claims       = "Requestor",
                        EmailAddress = u.Email,
                        PlexInfo     = new UserManagementPlexInformation
                        {
                            Thumb = u.Thumb
                        },
                        LastLoggedIn = userDb?.LastLoggedIn ?? DateTime.MinValue,
                    });
                }
            }
            return(Response.AsJson(model));
        }
        private void NotifyUsers(IEnumerable<RequestedModel> modelChanged, string apiKey)
        {
            try
            {
                var plexUser = PlexApi.GetUsers(apiKey);
                if (plexUser?.User == null || plexUser.User.Length == 0)
                {
                    return;
                }

                var users = UserNotifyRepo.GetAll().ToList();
                foreach (var model in modelChanged)
                {
                    var selectedUsers = users.Select(x => x.Username).Intersect(model.RequestedUsers);
                    foreach (var user in selectedUsers)
                    {
                        var email = plexUser.User.FirstOrDefault(x => x.Username == user);
                        if (email == null)
                        {
                            // We do not have a plex user that requested this!
                            continue;
                        }
                        var notificationModel = new NotificationModel
                        {
                            User = email.Username,
                            UserEmail = email.Email,
                            NotificationType = NotificationType.RequestAvailable,
                            Title = model.Title
                        };

                        // Send the notification to the user.
                        Notification.Publish(notificationModel);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Exemplo n.º 13
0
        public async Task <IEnumerable <UsersViewModel> > GetFriends()
        {
            var vm = new List <UsersViewModel>();
            var s  = await PlexSettings.GetSettingsAsync();

            foreach (var server in s.Servers)
            {
                var users = await PlexApi.GetUsers(server.PlexAuthToken);

                if (users?.User != null && users.User.Any())
                {
                    vm.AddRange(users.User.Select(u => new UsersViewModel
                    {
                        Username = u.Username,
                        Id       = u.Id
                    }));
                }
            }

            // Filter out any dupes
            return(vm.DistinctBy(x => x.Id));
        }
Exemplo n.º 14
0
        public async Task NotifyUsers(IEnumerable <RequestedModel> modelChanged, NotificationType type)
        {
            try
            {
                var settings = await PlexSettings.GetSettingsAsync();

                var plexUser    = PlexApi.GetUsers(settings.PlexAuthToken);
                var userAccount = PlexApi.GetAccount(settings.PlexAuthToken);

                var adminUsername = userAccount.Username ?? string.Empty;

                var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList();
                Log.Debug("Notifying Users Count {0}", users.Count);
                foreach (var model in modelChanged)
                {
                    var selectedUsers = new List <string>();

                    foreach (var u in users)
                    {
                        var requestUser = model.RequestedUsers.FirstOrDefault(
                            x => x.Equals(u.Username, StringComparison.CurrentCultureIgnoreCase) || x.Equals(u.UserAlias, StringComparison.CurrentCultureIgnoreCase));
                        if (string.IsNullOrEmpty(requestUser))
                        {
                            continue;
                        }

                        // Make sure we do not already have the user
                        if (!selectedUsers.Contains(requestUser))
                        {
                            selectedUsers.Add(requestUser);
                        }
                    }

                    foreach (var user in selectedUsers)
                    {
                        Log.Info("Notifying user {0}", user);
                        if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
                        {
                            Log.Info("This user is the Plex server owner");
                            await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath, type, model.Type);

                            return;
                        }

                        UserHelperModel localUser = null;
                        //users.FirstOrDefault( x =>
                        //        x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase) ||
                        //        x.UserAlias.Equals(user, StringComparison.CurrentCultureIgnoreCase));

                        foreach (var userHelperModel in users)
                        {
                            if (!string.IsNullOrEmpty(userHelperModel.Username))
                            {
                                if (userHelperModel.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    localUser = userHelperModel;
                                    break;
                                }
                            }
                            if (!string.IsNullOrEmpty(userHelperModel.UserAlias))
                            {
                                if (userHelperModel.UserAlias.Equals(user, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    localUser = userHelperModel;
                                    break;
                                }
                            }
                        }


                        // So if the request was from an alias, then we need to use the local user (since that contains the alias).
                        // If we do not have a local user, then we should be using the Plex user if that user exists.
                        // This will execute most of the time since Plex and Local users will most always be in the database.
                        if (localUser != null)
                        {
                            if (string.IsNullOrEmpty(localUser?.EmailAddress))
                            {
                                Log.Info("There is no email address for this Local user ({0}), cannot send notification", localUser.Username);
                                continue;
                            }

                            Log.Info("Sending notification to: {0} at: {1}, for : {2}", localUser, localUser.EmailAddress, model.Title);
                            await PublishUserNotification(localUser.Username, localUser.EmailAddress, model.Title, model.PosterPath, type, model.Type);
                        }
                        else
                        {
                            var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
                            if (string.IsNullOrEmpty(email?.Email))
                            {
                                Log.Info("There is no email address for this Plex user ({0}), cannot send notification", email?.Username);
                                // We do not have a plex user that requested this!
                                continue;
                            }

                            Log.Info("Sending notification to: {0} at: {1}, for : {2}", email.Username, email.Email, model.Title);
                            await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath, type, model.Type);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Exemplo n.º 15
0
        public async Task NotifyUsers(RequestedModel model, NotificationType type)
        {
            try
            {
                var settings = await PlexSettings.GetSettingsAsync();

                var plexUser    = PlexApi.GetUsers(settings.PlexAuthToken); // TODO emby
                var userAccount = PlexApi.GetAccount(settings.PlexAuthToken);
                var localUsers  = UserHelper.GetUsers().ToList();

                var adminUsername = userAccount.Username ?? string.Empty;

                var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList();
                Log.Debug("Notifying Users Count {0}", users.Count);

                // Get the usernames or alias depending if they have an alias
                var userNamesWithFeature = users.Select(x => x.UsernameOrAlias).ToList();
                Log.Debug("Users with the feature count {0}", userNamesWithFeature.Count);
                Log.Debug("Usernames: ");
                foreach (var u in userNamesWithFeature)
                {
                    Log.Debug(u);
                }

                Log.Debug("Users in the requested model count: {0}", model.AllUsers.Count);
                Log.Debug("usernames from model: ");
                foreach (var modelAllUser in model.AllUsers)
                {
                    Log.Debug(modelAllUser);
                }

                if (model.AllUsers == null || !model.AllUsers.Any())
                {
                    Log.Debug("There are no users in the model.AllUsers, no users to notify");
                    return;
                }
                var usersToNotify = userNamesWithFeature.Intersect(model.AllUsers, StringComparer.CurrentCultureIgnoreCase).ToList();

                if (!usersToNotify.Any())
                {
                    Log.Debug("Could not find any users after the .Intersect()");
                }

                Log.Debug("Users being notified for this request count {0}", users.Count);
                foreach (var user in usersToNotify)
                {
                    Log.Info("Notifying user {0}", user);
                    if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Log.Info("This user is the Plex server owner");
                        await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath, type, model.Type);

                        return;
                    }

                    var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
                    if (email == null) // This is not a Plex User
                    {
                        // Local User?
                        var local = localUsers.FirstOrDefault(x => x.UsernameOrAlias.Equals(user));
                        if (local != null)
                        {
                            Log.Info("Sending notification to: {0} at: {1}, for title: {2}", local.UsernameOrAlias, local.EmailAddress, model.Title);
                            await PublishUserNotification(local.UsernameOrAlias, local.EmailAddress, model.Title, model.PosterPath, type, model.Type);

                            continue;
                        }
                    }

                    Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Username, email.Email, model.Title);
                    await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath, type, model.Type);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Exemplo n.º 16
0
        private void UpdatePlexUsers()
        {
            try
            {
                var settings = PlexSettings.GetSettings();
                if (string.IsNullOrEmpty(settings.PlexAuthToken))
                {
                    return;
                }
                var plexUsers = PlexApi.GetUsers(settings.PlexAuthToken);

                if (plexUsers?.User == null)
                {
                    return;
                }

                var prSettings = PlexRequestSettings.GetSettings();

                var dbUsers = PlexUsers.GetAll().ToList();
                foreach (var user in plexUsers.User)
                {
                    if (dbUsers.FirstOrDefault(x => x.PlexUserId == user.Id) != null)
                    {
                        continue;
                    }

                    int permissions = 0;
                    if (prSettings.SearchForMovies)
                    {
                        permissions = (int)Permissions.RequestMovie;
                    }
                    if (prSettings.SearchForTvShows)
                    {
                        permissions += (int)Permissions.RequestTvShow;
                    }
                    if (prSettings.SearchForMusic)
                    {
                        permissions += (int)Permissions.RequestMusic;
                    }
                    if (!prSettings.RequireMovieApproval)
                    {
                        permissions += (int)Permissions.AutoApproveMovie;
                    }
                    if (!prSettings.RequireTvShowApproval)
                    {
                        permissions += (int)Permissions.AutoApproveTv;
                    }
                    if (!prSettings.RequireMusicApproval)
                    {
                        permissions += (int)Permissions.AutoApproveAlbum;
                    }

                    // Add report Issues

                    permissions += (int)Permissions.ReportIssue;

                    var m = new PlexUsers
                    {
                        PlexUserId   = user.Id,
                        Permissions  = permissions,
                        Features     = 0,
                        UserAlias    = string.Empty,
                        EmailAddress = user.Email,
                        Username     = user.Username,
                        LoginId      = Guid.NewGuid().ToString()
                    };

                    PlexUsers.Insert(m);
                }
            }
            catch (Exception e)
            {
                Logger.Fatal("Exception when migrating Version 1.10.0 (UpdatePlexUsers)");
                Logger.Fatal(e);
            }
        }
Exemplo n.º 17
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.
        }
Exemplo n.º 18
0
        public void Execute(IJobExecutionContext context)
        {
            JobRecord.SetRunning(true, JobNames.PlexUserChecker);

            try
            {
                var settings = PlexSettings.GetSettings();
                if (string.IsNullOrEmpty(settings.PlexAuthToken))
                {
                    return;
                }
                var plexUsers = PlexApi.GetUsers(settings.PlexAuthToken);
                var userManagementSettings = UserManagementSettings.GetSettings();
                var mainPlexAccount        = PlexApi.GetAccount(settings.PlexAuthToken);
                var requests = RequestService.GetAll().ToList();

                var dbUsers    = Repo.GetAll().ToList();
                var localUsers = LocalUserRepository.GetAll().ToList();

                // Regular users
                foreach (var user in plexUsers.User)
                {
                    var dbUser = dbUsers.FirstOrDefault(x => x.PlexUserId == user.Id);
                    if (dbUser != null)
                    {
                        // We already have the user, let's check if they have updated any of their info.
                        var needToUpdate    = false;
                        var usernameChanged = false;

                        if (!string.IsNullOrEmpty(user.Username)) // If true then this is a managed user, we do not want to update the email since Managed Users do not have email addresses
                        {
                            // Do we need up update any info?
                            if (!dbUser.EmailAddress.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase))
                            {
                                dbUser.EmailAddress = user.Email;
                                needToUpdate        = true;
                            }
                        }
                        if (!dbUser.Username.Equals(user.Title, StringComparison.CurrentCultureIgnoreCase))
                        {
                            needToUpdate    = true;
                            usernameChanged = true;
                        }

                        if (needToUpdate)
                        {
                            if (usernameChanged)
                            {
                                // The username has changed, let's check if the username matches any local users
                                var localUser = localUsers.FirstOrDefault(x => x.UserName.Equals(user.Title, StringComparison.CurrentCultureIgnoreCase));
                                dbUser.Username = user.Title;
                                if (localUser != null)
                                {
                                    // looks like we have a local user with the same name...
                                    // We should delete the local user and the Plex user will become the master,
                                    // I am not going to update the Plex Users permissions as that could end up leading to a security vulnerability
                                    // Where anyone could change their Plex Username to the PR.Net server admins name and get all the admin permissions.

                                    LocalUserRepository.Delete(localUser);
                                }

                                // Since the username has changed, we need to update all requests with that username (unless we are using the alias! Since the alias won't change)
                                if (string.IsNullOrEmpty(dbUser.UserAlias))
                                {
                                    // Update all requests
                                    var requestsWithThisUser = requests.Where(x => x.RequestedUsers.Contains(user.Username)).ToList();
                                    foreach (var r in requestsWithThisUser)
                                    {
                                        r.RequestedUsers.Remove(user.Title);   // Remove old
                                        r.RequestedUsers.Add(dbUser.Username); // Add new
                                    }

                                    if (requestsWithThisUser.Any())
                                    {
                                        RequestService.BatchUpdate(requestsWithThisUser);
                                    }
                                }
                            }
                            Repo.Update(dbUser);
                        }

                        continue;
                    }

                    // Looks like it's a new user!
                    var m = new PlexUsers
                    {
                        PlexUserId   = user.Id,
                        Permissions  = UserManagementHelper.GetPermissions(userManagementSettings),
                        Features     = UserManagementHelper.GetFeatures(userManagementSettings),
                        UserAlias    = string.Empty,
                        EmailAddress = user.Email,
                        Username     = user.Title,
                        LoginId      = Guid.NewGuid().ToString()
                    };

                    Repo.Insert(m);
                }

                // Main Plex user
                var dbMainAcc    = dbUsers.FirstOrDefault(x => x.Username.Equals(mainPlexAccount.Username, StringComparison.CurrentCulture));
                var localMainAcc = localUsers.FirstOrDefault(x => x.UserName.Equals(mainPlexAccount.Username, StringComparison.CurrentCulture));

                // TODO if admin acc does exist, check if we need to update it


                // Create the local admin account if it doesn't already exist
                if (dbMainAcc == null && localMainAcc == null)
                {
                    var a = new PlexUsers
                    {
                        PlexUserId   = mainPlexAccount.Id,
                        Permissions  = UserManagementHelper.GetPermissions(userManagementSettings),
                        Features     = UserManagementHelper.GetFeatures(userManagementSettings),
                        UserAlias    = string.Empty,
                        EmailAddress = mainPlexAccount.Email,
                        Username     = mainPlexAccount.Username,
                        LoginId      = Guid.NewGuid().ToString()
                    };

                    a.Permissions += (int)Permissions.Administrator;  // Make admin

                    Repo.Insert(a);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                JobRecord.SetRunning(false, JobNames.PlexUserChecker);
                JobRecord.Record(JobNames.PlexUserChecker);
            }
        }