Пример #1
0
 private void GetPendingInvitationsCount(Callback <int> callback)
 {
     InvitationHelper.GetInvitationsFrom(this.client.BigDB, InvitationType.Friend,
                                         this.name, invitations =>
                                         callback(invitations.Count(invite =>
                                                                    invite.Status == InvitationStatus.Pending)));
 }
        public async Task <ActionResult> ManualJoin(string code)
        {
            var user       = db.Users.Find(User.Identity.GetUserId());
            var realGuid   = Guid.Parse(code);
            var invitation = db.Invitations.FirstOrDefault(i => i.RecipientEmail == user.Email && i.Code == realGuid);

            if (invitation == null)
            {
                return(View("NotFoundError"));
            }
            var expirationDate = invitation.Created.AddDays(invitation.TTL);

            if (invitation.IsValid && DateTime.Now < expirationDate)
            {
                InvitationHelper.MarkAsInvalid(invitation.Id);
                user.HouseholdId = invitation.HouseholdId;
                roleHelper.UpdateUserRole(user.Id, "Member");

                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Dashboard", "Home"));
            }

            return(View("AcceptError", invitation));
        }
        private async Task <Guid> CreateOutlookMeeting(
            CreateInvitationCommand request,
            IReadOnlyCollection <BuilderParticipant> meetingParticipants,
            Invitation invitation)
        {
            foreach (var meetingParticipant in meetingParticipants)
            {
                _logger.LogInformation($"Adding {meetingParticipant.Person.AzureUniqueId} - {meetingParticipant.Person.Mail} to invitation {invitation.Id}");
            }

            var organizer = await _personRepository.GetByOidAsync(_currentUserProvider.GetCurrentUserOid());

            var meeting = await _meetingClient.CreateMeetingAsync(meetingBuilder =>
            {
                var baseUrl = InvitationHelper.GetBaseUrl(_meetingOptions.CurrentValue.PcsBaseUrl, _plantProvider.Plant);

                meetingBuilder
                .StandaloneMeeting(InvitationHelper.GenerateMeetingTitle(invitation), request.Location)
                .StartsOn(request.StartTime, request.EndTime)
                .WithTimeZone("UTC")
                .WithParticipants(meetingParticipants)
                .WithClassification(MeetingClassification.Open)
                .EnableOutlookIntegration()
                .WithInviteBodyHtml(InvitationHelper.GenerateMeetingDescription(invitation, baseUrl, organizer));
            });

            return(meeting.Id);
        }
Пример #4
0
        public async Task <ActionResult> AcceptRegisterInvitation(AcceptRegisterInvitationViewModel invitationVM)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName   = invitationVM.FirstName,
                    LastName    = invitationVM.LastName,
                    DisplayName = invitationVM.DisplayName,
                    UserName    = invitationVM.Email,
                    Email       = invitationVM.Email,
                    AvatarPath  = "/Avatars/Stuart.png",
                    HouseholdId = invitationVM.HouseholdId
                };

                var result = await UserManager.CreateAsync(user, invitationVM.Password);

                if (result.Succeeded)
                {
                    InvitationHelper.MarkAsInvalid(invitationVM.Id);
                    rHelp.AddUserToRole(user.Id, "Member");

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Hooray", "Account"));
                }

                AddErrors(result);
            }

            return(View(invitationVM));
        }
Пример #5
0
        public async Task <Result <string> > Handle(UnCompletePunchOutCommand request, CancellationToken cancellationToken)
        {
            var invitation = await _invitationRepository.GetByIdAsync(request.InvitationId);

            var currentUserAzureOid = _currentUserProvider.GetCurrentUserOid();
            var hasAdminPrivilege   = await InvitationHelper.HasIpoAdminPrivilege(_permissionCache, _plantProvider, _currentUserProvider);

            var participant = invitation.Participants.SingleOrDefault(p =>
                                                                      p.SortKey == 0 &&
                                                                      p.Organization == Organization.Contractor &&
                                                                      (p.AzureOid == currentUserAzureOid || hasAdminPrivilege));

            if (participant == null || participant.FunctionalRoleCode != null)
            {
                var functionalRole = invitation.Participants
                                     .SingleOrDefault(p => p.SortKey == 0 &&
                                                      p.FunctionalRoleCode != null &&
                                                      p.Type == IpoParticipantType.FunctionalRole);

                invitation.UnCompleteIpo(functionalRole, request.ParticipantRowVersion);
            }
            else
            {
                invitation.UnCompleteIpo(participant, request.ParticipantRowVersion);
            }

            invitation.SetRowVersion(request.InvitationRowVersion);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <string>(invitation.RowVersion.ConvertToString()));
        }
        public async Task <ActionResult> AcceptInvitation(AcceptInvitationVM model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, HouseholdId = model.HouseholdId
                };
                if (model.Avatar != null)
                {
                    //Run the avatar upload code from blog/bt here
                }
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    roleHelper.UpdateUserRole(user.Id, "Member");
                    InvitationHelper.MarkAsInvalid(model.InvitationId);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Dashboard", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #7
0
        public async Task <ActionResult> AcceptInvitation(AcceptInvitationViewModel invitationvm)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName   = invitationvm.FirstName,
                    LastName    = invitationvm.LastName,
                    UserName    = invitationvm.Email,
                    Email       = invitationvm.Email,
                    AvatarPath  = "/Avatars/default_user.png",
                    HouseholdId = invitationvm.HouseholdId
                };

                var result = await UserManager.CreateAsync(user, invitationvm.Password);

                if (result.Succeeded)
                {
                    InvitationHelper.MarkAsInvalid(invitationvm.Id);

                    roleHelper.AddUserToRole(user.Id, "Member");

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Dashboard", "Home"));
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return(View(invitationvm));
        }
