public PartyJoinResult PartyJoin(PartyJoinRequest request)
 {
     return(new PartyJoinResult
     {
         Result = new ServiceResult <PartyStatus>
         {
             Data = new PartyStatus
             {
                 Party = new PartyId
                 {
                     Id = "1"
                 },
                 SessionMembers = new List <PartyMemberDto>
                 {
                     new PartyMemberDto
                     {
                         User = new UserId
                         {
                             Id = 1
                         },
                         IsOwner = true
                     }
                 },
                 MatchmakeState = 0,
                 GameData = new byte[100]
             }
         }
     });
 }
        public void Setup()
        {
            _partyMatched = new PartyDataModel(LeaderPartyMatched, Pit);
            _partyMatched.AddPlayerToParty(PlayerPartyMatched, Pit);
            _matchedPartyJoinRequest = new PartyJoinRequest(_partyMatched, "type-matched", null);
            _partyError              = new PartyDataModel(LeaderPartyError, Pit);
            _errorPartyJoinRequest   = new PartyJoinRequest(_partyError, "type-error", null);
            _partyRequeue            = new PartyDataModel(LeaderPartyRequeue, Pit);
            _requeuePartyJoinRequest = new PartyJoinRequest(_partyRequeue, "type-requeue", null);

            _logger    = new Mock <ILogger>();
            Log.Logger = _logger.Object;

            _transaction = new Mock <ITransaction>(MockBehavior.Strict);
            _transaction.Setup(tx => tx.Dispose());

            _memoryStoreClient = new Mock <IMemoryStoreClient>(MockBehavior.Strict);
            _memoryStoreClient.Setup(client => client.Dispose());
            _memoryStoreClient.Setup(client => client.CreateTransaction()).Returns(_transaction.Object);

            var memoryStoreClientManager = new Mock <IMemoryStoreClientManager <IMemoryStoreClient> >();

            memoryStoreClientManager.Setup(manager => manager.GetClient()).Returns(_memoryStoreClient.Object);
            _service = new GatewayInternalServiceImpl(memoryStoreClientManager.Object);
        }
 public PartyJoinRequestsListItemViewModel(PartyJoinRequest request)
 {
     ID          = request.ID;
     Avatar      = new SmallEntityAvatarViewModel(request.Citizen.Entity);
     Message     = request.Message;
     RequestDay  = request.Day;
     RequestTime = request.DateTime;
 }
Beispiel #4
0
 private static WaitingParty ConvertToProto(PartyJoinRequest request)
 {
     return(new WaitingParty
     {
         Party = ConvertToProto(request.Party),
         Metadata = { request.Metadata }
     });
 }
Beispiel #5
0
        public void CancelJoinRequest(PartyJoinRequest request)
        {
            var citizenLink = EntityLinkCreator.Create(request.Citizen.Entity);
            var message     = $"{citizenLink} canceled join request";

            using (NoSaveChanges)
                warningService.AddWarning(request.PartyID, message);

            partyJoinRequestRepository.Remove(request);
            partyJoinRequestRepository.SaveChanges();
        }
Beispiel #6
0
        public void DeclineJoinRequest(PartyJoinRequest request)
        {
            var partyLink = EntityLinkCreator.Create(request.Party.Entity);
            var message   = $"Your request to {partyLink} was declined.";

            using (NoSaveChanges)
                warningService.AddWarning(request.CitizenID, message);

            partyJoinRequestRepository.Remove(request);
            partyJoinRequestRepository.SaveChanges();
        }
Beispiel #7
0
        public MethodResult CanCancelJoinRequest(PartyJoinRequest request, Citizen citizen)
        {
            if (request == null)
            {
                return(new MethodResult("Request does not exist!"));
            }
            if (request.CitizenID != citizen.ID)
            {
                return(new MethodResult("You cannot remove someone's request!"));
            }

            return(MethodResult.Success);
        }
Beispiel #8
0
        public void AcceptJoinRequest(PartyJoinRequest request)
        {
            var partyLink = EntityLinkCreator.Create(request.Party.Entity);
            var message   = $"Your join request to party {partyLink} was accepted";

            using (NoSaveChanges)
            {
                JoinParty(request.Citizen, request.Party);
                warningService.AddWarning(request.CitizenID, message);
            }


            partyJoinRequestRepository.SaveChanges();
        }
        public void ReturnAnEquivalentPartyJoinRequest()
        {
            var partyJoinRequest = new PartyJoinRequest(new PartyDataModel("Leader", "PIT"), "type",
                                                        new Dictionary <string, string> {
                { "cmf", "cmz" }
            });
            var serializedPartyJoinRequest   = JsonConvert.SerializeObject(partyJoinRequest);
            var deserializedPartyJoinRequest =
                JsonConvert.DeserializeObject <PartyJoinRequest>(serializedPartyJoinRequest);

            Assert.AreEqual(partyJoinRequest.Id, deserializedPartyJoinRequest.Id);
            Assert.AreEqual(partyJoinRequest.Party.Id, deserializedPartyJoinRequest.Party.Id);
            Assert.AreEqual(partyJoinRequest.Type, deserializedPartyJoinRequest.Type);
            Assert.AreEqual(0, deserializedPartyJoinRequest.Score);
            Assert.IsNull(deserializedPartyJoinRequest.QueueName);
            CollectionAssert.AreEquivalent(partyJoinRequest.Metadata, deserializedPartyJoinRequest.Metadata);
        }
