Пример #1
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);
            }
        }
Пример #2
0
        private string GetOwnerId(string authToken, string userName)
        {
            var userAccount = PlexApi.GetAccount(authToken);

            if (userAccount == null)
            {
                return(string.Empty);
            }
            return(userAccount.Id);
        }
Пример #3
0
        private bool CheckIfUserIsOwner(string authToken, string userName)
        {
            var userAccount = PlexApi.GetAccount(authToken);

            if (userAccount == null)
            {
                return(false);
            }
            return(userAccount.Username != null && userAccount.Username.Equals(userName, StringComparison.CurrentCultureIgnoreCase));
        }
Пример #4
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 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);
            }
        }
Пример #6
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);
            }
        }
Пример #7
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);
            }
        }
Пример #8
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);
            }
        }
Пример #9
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.
        }
Пример #10
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);
            }
        }