Пример #8
0
        public async Task <ActionResult> AcceptLoginInvitation(AcceptLoginInvitationViewModel invitationVM, string returnUrl)
        {
            var user = db.Users.Where(u => u.Email == invitationVM.Email).FirstOrDefault();

            if (!ModelState.IsValid)
            {
                return(View(invitationVM));
            }

            var result = await SignInManager.PasswordSignInAsync(invitationVM.Email, invitationVM.Password, invitationVM.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                InvitationHelper.MarkAsInvalid(invitationVM.Id);
                rHelp.RemoveUserFromRole(user.Id, "Guest");
                rHelp.AddUserToRole(user.Id, "Member");
                user.HouseholdId = invitationVM.HouseholdId;
                db.SaveChanges();
                return(RedirectToAction("Hooray", "Account"));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = invitationVM.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(invitationVM));
            }
        }
Пример #9
0
        public async Task <bool> CurrentUserIsAllowedToDeleteIpoAsync(int invitationId, CancellationToken cancellationToken)
        {
            var hasAdminPermission = await InvitationHelper.HasIpoAdminPrivilege(_permissionCache, _plantProvider, _currentUserProvider);

            if (hasAdminPermission)
            {
                return(true);
            }

            return(await CurrentUserIsCreatorOfIpoAsync(invitationId, cancellationToken));
        }
Пример #10
0
 public ActionResult Edit([Bind(Include = "Id,Name,HeadofHholdId")] Household household)
 {
     if (ModelState.IsValid)
     {
         InvitationHelper invitationHelper = new InvitationHelper();
         db.Entry(household).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(household));
 }
Пример #11
0
        public async Task <bool> CurrentUserIsAdminOrValidAccepterParticipantAsync(int invitationId, CancellationToken cancellationToken)
        {
            var hasAdminPermission = await InvitationHelper.HasIpoAdminPrivilege(_permissionCache, _plantProvider, _currentUserProvider);

            if (hasAdminPermission)
            {
                return(true);
            }

            return(await CurrentUserIsValidAccepterParticipantAsync(invitationId, cancellationToken));
        }
        private async Task <List <BuilderParticipant> > AddPersonParticipantsWithOidsAsync(
            Invitation invitation,
            List <BuilderParticipant> meetingParticipants,
            List <ParticipantsForCommand> personParticipantsWithOids)
        {
            var personsAdded = new List <ParticipantsForCommand>();

            foreach (var participant in personParticipantsWithOids)
            {
                if (InvitationHelper.ParticipantIsSigningParticipant(participant))
                {
                    meetingParticipants = await AddSigner(
                        invitation,
                        meetingParticipants,
                        participant.InvitedPerson,
                        participant.SortKey,
                        participant.Organization);

                    personsAdded.Add(participant);
                }
            }

            personParticipantsWithOids.RemoveAll(p => personsAdded.Contains(p));

            var oids    = personParticipantsWithOids.Where(p => p.SortKey > 1).Select(p => p.InvitedPerson.AzureOid.ToString()).ToList();
            var persons = oids.Count > 0
                ? await _personApiService.GetPersonsByOidsAsync(_plantProvider.Plant, oids)
                : new List <ProCoSysPerson>();

            if (persons.Any())
            {
                foreach (var participant in personParticipantsWithOids)
                {
                    var person = persons.SingleOrDefault(p => p.AzureOid == participant.InvitedPerson.AzureOid.ToString());
                    if (person != null)
                    {
                        invitation.AddParticipant(new Participant(
                                                      _plantProvider.Plant,
                                                      participant.Organization,
                                                      IpoParticipantType.Person,
                                                      null,
                                                      person.FirstName,
                                                      person.LastName,
                                                      person.UserName,
                                                      person.Email,
                                                      new Guid(person.AzureOid),
                                                      participant.SortKey));
                        meetingParticipants = InvitationHelper.AddPersonToOutlookParticipantList(person, meetingParticipants);
                    }
                }
            }

            return(meetingParticipants);
        }
        public async Task GetProjectName_UnKnownInvitationId_ShouldReturnNull()
        {
            using (var context = new IPOContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider))
            {
                // Arrange
                var dut = new InvitationHelper(context);

                // Act
                var projectName = await dut.GetProjectNameAsync(0);

                // Assert
                Assert.IsNull(projectName);
            }
        }
        private async Task <List <BuilderParticipant> > AddSigner(
            Invitation invitation,
            List <BuilderParticipant> meetingParticipants,
            IList <Participant> existingParticipants,
            InvitedPersonForEditCommand person,
            int sortKey,
            Organization organization)
        {
            var personFromMain = await _personApiService.GetPersonByOidWithPrivilegesAsync(_plantProvider.Plant,
                                                                                           person.AzureOid.ToString(), _objectName, _signerPrivileges);

            if (personFromMain != null)
            {
                var existingParticipant = existingParticipants.SingleOrDefault(p => p.Id == person.Id);
                if (existingParticipant != null)
                {
                    invitation.UpdateParticipant(
                        existingParticipant.Id,
                        organization,
                        IpoParticipantType.Person,
                        null,
                        personFromMain.FirstName,
                        personFromMain.LastName,
                        personFromMain.Email,
                        new Guid(personFromMain.AzureOid),
                        sortKey,
                        person.RowVersion);
                }
                else
                {
                    invitation.AddParticipant(new Participant(
                                                  _plantProvider.Plant,
                                                  organization,
                                                  IpoParticipantType.Person,
                                                  null,
                                                  personFromMain.FirstName,
                                                  personFromMain.LastName,
                                                  personFromMain.UserName,
                                                  personFromMain.Email,
                                                  new Guid(personFromMain.AzureOid),
                                                  sortKey));
                }
                meetingParticipants = InvitationHelper.AddPersonToOutlookParticipantList(personFromMain, meetingParticipants);
            }
            else
            {
                throw new IpoValidationException($"Person does not have required privileges to be the {organization} participant.");
            }
            return(meetingParticipants);
        }
Пример #15
0
        public async Task <ActionResult> ManualJoin(string code)
        {
            var userId     = User.Identity.GetUserId();
            var user       = db.Users.Find(userId);
            var realGuid   = Guid.Parse(code);
            var invitation = db.Invitations.FirstOrDefault(i => i.Code == realGuid);

            InvitationHelper.MarkAsInvalid(invitation.Id);
            roleHelper.RemoveUserFromRole(userId, "Guest");
            roleHelper.AddUserToRole(userId, "Member");

            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

            return(RedirectToAction("Dashboard", "Home"));
        }