Beispiel #10
0
        public MethodResult CanDeclineJoinRequest(PartyJoinRequest request, Citizen citizen)
        {
            if (request == null)
            {
                return(new MethodResult("Request does not exist!"));
            }

            if (IsPartyMember(citizen, request.Party).IsError)
            {
                return(new MethodResult("Citizen is not a member of the party!"));
            }

            if (GetPartyRole(citizen, request.Party) == PartyRoleEnum.Member)
            {
                return(new MethodResult("You cannot do that!"));
            }

            return(MethodResult.Success);
        }
Beispiel #11
0
        public void SendJoinRequest(Citizen citizen, Party party, string message)
        {
            var request = new PartyJoinRequest()
            {
                Day       = GameHelper.CurrentDay,
                CitizenID = citizen.ID,
                DateTime  = DateTime.Now,
                PartyID   = party.ID,
                Message   = message
            };
            var citizenLink  = EntityLinkCreator.Create(citizen.Entity);
            var requestsLink = LinkCreator.Create("join requests", "JoinRequests", "Party", new { partyID = party.ID });

            var warningMessage = $"{citizenLink} send join requests. You can see actual {requestsLink} to accept or decline them.";

            using (NoSaveChanges)
                warningService.AddWarning(party.ID, warningMessage);

            partyJoinRequestRepository.Add(request);
            ConditionalSaveChanges(partyJoinRequestRepository);
        }
Beispiel #12
0
 public void RemoveJoinRequest(PartyJoinRequest request)
 {
     context.PartyJoinRequests.Remove(request);
 }
Beispiel #13
0
 public void AddJoinRequest(PartyJoinRequest request)
 {
     context.PartyJoinRequests.Add(request);
 }
Beispiel #14
0
        protected override async Task Handle(GameStageUser stageUser, IFieldObjUser user, IPacketReader packet)
        {
            var stage   = stageUser.Stage;
            var service = stage.PartyService;
            var type    = (PartyResultCode)packet.ReadByte();

            switch (type)
            {
            case PartyResultCode.InviteParty_Sent:
            case PartyResultCode.InviteParty_AlreadyInvited:
            case PartyResultCode.InviteParty_AlreadyInvitedByInviter:
                break;     // Do nothing

            case PartyResultCode.InviteParty_Accepted:
            {
                var serviceRequest = new InviteClaimRequest {
                    Type = InviteType.Party, Invited = user.ID
                };
                var serviceResponse = await stage.InviteService.Claim(serviceRequest);

                if (serviceResponse.Result == InviteServiceResult.Ok)
                {
                    var result   = PartyResultCode.JoinParty_Done;
                    var response = new UnstructuredOutgoingPacket(PacketSendOperations.PartyResult);
                    var party    = stage.GetUser(serviceResponse.Invite.Inviter)?.FieldUser?.Party?.ID;

                    if (party == null)
                    {
                        result = PartyResultCode.JoinParty_UnknownUser;
                    }
                    else
                    {
                        var joinRequest = new PartyJoinRequest
                        {
                            Party  = party.Value,
                            Member = new PartyMemberContract
                            {
                                Id      = user.ID,
                                Name    = user.Character.Name,
                                Job     = user.Character.Job,
                                Level   = user.Character.Level,
                                Channel = stage.ChannelID,
                                Field   = user.Field.ID
                            }
                        };
                        var joinResponse = await service.Join(joinRequest);

                        if (joinResponse.Result == PartyServiceResult.Ok)
                        {
                            return;
                        }
                        if (joinResponse.Result == PartyServiceResult.FailedAlreadyInParty)
                        {
                            result = PartyResultCode.JoinParty_AlreadyJoined;
                        }
                        if (joinResponse.Result == PartyServiceResult.FailedFullParty)
                        {
                            result = PartyResultCode.JoinParty_AlreadyFull;
                        }
                    }

                    response.WriteByte((byte)result);

                    await user.Dispatch(response);
                }
                break;
            }

            case PartyResultCode.InviteParty_Rejected:
            {
                if (user.Party != null)
                {
                    return;
                }

                var serviceRequest = new InviteClaimRequest {
                    Type = InviteType.Party, Invited = user.ID
                };
                var serviceResponse = await stage.InviteService.Claim(serviceRequest);

                if (serviceResponse.Result == InviteServiceResult.Ok)
                {
                    var inviter  = serviceResponse.Invite.Inviter;
                    var dispatch = new UnstructuredOutgoingPacket(PacketSendOperations.PartyResult)
                                   .WriteByte((byte)PartyResultCode.ServerMsg)
                                   .WriteBool(true)
                                   .WriteString($"'{user.Character.Name}' rejected the party invitation request.");
                    var dispatchRequest = new DispatchToCharactersRequest {
                        Data = ByteString.CopyFrom(dispatch.Buffer)
                    };

                    dispatchRequest.Characters.Add(inviter);

                    await stage.DispatchService.DispatchToCharacters(dispatchRequest);
                }
                break;
            }

            default:
                stage.Logger.LogWarning($"Unhandled party result type: {type}");
                break;
            }
        }
