Ejemplo n.º 1
0
        public Result EnsureDefaultUsers()
        {
            try
            {
                if (!_db.Users.Any())
                {
                    _logger.LogInformation("Seeding");
                    foreach (var user in _appSettings.Value.DefaultAdmins
                             .EmptyIfNull()
                             .Select(username => new User
                    {
                        DisplayName = username,
                        Username = username,
                        Role = Role.Admin
                    })
                             .Concat(_appSettings.Value.DefaultUsers
                                     .EmptyIfNull()
                                     .Select(username => new User
                    {
                        DisplayName = username,
                        Username = username,
                        Role = Role.User
                    })))
                    {
                        AssignNewPassword(user, _appSettings.Value.DefaultPassword);
                        _db.Users.Add(user);
                    }

                    _db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                return(Result.Failure(e.Message));
            }

            return(Result.Success());
        }
        public Result UpdateNotificationSetting(NotificationInfo info)
        {
            try
            {
                var setting = _db.NotificationSettings
                              .SingleOrDefault(x => x.ParticipantId == info.ParticipantId && x.Type == info.Type);
                var takeTurns = _db.Participants.Include(x => x.Activity)
                                .Select(x => new { x.Id, x.Activity.TakeTurns })
                                .Single(x => x.Id == info.ParticipantId)
                                .TakeTurns;
                if (setting is null)
                {
                    // only add a setting if one of the notification types is selected
                    if (info.AnyActive && info.Type.IsAllowed(takeTurns))
                    {
                        setting        = _mapper.Map <NotificationSetting>(info);
                        setting.Origin = NotificationOrigin.Participant;
                        _db.NotificationSettings.Add(setting);
                    }
                }
                else
                {
                    if (info.AnyActive && info.Type.IsAllowed(takeTurns))
                    {
                        _mapper.Map(info, setting);
                        setting.Origin = NotificationOrigin.Participant;
                        _db.NotificationSettings.Update(setting);
                    }
                    else
                    {
                        // delete settings that don't have any notification type selected
                        _db.NotificationSettings.Remove(setting);
                    }
                }

                _db.SaveChanges();
                return(Result.Success());
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to update notification settings");
                return(Result.Failure(e.Message));
            }
        }
Ejemplo n.º 3
0
        public Result SaveSubscription(int userId, PushSubscription sub)
        {
            try
            {
                if (_db.PushSubscriptionDevices.Find(userId, sub.Endpoint) is null)
                {
                    var device = _mapper.Map <PushSubscriptionDevice>(sub);
                    device.UserId = userId;
                    _db.PushSubscriptionDevices.Add(device);
                    _db.SaveChanges();
                }

                return(Result.Success());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to save sub for user {userId}");
                return(Result.Failure("Failed to save subscription"));
            }
        }
Ejemplo n.º 4
0
        public Result <ActivityDetails, ValidityError> SaveActivity(EditableActivity activity, int ownerId)
        {
            try
            {
                if (activity is null)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("no activity provided"));
                }

                if (string.IsNullOrWhiteSpace(activity.Name))
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("empty name"));
                }

                TimeSpan?period = null;
                if (!activity.PeriodUnit.HasValue)
                {
                    activity.PeriodCount = null;
                }
                else if (!activity.PeriodCount.HasValue)
                {
                    activity.PeriodUnit = null;
                }
                else if (activity.PeriodCount.Value == 0)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period count"));
                }
                else
                {
                    switch (activity.PeriodUnit.Value)
                    {
                    case Unit.Hour:
                        period = TimeSpan.FromHours(activity.PeriodCount.Value);
                        break;

                    case Unit.Day:
                        period = TimeSpan.FromDays(activity.PeriodCount.Value);
                        break;

                    case Unit.Week:
                        period = TimeSpan.FromDays(7 * activity.PeriodCount.Value);
                        break;

                    case Unit.Month:
                        period = TimeSpan.FromDays(365.25 / 12 * activity.PeriodCount.Value);
                        break;

                    case Unit.Year:
                        period = TimeSpan.FromDays(365.25 * activity.PeriodCount.Value);
                        break;

                    default:
                        return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period unit"));
                    }
                }

                activity.Participants ??= new List <UserInfo>();

                // sanitize the default notification settings to ensure there's only one per type
                var defaultNotificationSettings =
                    (activity.DefaultNotificationSettings ?? new List <NotificationInfo>())
                    .Where(x => x.AnyActive && x.Type.IsAllowed(activity.TakeTurns))
                    .GroupBy(x => x.Type)
                    .Select(g => g.First())
                    .ToDictionary(x => x.Type);

                if (activity.Id < 0)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID"));
                }

                var userIds = activity.Participants.Select(p => p.Id).Append(ownerId).ToHashSet();

                var      add = false;
                Activity activityToUpdate;
                if (activity.Id == 0)
                {
                    add = true;
                    activityToUpdate = new Activity
                    {
                        Participants = _db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant).ToList(),
                        DefaultNotificationSettings = _mapper.Map <List <DefaultNotificationSetting> >(defaultNotificationSettings.Values),
                        Owner = _db.Users.Find(ownerId),
                        Turns = new List <Turn>(0)
                    };
                    foreach (var participant in activityToUpdate.Participants)
                    {
                        participant.NotificationSettings.AddRange(_mapper.Map <List <NotificationSetting> >(defaultNotificationSettings.Values));
                    }
                }
                else
                {
                    activityToUpdate = GetActivity(activity.Id, false, true, true);
                    if (activityToUpdate is null)
                    {
                        return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID"));
                    }

                    if (activityToUpdate.IsDisabled)
                    {
                        return(ValidityError.ForInvalidObject <ActivityDetails>("activity is disabled"));
                    }

                    // remove any participants that should no longer be there
                    activityToUpdate.Participants.RemoveAll(x => !userIds.Contains(x.UserId));

                    // remove any existing participants from the list so we're left with only new participants
                    userIds.ExceptWith(activityToUpdate.Participants.Select(x => x.UserId));

                    // add new participants
                    activityToUpdate.Participants.AddRange(_db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant));

                    // remove any default notifications that should no longer be there
                    activityToUpdate.DefaultNotificationSettings.RemoveAll(x =>
                    {
                        var remove = !defaultNotificationSettings.ContainsKey(x.Type);

                        if (remove)
                        {
                            foreach (var participant in activityToUpdate.Participants)
                            {
                                participant.NotificationSettings.RemoveAll(y => y.Type == x.Type && y.Origin == NotificationOrigin.Default);
                            }
                        }

                        return(remove);
                    });

                    // remove any participant notifications that are no longer valid because the activity no longer has turns needed
                    if (activityToUpdate.TakeTurns && !activity.TakeTurns)
                    {
                        foreach (var participant in activityToUpdate.Participants)
                        {
                            participant.NotificationSettings.RemoveAll(x => !x.Type.IsAllowed(activity.TakeTurns));
                        }
                    }

                    // update any existing default notification and remove it from the new list
                    foreach (var noteToUpdate in activityToUpdate.DefaultNotificationSettings)
                    {
                        if (defaultNotificationSettings.Remove(noteToUpdate.Type, out var updatedNote))
                        {
                            _mapper.Map(updatedNote, noteToUpdate);

                            // update any existing participant notifications that originated from a default notification
                            foreach (var participantNote in activityToUpdate.Participants.SelectMany(x => x.NotificationSettings).Where(x => x.Type == updatedNote.Type && x.Origin == NotificationOrigin.Default))
                            {
                                //make sure we don't clear the participant ID
                                updatedNote.ParticipantId = participantNote.ParticipantId;
                                _mapper.Map(updatedNote, participantNote);
                            }
                        }
                    }

                    // add any remaining notifications
                    foreach (var note in defaultNotificationSettings.Values)
                    {
                        activityToUpdate.DefaultNotificationSettings.Add(_mapper.Map <DefaultNotificationSetting>(note));
                        foreach (var participant in activityToUpdate.Participants.Where(participant =>
                                                                                        participant.NotificationSettings.All(x => x.Type != note.Type)))
                        {
                            participant.NotificationSettings.Add(_mapper.Map <NotificationSetting>(note));
                        }
                    }
                }

                activityToUpdate.OwnerId     = ownerId;
                activityToUpdate.Name        = activity.Name;
                activityToUpdate.Description = string.IsNullOrWhiteSpace(activity.Description)
                    ? null
                    : activity.Description.Trim();
                activityToUpdate.PeriodCount = activity.PeriodCount;
                activityToUpdate.PeriodUnit  = activity.PeriodUnit;
                activityToUpdate.Period      = period;
                activityToUpdate.TakeTurns   = activity.TakeTurns;

                if (add)
                {
                    _db.Activities.Add(activityToUpdate);
                }
                else
                {
                    _db.Activities.Update(activityToUpdate);
                }

                var details = ActivityDetails.Calculate(activityToUpdate, ownerId, _mapper);

                _db.SaveChanges();
                details.Update(activityToUpdate);
                return(Result.Success <ActivityDetails, ValidityError>(details));
            }
            catch (Exception e)
            {
                var message = $"Failed to save activity '{activity?.Id}'";
                _logger.LogError(e, message);
                return(ValidityError.ForInvalidObject <ActivityDetails>(message));
            }

            Participant CreateNewParticipant(User user)
            {
                return(new Participant
                {
                    UserId = user.Id,
                    User = user,
                    DismissUntilTimeOfDay = _appSettings.Value.PushNotifications.DefaultDismissTime,
                    NotificationSettings = new List <NotificationSetting>()
                });
            }
        }