Пример #16
0
        public async Task <ActionResult> AcceptInvitation(AcceptInvitationVM model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    HouseholdId = model.HouseholdId
                };

                if (model.Avatar != null)
                {
                    if (FileUploadValidator.IsWebFriendlyImage(model.Avatar))
                    {
                        var fileName = FileStamp.MakeUnique(model.Avatar.FileName);

                        var serverFolder = WebConfigurationManager.AppSettings["DefaultServerFolder"];
                        model.Avatar.SaveAs(Path.Combine(Server.MapPath("~" + serverFolder), fileName));
                        user.AvatarPath = $"{serverFolder}/{fileName}";
                    }
                }

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    rolesHelper.AddUserToRole(user.Id, "Member");
                    InvitationHelper.MarkAsInvalid(model.InvitationId);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Dashboard", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form

            return(View(model));
        }
Пример #17
0
        public async Task <ActionResult> AcceptInvitation(AcceptInvitationViewModel invitationvm, HttpPostedFileBase avatar)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName   = invitationvm.FirstName,
                    LastName    = invitationvm.LastName,
                    DisplayName = invitationvm.DisplayName,
                    UserName    = invitationvm.Email,
                    Email       = invitationvm.Email,
                    AvatarPath  = "/Avatars/default_user.png",
                    HouseholdId = invitationvm.HouseholdId
                };

                if (avatar != null)
                {
                    if (ImageUploadValidator.IsWebFriendlyImage(avatar))
                    {
                        var fileName     = Path.GetFileName(avatar.FileName);
                        var justFileName = Path.GetFileNameWithoutExtension(fileName);
                        justFileName = StringUtilities.URLFriendly(justFileName);
                        fileName     = $"{justFileName}_{DateTime.Now.Ticks}{Path.GetExtension(fileName)}";
                        avatar.SaveAs(Path.Combine(Server.MapPath("~/Avatars/"), fileName));
                        user.AvatarPath = "/Avatars/" + fileName;
                    }
                }

                var result = await UserManager.CreateAsync(user, invitationvm.Password);

                if (result.Succeeded)
                {
                    InvitationHelper.MarkAsInvalid(invitationvm.Id);

                    roleHelper.AddUserToRole(user.Id, "Member");

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Home"));
                }

                AddErrors(result);
            }

            //If we got this far, something failed, redisplay form
            return(View(invitationvm));
        }
        public async Task <Result <string> > Handle(EditInvitationCommand request, CancellationToken cancellationToken)
        {
            var meetingParticipants = new List <BuilderParticipant>();
            var invitation          = await _invitationRepository.GetByIdAsync(request.InvitationId);

            var mcPkgScope = await GetMcPkgScopeAsync(request.UpdatedMcPkgScope, invitation.ProjectName);

            var commPkgScope = await GetCommPkgScopeAsync(request.UpdatedCommPkgScope, invitation.ProjectName);

            meetingParticipants = await UpdateParticipants(meetingParticipants, request.UpdatedParticipants, invitation);

            invitation.EditIpo(
                request.Title,
                request.Description,
                request.Type,
                request.StartTime,
                request.EndTime,
                request.Location,
                mcPkgScope,
                commPkgScope);

            invitation.SetRowVersion(request.RowVersion);
            try
            {
                var baseUrl =
                    InvitationHelper.GetBaseUrl(_meetingOptions.CurrentValue.PcsBaseUrl, _plantProvider.Plant);

                var organizer = await _personRepository.GetByIdAsync(invitation.CreatedById);

                await _meetingClient.UpdateMeetingAsync(invitation.MeetingId, builder =>
                {
                    builder.UpdateLocation(request.Location);
                    builder.UpdateMeetingDate(request.StartTime, request.EndTime);
                    builder.UpdateTimeZone("UTC");
                    builder.UpdateParticipants(meetingParticipants);
                    builder.UpdateInviteBodyHtml(InvitationHelper.GenerateMeetingDescription(invitation, baseUrl, organizer));
                });
            }
            catch (Exception e)
            {
                throw new Exception("Error: Could not update outlook meeting.", e);
            }

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <string>(invitation.RowVersion.ConvertToString()));
        }
Пример #19
0
        private void AnswerInvitation(string senderName, bool accept, Callback <string> successCallback,
                                      Callback <InvitationError> errorCallback)
        {
            InvitationHelper.GetInvitation(this.client.BigDB, InvitationType.Friend,
                                           senderName, this.name, invitation =>
            {
                if (!invitation.Exists)
                {
                    errorCallback(InvitationError.InvitationNotFound);
                    return;
                }

                CommonPlayer.GetId(this.client.BigDB, senderName, senderId =>
                {
                    if (senderId == null)
                    {
                        InvitationHelper.DeleteInvitation(this.client.BigDB, InvitationType.Friend, senderName,
                                                          this.name, result =>
                                                          errorCallback(InvitationError.PlayerNotFound));
                        return;
                    }

                    this.GetFriendsCount(numFriends =>
                    {
                        if (accept)
                        {
                            if (numFriends >= this.MaxFriendsAllowed)
                            {
                                errorCallback(InvitationError.LimitReached);
                                return;
                            }

                            invitation.Status = InvitationStatus.Accepted;
                            this.AddOrRemoveFriend(senderId, true);
                        }
                        else
                        {
                            invitation.Status = InvitationStatus.Rejected;
                        }

                        invitation.Save(() => successCallback(senderId));
                    });
                });
            });
        }