Beispiel #15
0
        public async Task <PartyJoinResponse> Join(PartyJoinRequest request)
        {
            var source = new CancellationTokenSource();

            source.CancelAfter(PartyLockTimeoutDuration);

            var @lock = await _locker.AcquireAsync(PartyLockKey, cancellationToken : source.Token);

            if (@lock != null)
            {
                var result = PartyServiceResult.Ok;
                var party  = await _repository.Retrieve(request.Party);

                if (await _repository.RetrieveByMember(request.Member.Id) != null)
                {
                    result = PartyServiceResult.FailedAlreadyInParty;
                }
                if (party == null)
                {
                    result = PartyServiceResult.FailedNonExistentParty;
                }
                else if (party.Members.Any(m => m.ID == request.Member.Id))
                {
                    result = PartyServiceResult.FailedAlreadyInParty;
                }
                else if (party.Members.Count >= 6)
                {
                    result = PartyServiceResult.FailedFullParty;
                }

                if (result == PartyServiceResult.Ok)
                {
                    party.Members.Add(new PartyMemberRecord(request.Member));

                    await _repository.Update(party);

                    await Task.WhenAll(party.Members.Select(async m =>
                    {
                        var packet = new UnstructuredOutgoingPacket(PacketSendOperations.PartyResult);

                        packet.WriteByte((byte)PartyResultCode.JoinParty_Done);
                        packet.WriteInt(party.ID);
                        packet.WriteString(request.Member.Name);
                        packet.WritePartyData(party, m.Channel);

                        var dispatchRequest = new DispatchToCharactersRequest {
                            Data = ByteString.CopyFrom(packet.Buffer)
                        };

                        dispatchRequest.Characters.Add(m.ID);

                        await _dispatcher.DispatchToCharacters(dispatchRequest);
                    }));

                    await _messenger.PublishAsync(new PartyUpdateEvent { Party = party });
                }

                await @lock.ReleaseAsync();

                return(new PartyJoinResponse {
                    Result = result, Party = party?.ToContract()
                });
            }

            return(new PartyJoinResponse {
                Result = PartyServiceResult.FailedTimeout
            });
        }
Beispiel #16
0
        public override async Task <Operation> Join(JoinRequestProto request, ServerCallContext context)
        {
            // TODO(dom): refactor this later.
            var playerIdentifier = AuthHeaders.ExtractPlayerId(context);

            using (var memClient = _memoryStoreClientManager.GetClient())
            {
                try
                {
                    var party = await GetPartyForMember(memClient, playerIdentifier) ??
                                throw new EntryNotFoundException(playerIdentifier);

                    if (party.LeaderPlayerId != playerIdentifier)
                    {
                        throw new RpcException(new Status(StatusCode.PermissionDenied,
                                                          "Only the leader can start matchmaking"));
                    }

                    if (!party.SufficientMembers())
                    {
                        throw new RpcException(new Status(StatusCode.FailedPrecondition,
                                                          "There are not enough members in the party to start matchmaking"));
                    }

                    party.CurrentPhase = PartyDataModel.Phase.Matchmaking;

                    var matchmakingMetadata = new Dictionary <string, string>(request.Metadata);
                    var partyJoinRequest    = new PartyJoinRequest(party, request.MatchmakingType, matchmakingMetadata);
                    var entriesToCreate     = new List <Entry> {
                        partyJoinRequest
                    };
                    entriesToCreate.AddRange(CreateJoinRequestsForEachMember(party, request.MatchmakingType,
                                                                             matchmakingMetadata));

                    using (var tx = memClient.CreateTransaction())
                    {
                        tx.UpdateAll(party.Yield());
                        tx.CreateAll(entriesToCreate);
                        tx.EnqueueAll(partyJoinRequest.Yield());
                    }
                }
                catch (EntryNotFoundException)
                {
                    Log.Information("Player is not a member of any party");
                    throw new RpcException(new Status(StatusCode.NotFound, "player is not a member of any party"));
                }
                catch (EntryAlreadyExistsException e)
                {
                    Reporter.JoinRequestQueuedInc();
                    Log.Information($"Party already queued: {e.Id}.");
                    throw new RpcException(new Status(StatusCode.AlreadyExists,
                                                      "party is already queued for matchmaking"));
                }
                catch (TransactionAbortedException)
                {
                    Reporter.TransactionAbortedInc("Join");
                    Log.Warning("Transaction for join was aborted");
                    throw new RpcException(new Status(StatusCode.Unavailable,
                                                      "join aborted due to concurrent modification; safe to retry"));
                }
            }

            Reporter.JoinRequestInc();
            Log.Information($"Created party join request for the party associated to player ${playerIdentifier}.");
            return(new Operation
            {
                Name = playerIdentifier
            });
        }