Пример #20
0
        public async Task <bool> HasPermissionToEditParticipantAsync(int id, int invitationId, CancellationToken cancellationToken)
        {
            if (await InvitationHelper.HasIpoAdminPrivilege(_permissionCache, _plantProvider, _currentUserProvider))
            {
                return(true);
            }

            var invitation = await(from i in _context.QuerySet <Invitation>()
                                   where i.Id == invitationId
                                   select i).SingleAsync(cancellationToken);

            switch (invitation.Status)
            {
            case IpoStatus.Planned when await CurrentUserIsValidCompleterParticipantAsync(invitationId, cancellationToken):
            case IpoStatus.Completed when await CurrentUserIsValidAccepterParticipantAsync(invitationId, cancellationToken):
                return(true);
            }

            var participant = await(from p in _context.QuerySet <Participant>()
                                    where EF.Property <int>(p, "InvitationId") == invitationId &&
                                    p.Id == id
                                    select p).SingleAsync(cancellationToken);

            if (participant.SignedAtUtc != null)
            {
                return(false);
            }

            if (participant.FunctionalRoleCode == null &&
                participant.AzureOid == _currentUserProvider.GetCurrentUserOid())
            {
                return(true);
            }

            var person = await _personApiService.GetPersonInFunctionalRoleAsync(
                _plantProvider.Plant,
                _currentUserProvider.GetCurrentUserOid().ToString(),
                participant.FunctionalRoleCode);

            return(person != null);
        }
Пример #21
0
        public async Task <ActionResult> AcceptInvitationWithAcct(AcceptInvitationWithAcctViewModel invitationVm)
        {
            if (!ModelState.IsValid)
            {
                return(View(invitationVm));
            }

            var existingUser = db.Users.FirstOrDefault(u => u.Email == invitationVm.Email);

            existingUser.HouseholdId = invitationVm.HouseholdId;

            if (!roleHelper.IsDemoUser(db.Users.FirstOrDefault(u => u.Email == invitationVm.Email).Id))
            {
                InvitationHelper.MarkAsInvalid(invitationVm.Id);
                roleHelper.RemoveUserFromRole(db.Users.FirstOrDefault(u => u.Email == invitationVm.Email).Id, "UnAssigned");
                roleHelper.AddUserToRole(db.Users.FirstOrDefault(u => u.Email == invitationVm.Email).Id, "Member");
            }

            if (!roleHelper.IsDemoUser(existingUser.Id))
            {
                db.SaveChanges();
            }

            var result = await SignInManager.PasswordSignInAsync(invitationVm.Email, invitationVm.Password, false, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                //InvitationHelper.MarkAsInvalid(invitationVm.Id);
                return(RedirectToAction("Index", "Home"));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(invitationVm));
            }
        }
        private async Task <List <BuilderParticipant> > AddSigner(
            Invitation invitation,
            List <BuilderParticipant> meetingParticipants,
            IInvitedPersonForCommand invitedSigner,
            int sortKey,
            Organization organization)
        {
            var person = await _personApiService.GetPersonByOidWithPrivilegesAsync(
                _plantProvider.Plant,
                invitedSigner.AzureOid.ToString(),
                _objectName,
                _signerPrivileges);

            if (person != null)
            {
                invitation.AddParticipant(new Participant(
                                              _plantProvider.Plant,
                                              organization,
                                              IpoParticipantType.Person,
                                              null,
                                              person.FirstName,
                                              person.LastName,
                                              person.UserName,
                                              person.Email,
                                              new Guid(person.AzureOid),
                                              sortKey));
                meetingParticipants = InvitationHelper.AddPersonToOutlookParticipantList(person, meetingParticipants);
            }
            else
            {
                throw new IpoValidationException(
                          $"Person does not have required privileges to be the {organization} participant.");
            }

            return(meetingParticipants);
        }
Пример #23
0
        public void ProcessMessages(QueueItem item, LobbyPlayer player)
        {
            switch (item.Method)
            {
            case "getFriends":
            {
                this.GetFriendKeys(player.ConnectUserId, keys =>
                    {
                        if (keys.Count <= 0)
                        {
                            player.Send(item.Method);
                            return;
                        }

                        OnlineStatus.GetOnlineStatus(this.client, keys.ToArray(), status =>
                        {
                            var rtn = Message.Create(item.Method);
                            foreach (var stat in status.Where(stat => stat != null))
                            {
                                stat.ToMessage(rtn);
                            }
                            player.Send(rtn);
                        });
                    });
                break;
            }

            case "getPending":
            {
                InvitationHelper.GetInvitationsFrom(this.client.BigDB, InvitationType.Friend,
                                                    this.name, invites =>
                    {
                        var rtn = Message.Create(item.Method);
                        foreach (var invite in invites)
                        {
                            rtn.Add(invite.Recipient);
                            rtn.Add((int)invite.Status);
                        }
                        player.Send(rtn);
                    });
                break;
            }

            case "getInvitesToMe":
            {
                InvitationHelper.GetInvitationsTo(this.client.BigDB, InvitationType.Friend,
                                                  this.name, invites =>
                    {
                        var rtn = Message.Create(item.Method);
                        foreach (var invite in invites.Where(it => it.Status == InvitationStatus.Pending))
                        {
                            rtn.Add(invite.Sender);
                        }
                        player.Send(rtn);
                    });
                break;
            }

            case "getBlockedUsers":
            {
                InvitationBlocking.GetBlockedUsers(this.client.BigDB, this.connectUserId, blockedUsers =>
                    {
                        var rtn = Message.Create(item.Method);
                        foreach (var blockedUser in blockedUsers)
                        {
                            rtn.Add(blockedUser);
                        }
                        player.Send(rtn);
                    });
                break;
            }

            case "createInvite":
            {
                if (!player.HasFriendFeatures)
                {
                    player.Send(item.Method, false);
                    return;
                }

                var friendName = item.Message.GetString(0).ToLower();

                this.CreateInvitation(friendName,
                                      () => player.Send(item.Method, true),
                                      error =>
                    {
                        switch (error)
                        {
                        case InvitationError.PlayerNotFound:
                            {
                                player.Send(item.Method, false,
                                            "Unknown user. Please check your spelling.");
                                break;
                            }

                        case InvitationError.AlreadyAdded:
                            {
                                player.Send(item.Method, false,
                                            "This user is already on your friendslist!");
                                break;
                            }

                        case InvitationError.AlreadySent:
                            {
                                player.Send(item.Method, false,
                                            "You already have a pending invitation for this user.");
                                break;
                            }

                        case InvitationError.LimitReached:
                            {
                                player.Send(item.Method, false,
                                            "You cannot have more than " +
                                            this.MaxFriendsAllowed +
                                            " friends and invites.");
                                break;
                            }

                        case InvitationError.Blocked:
                            {
                                player.Send(item.Method, false,
                                            "This user is blocking friend requests.");
                                break;
                            }

                        case InvitationError.SendingToSelf:
                            {
                                player.Send(item.Method, false,
                                            "You cannot add yourself.");
                                break;
                            }
                        }
                    });
                break;
            }

            case "answerInvite":
            {
                if (!player.HasFriendFeatures)
                {
                    player.Send(item.Method, false);
                    return;
                }

                var invitedBy = item.Message.GetString(0).ToLower();
                var accept    = item.Message.GetBoolean(1);

                this.AnswerInvitation(invitedBy, accept,
                                      senderId =>
                    {
                        OnlineStatus.GetOnlineStatus(this.client, senderId, onlineStatus =>
                        {
                            var rtn = Message.Create(item.Method, true);
                            player.Send(onlineStatus.ToMessage(rtn));
                        });
                    },
                                      error =>
                    {
                        switch (error)
                        {
                        case InvitationError.PlayerNotFound:
                            {
                                player.Send(item.Method, false,
                                            "Sorry, the sender of this friend request does not exist.");
                                break;
                            }

                        case InvitationError.InvitationNotFound:
                            {
                                player.Send(item.Method, false,
                                            "Sorry, the friend request does not exist anymore.");
                                break;
                            }

                        case InvitationError.LimitReached:
                            {
                                player.Send(item.Method, false,
                                            "You cannot have more than " +
                                            this.MaxFriendsAllowed +
                                            " friends.");
                                break;
                            }
                        }
                    });
                break;
            }

            case "deleteInvite":
            {
                var recipientName = item.Message.GetString(0).ToLower();

                InvitationHelper.DeleteInvitation(this.client.BigDB, InvitationType.Friend,
                                                  this.name, recipientName, success =>
                    {
                        if (!success)
                        {
                            this.client.ErrorLog.WriteError(
                                "Error deleting invitation from " + player.Name + " to " +
                                recipientName, "Invite not found",
                                "Error deleting pending invitation", null);
                        }
                        player.Send(item.Method, success);
                    });
                break;
            }

            case "blockUserInvites":
            {
                var invitedByName = item.Message.GetString(0).ToLower();
                var shouldBlock   = item.Message.GetBoolean(1);

                InvitationBlocking.BlockUser(this.client.BigDB, this.connectUserId, invitedByName, shouldBlock,
                                             () =>
                    {
                        if (shouldBlock)
                        {
                            InvitationHelper.GetInvitation(this.client.BigDB, InvitationType.Friend, invitedByName,
                                                           this.name, invitation =>
                            {
                                if (invitation.Exists)
                                {
                                    invitation.Status = InvitationStatus.Rejected;
                                    invitation.Save(() => player.Send(item.Method, true));
                                }
                                else
                                {
                                    player.Send(item.Method, true);
                                }
                            });
                        }
                        else
                        {
                            player.Send(item.Method, true);
                        }
                    });
                break;
            }

            case "getBlockStatus":
            {
                InvitationBlocking.IsBlockingAllUsers(this.client.BigDB, this.connectUserId,
                                                      isBlocking => { player.Send(item.Method, isBlocking); });
                break;
            }

            case "blockAllInvites":
            {
                var shouldBlock = item.Message.GetBoolean(0);

                InvitationBlocking.BlockAllFriends(this.client.BigDB, this.connectUserId, shouldBlock);
                player.Send(item.Method, shouldBlock);
                break;
            }

            case "deleteFriend":
            {
                CommonPlayer.GetId(this.client.BigDB, item.Message.GetString(0).ToLower(), friendId =>
                    {
                        this.AddOrRemoveFriend(friendId, false,
                                               delegate { player.Send(item.Method, true); });
                    });
                break;
            }

            case "GetOnlineStatus":
            {
                var id = item.Message.Count > 0 ? item.Message.GetString(0) : player.ConnectUserId;
                OnlineStatus.GetOnlineStatus(this.client, id,
                                             onlineStatus => player.Send(onlineStatus.ToMessage(item.Method)));
                break;
            }
            }
        }
        private async Task <List <BuilderParticipant> > AddFunctionalRoleParticipantsAsync(
            Invitation invitation,
            List <BuilderParticipant> meetingParticipants,
            List <ParticipantsForCommand> functionalRoleParticipants)
        {
            var codes           = functionalRoleParticipants.Select(p => p.InvitedFunctionalRole.Code).ToList();
            var functionalRoles =
                await _functionalRoleApiService.GetFunctionalRolesByCodeAsync(_plantProvider.Plant, codes);

            foreach (var participant in functionalRoleParticipants)
            {
                var fr = functionalRoles.SingleOrDefault(p => p.Code == participant.InvitedFunctionalRole.Code);
                if (fr != null)
                {
                    invitation.AddParticipant(new Participant(
                                                  _plantProvider.Plant,
                                                  participant.Organization,
                                                  IpoParticipantType.FunctionalRole,
                                                  fr.Code,
                                                  null,
                                                  null,
                                                  null,
                                                  fr.Email,
                                                  null,
                                                  participant.SortKey));
                    if (fr.UsePersonalEmail != null && fr.UsePersonalEmail == false && fr.Email != null)
                    {
                        meetingParticipants.AddRange(InvitationHelper.SplitAndCreateOutlookParticipantsFromEmailList(fr.Email));
                    }
                    if (fr.InformationEmail != null)
                    {
                        meetingParticipants.AddRange(InvitationHelper.SplitAndCreateOutlookParticipantsFromEmailList(fr.InformationEmail));
                    }
                    foreach (var person in participant.InvitedFunctionalRole.InvitedPersons)
                    {
                        var frPerson = fr.Persons.SingleOrDefault(p => p.AzureOid == person.AzureOid.ToString());
                        if (frPerson != null)
                        {
                            invitation.AddParticipant(new Participant(
                                                          _plantProvider.Plant,
                                                          participant.Organization,
                                                          IpoParticipantType.Person,
                                                          fr.Code,
                                                          frPerson.FirstName,
                                                          frPerson.LastName,
                                                          frPerson.UserName,
                                                          frPerson.Email,
                                                          new Guid(frPerson.AzureOid),
                                                          participant.SortKey));
                            meetingParticipants = InvitationHelper.AddPersonToOutlookParticipantList(frPerson, meetingParticipants, person.Required);
                        }
                    }
                }
                else
                {
                    throw new IpoValidationException(
                              $"Could not find functional role with functional role code '{participant.InvitedFunctionalRole.Code}' on participant {participant.Organization}.");
                }
            }
            return(meetingParticipants);
        }
Пример #25
0
        public void HandleMessage(LobbyPlayer player, Message m)
        {
            var rtn = Message.Create(m.Type);

            switch (m.Type)
            {
            case "getCrew":
            {
                this.LoadCrew(Regex.Replace(m.GetString(0), @"\s+", "").ToLower(),
                              crew => crew.SendGetMessage(player));
                break;
            }

            case "getMyCrews":
            {
                this.GetMyCrews(rtn, player);
                break;
            }

            case "createCrew":
            {
                this.CreateCrew(rtn, player, m.GetString(0).Trim());
                break;
            }

            case "getCrewInvites":
            {
                InvitationHelper.GetInvitationsTo(this.client.BigDB, InvitationType.Crew,
                                                  player.Name, invites =>
                    {
                        var invitesIds =
                            invites.Where(it => it.Status == InvitationStatus.Pending)
                            .Select(it => it.Sender)
                            .ToArray();
                        if (invitesIds.Length > 0)
                        {
                            this.client.BigDB.LoadKeys("Crews", invitesIds, crews =>
                            {
                                foreach (var crew in crews.Where(crew => crew != null))
                                {
                                    rtn.Add(crew.Key);
                                    rtn.Add(crew.GetString("Name"));
                                    rtn.Add(crew.GetString("LogoWorld", ""));
                                }

                                player.Send(rtn);
                            });
                        }
                        else
                        {
                            player.Send(rtn);
                        }
                    });
                break;
            }

            case "blockCrewInvites":
            {
                var crewId      = m.GetString(0).ToLower();
                var shouldBlock = m.GetBoolean(1);

                InvitationBlocking.BlockCrew(this.client.BigDB, player.ConnectUserId, crewId, shouldBlock, () =>
                    {
                        if (shouldBlock)
                        {
                            InvitationHelper.GetInvitation(this.client.BigDB, InvitationType.Crew, crewId, player.Name,
                                                           invitation =>
                            {
                                if (invitation.Exists)
                                {
                                    invitation.Status = InvitationStatus.Rejected;
                                    invitation.Save(() => player.Send(m.Type, true));
                                }
                                else
                                {
                                    player.Send(m.Type, true);
                                }
                            });
                        }
                        else
                        {
                            player.Send(m.Type, true);
                        }
                    });
                break;
            }

            case "blockAllCrewInvites":
            {
                var shouldBlock = m.GetBoolean(0);

                InvitationBlocking.BlockAllCrews(this.client.BigDB, player.ConnectUserId, shouldBlock);
                player.Send(m.Type, shouldBlock);
                break;
            }
            }
        }
Пример #26
0
        private void InviteMember(BasePlayer player, string username, Callback successCallback,
                                  Callback <InvitationError> errorCallback)
        {
            if (!this.crew.HasPower(player, CrewPower.MembersManagement))
            {
                errorCallback(InvitationError.NotAllowed);
                return;
            }

            this.crew.GetMembers(members =>
            {
                if (members.Count >= 25)
                {
                    errorCallback(InvitationError.LimitReached);
                    return;
                }

                var member = members.FirstOrDefault(it => it.Name == username);
                if (member != null)
                {
                    errorCallback(InvitationError.AlreadyAdded);
                    return;
                }

                CommonPlayer.GetId(this.PlayerIO.BigDB, username, userId =>
                {
                    if (userId == null)
                    {
                        errorCallback(InvitationError.PlayerNotFound);
                        return;
                    }

                    InvitationHelper.GetInvitation(this.PlayerIO.BigDB, InvitationType.Crew,
                                                   this.crewId, username, oldInvitation =>
                    {
                        if (oldInvitation.Exists)
                        {
                            errorCallback(InvitationError.AlreadySent);
                            return;
                        }

                        InvitationBlocking.IsCrewBlocked(this.PlayerIO.BigDB, username, this.crewId, blocked =>
                        {
                            if (blocked)
                            {
                                errorCallback(InvitationError.Blocked);
                                return;
                            }

                            var newInvitation = new DatabaseObject();
                            newInvitation.Set("Sender", this.crewId);
                            newInvitation.Set("Recipient", username);
                            newInvitation.Set("Status", (int)InvitationStatus.Pending);

                            InvitationHelper.CreateInvitation(this.PlayerIO.BigDB, InvitationType.Crew,
                                                              this.crewId, username,
                                                              invitation => successCallback());
                        });
                    });
                });
            });
        }
Пример #27
0
        public override void GotMessage(CommonPlayer player, Message message)
        {
            if (!this.initialized)
            {
                this.queue.Add(new QueueItem(player, message));
                this.ProcessQueue();
                return;
            }

            if (message.Type == "getCrew")
            {
                this.crew.SendGetMessage(player);
                return;
            }

            if (player.IsGuest)
            {
                return;
            }

            switch (message.Type)
            {
            case "swapUsers":
            {
                if (player.ConnectUserId != "merge")
                {
                    break;
                }

                this.crew.SwapMembers(message.GetString(0), message.GetString(1), () => player.Send(message.Type));
                break;
            }

            case "subscribe":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Subscribing to contest crews is disabled.");
                    return;
                }
                if (this.crewId == "everybodyeditsstaff")
                {
                    break;
                }

                NotificationHelper.AddSubscription(this.PlayerIO.BigDB, player.ConnectUserId, "crew" + this.crewId,
                                                   subscribed =>
                    {
                        if (subscribed)
                        {
                            this.crew.Subscribers++;
                            this.crew.Save();
                        }
                        player.Send(message.Type, this.crew.Subscribers);
                    });
                break;
            }

            case "unsubscribe":
            {
                if (this.crewId == "everybodyeditsstaff")
                {
                    break;
                }

                NotificationHelper.RemoveSubscription(this.PlayerIO.BigDB, player.ConnectUserId,
                                                      "crew" + this.crewId,
                                                      unsubscribed =>
                    {
                        if (unsubscribed)
                        {
                            if (crew.Subscribers > 0)
                            {
                                this.crew.Subscribers--;
                                this.crew.Save();
                            }
                        }
                        player.Send(message.Type, this.crew.Subscribers);
                    });
                break;
            }

            case "answerInvite":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Joining is disabled for contest crews.");
                    return;
                }
                var accept = message.GetBoolean(0);

                InvitationHelper.GetInvitation(this.PlayerIO.BigDB, InvitationType.Crew,
                                               this.crewId, player.Name, invitation =>
                    {
                        var rtn = Message.Create(message.Type);

                        if (!invitation.Exists)
                        {
                            this.SendErrorReply(rtn, player, "Crew invite not found.");
                            return;
                        }
                        if (invitation.Status != InvitationStatus.Pending)
                        {
                            this.SendErrorReply(rtn, player, "Invitation already answered.");
                            return;
                        }
                        if (crew.IsMember(player))
                        {
                            this.SendErrorReply(rtn, player, "Already member of crew.");
                            return;
                        }

                        this.PlayerIO.BigDB.Load("CrewMembership", player.ConnectUserId, membership =>
                        {
                            if (accept)
                            {
                                if (membership != null && membership.Count >= 10)
                                {
                                    this.SendErrorReply(rtn, player, "You can't be in more than 10 crews.");
                                    return;
                                }

                                invitation.Status = InvitationStatus.Accepted;
                                crew.AddMember(player);
                            }
                            else
                            {
                                invitation.Status = InvitationStatus.Rejected;
                            }

                            rtn.Add(true);
                            invitation.Save(() => player.Send(rtn));
                        });
                    });
                break;
            }
            }

            if (!this.crew.IsMember(player))
            {
                return;
            }

            switch (message.Type)
            {
            case "setMemberInfo":
            {
                var username = message.GetString(0).ToLower();
                var about    = message.GetString(1);
                if (about.Length > 100)
                {
                    about = about.Substring(100);
                }

                this.SetMemberInfo(Message.Create(message.Type), player, username, about);
                break;
            }

            case "setMemberRank":
            {
                var username = message.GetString(0).ToLower();
                var rank     = message.GetInt(1);

                this.SetMemberRank(Message.Create(message.Type), player, username, rank);
                break;
            }

            case "editRank":
            {
                var rankId = message.GetInt(0);
                var name   = message.GetString(1).Trim();
                var powers = message.GetString(2);

                this.EditRank(Message.Create(message.Type), player, rankId, name, powers);
                break;
            }

            case "removeMember":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Removing members is disabled for contest crews.");
                    return;
                }
                var username = message.GetString(0).ToLower();

                this.RemoveMember(Message.Create(message.Type), player, username);
                break;
            }

            case "leaveCrew":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Leaving the crew is disabled for contest crews.");
                    return;
                }

                if (crew.IsMember(player) && !crew.GetRank(player).IsOwner)
                {
                    crew.DatabaseObject.GetObject("Members").Remove(player.ConnectUserId);
                    this.PlayerIO.BigDB.LoadOrCreate("CrewMembership", player.ConnectUserId, membership =>
                        {
                            membership.Remove(this.crewId);
                            membership.Save();
                            this.crew.Save();
                            player.Send(message.Type);
                            player.Disconnect();
                        });
                }
                break;
            }

            case "inviteMember":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Inviting members is disabled for contest crews.");
                    return;
                }

                var username = message.GetString(0).ToLower();

                this.InviteMember(player, username,
                                  () => player.Send(message.Type, true),
                                  error =>
                    {
                        switch (error)
                        {
                        case InvitationError.AlreadyAdded:
                            {
                                player.Send(message.Type, false,
                                            "This user is already a member of this crew.");
                                break;
                            }

                        case InvitationError.AlreadySent:
                            {
                                player.Send(message.Type, false,
                                            "This user already has a pending invitation.");
                                break;
                            }

                        case InvitationError.PlayerNotFound:
                            {
                                player.Send(message.Type, false,
                                            "Unknown user. Please check your spelling.");
                                break;
                            }

                        case InvitationError.Blocked:
                            {
                                player.Send(message.Type, false,
                                            "This user is blocking all crew invitations.");
                                break;
                            }

                        case InvitationError.NotAllowed:
                            {
                                player.Send(message.Type, false,
                                            "You have not been given rights to invite new members to this crew.");
                                break;
                            }

                        case InvitationError.LimitReached:
                            {
                                player.Send(message.Type, false,
                                            "Crew members limit reached.");
                                break;
                            }

                        default:
                            {
                                player.Send(message.Type, false,
                                            "Something went wrong. Try again later.");
                                break;
                            }
                        }
                    });
                break;
            }

            case "deleteInvite":
            {
                var recipientName = message.GetString(0).ToLower();

                if (!crew.HasPower(player, CrewPower.MembersManagement))
                {
                    player.Send(message.Type, false);
                }
                else
                {
                    InvitationHelper.DeleteInvitation(this.PlayerIO.BigDB, InvitationType.Crew,
                                                      this.crewId, recipientName, success =>
                        {
                            if (!success)
                            {
                                this.PlayerIO.ErrorLog.WriteError(
                                    "Error deleting crew invitation from " + this.crewId + " to " +
                                    recipientName, "Invite not found",
                                    "Error deleting pending invitation", null);
                            }
                            player.Send(message.Type, success);
                        });
                }
                break;
            }

            case "getPendingInvites":
            {
                if (!crew.HasPower(player, CrewPower.MembersManagement))
                {
                    player.Send(message.Type, false);
                }
                else
                {
                    InvitationHelper.GetInvitationsFrom(this.PlayerIO.BigDB, InvitationType.Crew,
                                                        this.crewId, invites =>
                        {
                            var rtn = Message.Create(message.Type);
                            rtn.Add(true);
                            foreach (var invite in invites)
                            {
                                rtn.Add(invite.Recipient);
                                rtn.Add((int)invite.Status);
                            }
                            player.Send(rtn);
                        });
                }
                break;
            }

            case "sendAlert":
            {
                if (!this.crew.HasPower(player, CrewPower.AlertSending))
                {
                    player.Send(message.Type, "You don't have rights to send alerts from this crew.");
                    break;
                }

                var text = message.GetString(0).Trim();
                if (text.Length > 140)
                {
                    text = text.Substring(0, 140);
                }

                this.crew.PublishNotification(text, notification =>
                    {
                        player.Send("info", "Success", "Alert sent to all crew subscribers.");
                        player.Send(message.Type);
                    });
                break;
            }

            case "setColors":
            {
                if (!this.crew.HasPower(player, CrewPower.ProfileCustomization))
                {
                    break;
                }

                if (!this.crew.Unlocked("ColorPick"))
                {
                    break;
                }

                this.crew.TextColor      = message.GetUInt(0);
                this.crew.PrimaryColor   = message.GetUInt(1);
                this.crew.SecondaryColor = message.GetUInt(2);
                this.crew.SetUnlocked("ColorPick", false);

                this.crew.Save();
                break;
            }

            case "setFaceplate":
            {
                if (!this.crew.HasPower(player, CrewPower.ProfileCustomization))
                {
                    break;
                }

                var id    = message.GetString(0).ToLower();
                var color = message.GetInt(1);

                if ((id != "none" && id != "" && !this.crew.Faceplates.Contains(id)) || color < 0 || color > 9)
                {
                    break;
                }

                if (id == "none")
                {
                    id = "";
                }

                this.crew.Faceplate      = id;
                this.crew.FaceplateColor = color;
                this.crew.Save();
                break;
            }

            case "disband":
            {
                if (crew.isContest)
                {
                    this.SendErrorReply(Message.Create(message.Type), player, "Disbanding the crew is disabled for contest crews.");
                    return;
                }

                if (!this.crew.GetRank(player).IsOwner)
                {
                    break;
                }

                // Cleanup membership of all members
                var members = this.crew.DatabaseObject.GetObject("Members").Properties.ToArray();
                this.PlayerIO.BigDB.LoadKeys("CrewMembership", members, membership =>
                    {
                        foreach (var m in membership.Where(m => m != null))
                        {
                            m.Remove(this.crewId);
                            m.Save();
                        }
                    });

                // Cleanup all pending invitations. People can't join here anymore
                InvitationHelper.GetInvitationsFrom(this.PlayerIO.BigDB, InvitationType.Crew,
                                                    this.crewId, invites => { InvitationHelper.DeleteInvitations(this.PlayerIO.BigDB, invites); });

                // Consume one "crew" PayVault item to allow user to buy another crew since this one is no longer active
                player.PayVault.Refresh(() =>
                    {
                        var crewItem = player.PayVault.First("crew");
                        if (crewItem != null)
                        {
                            player.PayVault.Consume(new[] { crewItem }, this.SetAsInvalid,
                                                    error => { this.SetAsInvalid(); });
                        }
                        else
                        {
                            this.SetAsInvalid();
                        }
                    });

                // Delete the crew object
                this.crew.Disband();

                player.Send(message.Type);

                break;
            }

            default:
            {
                this.shop.GotMessage(player, message);
                break;
            }
            }
        }
Пример #28
0
        private void CreateInvitation(string recipientName,
                                      Callback successCallback, Callback <InvitationError> errorCallback)
        {
            if (this.name == recipientName)
            {
                errorCallback(InvitationError.SendingToSelf);
                return;
            }

            CommonPlayer.GetId(this.client.BigDB, recipientName, recipientId =>
            {
                if (recipientId == null)
                {
                    errorCallback(InvitationError.PlayerNotFound);
                    return;
                }

                this.GetFriendKeys(this.connectUserId, friends =>
                {
                    if (friends.Contains(recipientId))
                    {
                        errorCallback(InvitationError.AlreadyAdded);
                        return;
                    }

                    InvitationHelper.GetInvitation(this.client.BigDB, InvitationType.Friend,
                                                   this.name, recipientName, oldInvitation =>
                    {
                        if (oldInvitation.Exists)
                        {
                            errorCallback(InvitationError.AlreadySent);
                            return;
                        }

                        this.GetPendingInvitationsCount(pendingInvitationsCount =>
                        {
                            if (friends.Count + pendingInvitationsCount >= this.MaxFriendsAllowed)
                            {
                                errorCallback(InvitationError.LimitReached);
                                return;
                            }

                            InvitationHelper.GetInvitation(this.client.BigDB, InvitationType.Friend,
                                                           recipientName, this.name, invitationToMe =>
                            {
                                if (invitationToMe.Exists && invitationToMe.Status == InvitationStatus.Pending)
                                {
                                    invitationToMe.Status = InvitationStatus.Accepted;
                                    this.AddOrRemoveFriend(recipientId, true,
                                                           () => invitationToMe.Save(successCallback));
                                    return;
                                }

                                InvitationBlocking.IsUserBlocked(this.client.BigDB, recipientId, this.name,
                                                                 blocked =>
                                {
                                    if (blocked)
                                    {
                                        errorCallback(InvitationError.Blocked);
                                        return;
                                    }

                                    var newInvitation = new DatabaseObject();
                                    newInvitation.Set("Sender", this.name);
                                    newInvitation.Set("Recipient", recipientName);
                                    newInvitation.Set("Status", (int)InvitationStatus.Pending);

                                    InvitationHelper.CreateInvitation(this.client.BigDB,
                                                                      InvitationType.Friend,
                                                                      this.name, recipientName,
                                                                      invitation => successCallback());
                                });
                            });
                        });
                    });
                });
            });
        }