Ejemplo n.º 1
0
        private Message ProcJoinRequest(Message msg)
        {
            OutputManager.Server.Write("Processing join request...");
            Messages.JoinRequest jrMsg = new JoinRequest(msg.ToString());
            OutputManager.Server.Write("Finding join point...");
            Messages.ResourceOwnerRequest joinPointRequest = new Messages.ResourceOwnerRequest(this.localNode, jrMsg.senderID);
            OutputManager.Server.Write("Awaiting to process...");
            Message tmp = ProcResourceOwnerRequest(joinPointRequest);

            OutputManager.Server.Write("process awaited");
            Messages.ResourceOwnerResponse joinPointResponse = tmp as Messages.ResourceOwnerResponse;
            Messages.JoinResponse          rMsg; // Used to create the response message later

            if (joinPointResponse == null)
            {
                OutputManager.Server.Write("No join point found." + (tmp == null ? "null" : tmp.ToString()));
                OutputManager.Server.Write("Join request failed!");
                rMsg             = new Messages.JoinResponse(this.localNode, this.localNode, this.localNode);
                rMsg.isProcessed = false;
            }
            else
            {
                OutputManager.Server.Write("Generating Pred and Succ nodes...");
                ChordNode succNode = new ChordNode(joinPointResponse.ownerIpAddress, joinPointResponse.ownerPort, joinPointResponse.ownerId);
                ChordNode predNode = new ChordNode(joinPointResponse.predIpAddress, joinPointResponse.predPort, joinPointResponse.predId);
                OutputManager.Server.Write("Generating a response...");
                rMsg             = new Messages.JoinResponse(this.localNode, succNode, predNode);
                rMsg.isProcessed = true;
                OutputManager.Server.Write("Join request processed!");
            }
            return(rMsg);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///   This override replaces the lite <see cref = "Lite.Operations.JoinRequest" /> with the lobby <see cref = "JoinRequest" /> and enables lobby support.
        /// </summary>
        /// <param name = "operationRequest">
        ///   The operation request.
        /// </param>
        /// <param name = "sendParameters">
        ///   The send Parameters.
        /// </param>
        protected override void HandleJoinOperation(OperationRequest operationRequest, SendParameters sendParameters)
        {
            // create join operation from the operation request
            var joinRequest = new JoinRequest(this.Protocol, operationRequest);

            if (!this.ValidateOperation(joinRequest, sendParameters))
            {
                return;
            }

            // check the type of join operation
            if (joinRequest.GameId.EndsWith(LobbySuffix))
            {
                // the game name ends with the lobby suffix
                // the client wants to join a lobby
                this.HandleJoinLobby(joinRequest, sendParameters);
            }
            else if (string.IsNullOrEmpty(joinRequest.LobbyId) == false)
            {
                // the lobbyId is set
                // the client wants to join a game with a lobby
                this.HandleJoinGameWithLobby(joinRequest, sendParameters);
            }
            else
            {
                base.HandleJoinOperation(operationRequest, sendParameters);
            }
        }
Ejemplo n.º 3
0
        public async Task JoinAsync(JoinRequest request)
        {
            this.room = await this.Group.AddAsync(request.RoomName);

            this.myName = request.UserName;

            this.Broadcast(this.room).OnJoin(request.UserName);

            // dummy external operation db.
            using (var activity = mysqlActivity.StartActivity("db:room/insert", ActivityKind.Internal))
            {
                // this is sample. use orm or any safe way.
                activity.SetTag("table", "rooms");
                activity.SetTag("query", $"INSERT INTO rooms VALUES (0, '@room', '@username', '1');");
                activity.SetTag("parameter.room", request.RoomName);
                activity.SetTag("parameter.username", request.UserName);
                await Task.Delay(TimeSpan.FromMilliseconds(2));
            }
            using (var activity = redisActivity.StartActivity($"redis:member/status", ActivityKind.Internal))
            {
                activity.SetTag("command", "set");
                activity.SetTag("parameter.key", this.myName);
                activity.SetTag("parameter.value", "1");
                await Task.Delay(TimeSpan.FromMilliseconds(1));
            }

            // use hub trace context to set your span on same level. Otherwise parent will automatically set.
            var hubTraceContext = this.Context.GetTraceContext();

            using (var activity = magiconionActivity.StartActivity("ChatHub:hub_context_relation", ActivityKind.Internal, hubTraceContext))
            {
                // this is sample. use orm or any safe way.
                activity.SetTag("message", "this span has no relationship with this method but relate with hub context. This means no relation with parent method.");
            }
        }
Ejemplo n.º 4
0
        public async Task RequestToJoinGroupById(long groupId, long userId)
        {
            Group currentGroup = await GetGroup(groupId);

            if (currentGroup.IsPublic == false)
            {
                JoinRequest joinRequest = new JoinRequest
                {
                    GroupId = groupId,
                    UserId  = userId
                };

                _context.JoinRequests.Add(joinRequest);
                await _context.SaveChangesAsync();
            }
            else
            {
                var groupUser = new GroupUser
                {
                    GroupId = groupId,
                    UserId  = userId,
                    Role    = Role.user
                };

                _context.GroupUsers.Add(groupUser);
                await _context.SaveChangesAsync();
            }
        }
        public JsonResult PromoteUserToAdmin(JoinRequest userBan)
        {
            string connStr     = ConfigurationManager.ConnectionStrings["MySQLConn"].ConnectionString;
            string returnValue = "welcome";

            HttpCookie userCookie = Request.Cookies["token"];

            MySqlConnection conn = new MySqlConnection(connStr);

            try
            {
                conn.Open();
                string          sql = "SELECT s.* FROM Token as t, User as u, ServerMember as sa, Server as s where t.token like '" + userCookie.Value + "' and t.idUser = u.id and sa.idUser = u.id and sa.idServer = s.id and s.id=" + userBan.ServerId + " and sa.userRole=1;";
                MySqlCommand    cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    rdr.Close();


                    conn.Close();
                    conn.Open();

                    sql = "SELECT * FROM ServerMember where idUser="******" and idServer=" + userBan.ServerId;
                    cmd = new MySqlCommand(sql, conn);
                    rdr = cmd.ExecuteReader();

                    if (rdr.HasRows)
                    {
                        rdr.Close();

                        conn.Close();
                        conn.Open();
                        sql = "UPDATE ServerMember SET userRole=1 WHERE idServer=" + userBan.ServerId + " and idUser="******"User promoted to admin!";
                    }
                }
                else
                {
                    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    returnValue         = "Unknown error!";
                }

                rdr.Close();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                returnValue         = "Unexcepted error!";
            }
            conn.Close();

            return(Json(returnValue));
        }
Ejemplo n.º 6
0
        public override async Task join(JoinRequest request, IServerStreamWriter <Message> responseStream, ServerCallContext context)
        {
            var observable = await _repo.GetCommentsObservable(request);

            var breakCount = 0;

            using (var subscription = observable.Subscribe(async(message) =>
            {
                try
                {
                    if (breakCount < 3)
                    {
                        await responseStream.WriteAsync(message);
                        breakCount = 0;
                    }
                }
                catch (Exception e)
                {
                    breakCount++;
                    _logger.LogError(e, "Error while writing comments to response.");
                }
            }))
            {
                _logger.LogInformation("User {UserId} subscribed to video {VideoId}", request.UserId, request.VideoId);
                //This is to prevent the response stream from being disposed
                while (breakCount < 3)
                {
                    await Task.Delay(1000);
                }
            }
        }
        public JoinRequest Update(JoinRequest updatedJoinRequest)
        {
            DeleteById(updatedJoinRequest.Id);
            JoinRequests.Add(updatedJoinRequest);

            return(updatedJoinRequest);
        }
Ejemplo n.º 8
0
        protected virtual Actor HandleJoinGameOperation(LitePeer peer, JoinRequest joinRequest, SendParameters sendParameters)
        {
            if (!this.ValidateGame(peer, joinRequest.OperationRequest, sendParameters))
            {
                return(null);
            }

            // special treatment for game and actor properties sent by AS3/Flash
            var protocol = peer.Protocol.ProtocolType;

            if (protocol == ProtocolType.Amf3V151 || protocol == ProtocolType.Amf3V152 || protocol == ProtocolType.Json)
            {
                Utilities.ConvertAs3WellKnownPropertyKeys(joinRequest.GameProperties, joinRequest.ActorProperties);
            }

            var   gamePeer = (GameClientPeer)peer;
            Actor actor    = this.HandleJoinOperation(peer, joinRequest, sendParameters);

            if (actor == null)
            {
                return(null);
            }

            // update game state at master server
            var peerId = gamePeer.PeerId ?? string.Empty;

            this.UpdateGameStateOnMaster(null, null, null, null, joinRequest.GameProperties, peerId);

            return(actor);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Joins the game.
        /// </summary>
        /// <param name="request">The join request.</param>
        /// <exception cref="System.InvalidOperationException">
        /// You have already joined other game.
        /// </exception>
        public void JoinGame(JoinRequest request)
        {
            // find the requested game
            MazeGame gameToJoin = gameManager.GetGame(request.GameName);

            // if no game found
            if (gameToJoin == null)
            {
                throw new InvalidOperationException(string.
                                                    Format("Could not find the game \"{0}\"", request.GameName));
            }

            // if the requested game has already started
            if (gameToJoin.Started)
            {
                throw new InvalidOperationException(string.
                                                    Format("The game \"{0}\" has already started.", request.GameName));
            }

            // else, the player can join..
            // now check that this player is not in any other game:
            // if the player is already in an unfinished game
            if (gameManager.ContainsGame(request.Client))
            {
                throw new InvalidOperationException("You have already joined other game.");
            }

            // the player is not in any other game.
            // add him to the game.
            gameToJoin.AddPlayer(request.Client);
        }
Ejemplo n.º 10
0
        public override async Task Join(JoinRequest req, IServerStreamWriter <Message> ssw, ServerCallContext scc)
        {
            var v = 0;

            Lock(msgs);
            msgs.Add(new Message()
            {
                M = $"{req.Un}: Joined!\r\n"
            });

            while (true)
            {
                while (v == msgs.Count)
                {
                    if (scc.CancellationToken.IsCancellationRequested)
                    {
                        msgs.Add(new Message()
                        {
                            M = $"{req.Un}: Left!\r\n"
                        });
                        Drop(msgs);
                        return;
                    }
                    Wait(msgs);
                }

                IEnumerable <Message> pend = msgs.Skip(v);
                v = msgs.Count;

                Drop(msgs);
                await ssw.WriteAllAsync(pend);

                Lock(msgs);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Join packet.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="packet"></param>
        protected void OnJoin(Player client, JoinRequest packet)
        {
            Console.WriteLine("[PLAYER JOIN] Name = " + packet.Name);

            foreach (var conn in this.Connections)
            {
                if (conn.Name == null)
                {
                    continue;
                }

                if ((packet.Name.ToLower() == conn.Name.ToLower() && conn.Id != client.Id) || packet.Name.Trim().ToLower() == "system")
                {
                    client.Send(new JoinResponse()
                    {
                        Success = false,
                        Message = "This name is already taken. Please, choose another one."
                    });
                    return;
                }
            }

            this.BroadcastMessage("SYSTEM", "Player '" + packet.Name + "' connected.");

            client.Name = packet.Name;
            client.Send(new JoinResponse()
            {
                Success = true,
                Message = ""
            });
        }
Ejemplo n.º 12
0
        public async Task JoinAsync(JoinRequest request)
        {
            this.room = await this.Group.AddAsync(request.RoomName);

            this.myName = request.UserName;

            this.Broadcast(this.room).OnJoin(request.UserName);

            // dummy external operation db.
            using (var activity = activitySource.StartActivity("db:room/insert", ActivityKind.Internal))
            {
                // this is sample. use orm or any safe way.
                activity.SetTag("table", "rooms");
                activity.SetTag("query", $"INSERT INTO rooms VALUES (0, '{request.RoomName}', '{request.UserName}', '1');");
                activity.SetTag("parameter.room", request.RoomName);
                activity.SetTag("parameter.username", request.UserName);
                await Task.Delay(TimeSpan.FromMilliseconds(2));
            }

            // if you don't want set relation to this method, but directly this streaming hub, set hub trace context to your activiy.
            var hubTraceContext = this.Context.GetTraceContext();

            using (var activity = activitySource.StartActivity("sample:hub_context_relation", ActivityKind.Internal, hubTraceContext))
            {
                // this is sample. use orm or any safe way.
                activity.SetTag("message", "this span has no relationship with this method but has with hub context.");
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        ///   Joins the peer to a <see cref = "LiteLobbyGame" />.
        ///   Called by <see cref = "HandleJoinOperation">HandleJoinOperation</see>.
        ///   Overridden to inject custom discussion rooms
        /// </summary>
        /// <param name = "joinOperation">
        ///   The join operation.
        /// </param>
        /// <param name = "sendParameters">
        ///   The send Parameters.
        /// </param>
        protected override void HandleJoinGameWithLobby(JoinRequest joinOperation, SendParameters sendParameters)
        {
            _dbId = (int)joinOperation.ActorProperties[(byte)ActProps.DbId];
            var devType = (int)joinOperation.ActorProperties[(byte)ActProps.DevType];

            handleOnlineStatus(_photonPer, _dbId, true, devType);

            // remove the peer from current game if the peer
            // allready joined another game
            this.RemovePeerFromCurrentRoom();

            // get a game reference from the game cache
            // the game will be created by the cache if it does not exists allready
            RoomReference gameReference = DiscussionGameCache.Instance.GetRoomReference(joinOperation.GameId,
                                                                                        joinOperation.LobbyId);

            // save the game reference in peers state
            this.RoomReference = gameReference;

            // enqueue the operation request into the games execution queue
            gameReference.Room.EnqueueOperation(this, joinOperation.OperationRequest, sendParameters);

            ////no base.HandleJoinGameWithLobby(), we've duplicated all its code here

            RoomReference lobbyReference = DiscussionLobbyCache.Instance.GetRoomReference(joinOperation.LobbyId);
            var           discLobby      = lobbyReference.Room as DiscussionLobby;

            if (discLobby != null)
            {
                discLobby.SaveRoomName(joinOperation.GameId);
            }
        }
Ejemplo n.º 14
0
        public async Task <bool> JoinAsync(string peerId, string connectionId, JoinRequest joinRequest)
        {
            using (await _peersLock.WriteLockAsync())
            {
                if (_peers.TryGetValue(peerId, out var peer))
                {
                    // 客户端多次调用 `Join`
                    if (peer.ConnectionId == connectionId)
                    {
                        _logger.LogError($"PeerJoinAsync() | Peer:{peerId} was joined.");
                        return(false);
                    }
                }

                peer = new Peer(_loggerFactory,
                                _mediasoupOptions.MediasoupSettings.WebRtcTransportSettings,
                                _mediasoupOptions.MediasoupSettings.PlainTransportSettings,
                                joinRequest.RtpCapabilities,
                                joinRequest.SctpCapabilities,
                                peerId,
                                connectionId,
                                joinRequest.DisplayName,
                                joinRequest.Sources,
                                joinRequest.AppData
                                );

                _peers[peerId] = peer;

                return(true);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        ///   Joins the peer to a <see cref = "LiteLobbyGame" />.
        ///   Called by <see cref = "HandleJoinOperation">HandleJoinOperation</see>.
        /// </summary>
        /// <param name = "joinOperation">
        ///   The join operation.
        /// </param>
        /// <param name = "sendParameters">
        ///   The send Parameters.
        /// </param>
        protected virtual void HandleJoinGameWithLobby(JoinRequest joinOperation, SendParameters sendParameters)
        {
            // remove the peer from current game if the peer
            // allready joined another game
            this.RemovePeerFromCurrentRoom();

            RoomReference gameReference = null;

            if (joinOperation.ActorNr == 0)
            {
                // get a game reference from the game cache
                // the game will be created by the cache if it does not exists allready
                gameReference = LiteLobbyGameCache.Instance.GetRoomReference(joinOperation.GameId, this, joinOperation.LobbyId);
            }
            else
            {
                if (!LiteLobbyGameCache.Instance.TryGetRoomReference(joinOperation.GameId, this, out gameReference))
                {
                    SendOperationResponse(
                        new OperationResponse
                    {
                        OperationCode = joinOperation.OperationRequest.OperationCode,
                        ReturnCode    = -1,
                        DebugMessage  = "the specified game is not exists."
                    },
                        sendParameters);
                    return;
                }
            }
            // save the game reference in peers state
            this.RoomReference = gameReference;

            // enqueue the operation request into the games execution queue
            gameReference.Room.EnqueueOperation(this, joinOperation.OperationRequest, sendParameters);
        }
Ejemplo n.º 16
0
        void PacketHandler.Run(int credential, string payload)
        {
            ClientSession clientSession = EasyGameServer.g_WorldManager.GetClient(credential);
            JoinRequest   joinRequest   = JsonFx.Json.JsonReader.Deserialize <JoinRequest>(payload);


            JoinResult joinResultPay = new JoinResult();

            joinResultPay.m_PlayerID = clientSession.m_PlayerID;
            joinResultPay.m_PosX     = clientSession.m_PosX;
            joinResultPay.m_PosY     = clientSession.m_PosY;
            joinResultPay.m_PosZ     = clientSession.m_PosZ;
            joinResultPay.m_Angle    = clientSession.m_Angle;
            joinResultPay.m_Speed    = clientSession.m_Speed;

            string resultPayload = JsonFx.Json.JsonWriter.Serialize(joinResultPay);

            resultPayload = Utils.Base64Encoding(resultPayload);

            Packet joinResult = new Packet();

            joinResult.m_Type    = (int)PacketTypes.PKT_SC_JOIN;
            joinResult.m_Payload = resultPayload;
            string resultPacket = JsonFx.Json.JsonWriter.Serialize(joinResult);


            EasyGameServer.g_WorldManager.SendBroadCast(resultPacket);
        }
Ejemplo n.º 17
0
    private void ProcessJoinRequest(GameServer gameServer, JoinRequest msg, INetworkAddress address)
    {
        Debug.LogFormat("Join request from player {0}. Address {1}", msg.m_playerName, address.ToString());

        if (gameServer.GetClientCount() == 2)
        {
            Debug.Log("Server is full.");
            return;
        }

        if (gameServer.IsClientConnected(address))
        {
            Debug.Log("Client is already connected.");
            return;
        }

        gameServer.AddClient(new ClientInfo(msg.m_playerName, (byte)gameServer.GetClientCount(), address));
        gameServer.AcceptClient(address);

        //
        if (gameServer.GetClientCount() == 2)
        {
            gameServer.SendOpponentFound();
            gameServer.NotifyPlayersConnected();
        }
    }
        public JoinRequest Create(JoinRequest newJoinRequest)
        {
            newJoinRequest.Id = JoinRequests.OrderByDescending(jr => jr.Id).Single().Id + 1;
            JoinRequests.Add(newJoinRequest);

            return(newJoinRequest);
        }
Ejemplo n.º 19
0
        public JsonResult RemoveServer(JoinRequest joinRequest)
        {
            string connStr     = ConfigurationManager.ConnectionStrings["MySQLConn"].ConnectionString;
            string returnValue = "Remove";

            HttpCookie userCookie = Request.Cookies["token"];

            MySqlConnection conn = new MySqlConnection(connStr);

            try
            {
                conn.Open();
                string          sql = "SELECT s.* FROM Token as t, User as u, ServerMember as sa, Server as s where t.token like '" + userCookie.Value + "' and t.idUser = u.id and sa.idUser = u.id and sa.idServer = s.id and sa.userRole=1 and s.id=" + joinRequest.ServerId + ";";
                MySqlCommand    cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    Server s = new Server();

                    while (rdr.Read())
                    {
                        s.Id = (int)rdr[0];
                    }

                    rdr.Close();

                    conn.Close();
                    conn.Open();
                    sql = "DELETE FROM ServerMember WHERE idServer=" + joinRequest.ServerId;
                    cmd = new MySqlCommand(sql, conn);
                    cmd.ExecuteNonQuery();

                    conn.Close();
                    conn.Open();
                    sql = "DELETE FROM Server WHERE id=" + joinRequest.ServerId;
                    cmd = new MySqlCommand(sql, conn);
                    cmd.ExecuteNonQuery();

                    returnValue = "Server left the building!";
                }
                else
                {
                    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    returnValue         = "Unknown error!";
                }

                rdr.Close();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                returnValue         = "Unexcepted error!";
            }
            conn.Close();

            return(Json(returnValue));
        }
Ejemplo n.º 20
0
 public void Serialize(JoinRequest message)
 {
     m_writer.Reset();
     m_writer.Write(NetworkMessageType.JoinRequest);
     m_writer.Write(message.m_clientVersion);
     m_writer.Write(message.m_playerName);
     m_writer.Flush();
 }
Ejemplo n.º 21
0
        public async Task JoinAsync(JoinRequest request)
        {
            this.room = await this.Group.AddAsync(request.RoomName);

            this.myName = request.UserName;

            this.Broadcast(this.room).OnJoin(request.UserName);
        }
Ejemplo n.º 22
0
 public void OnGameCreated(JObject jsonObject)
 {
     Debug.Log("Game created: " + jsonObject);
     GameCreatedMessage message = jsonObject.ToObject<GameCreatedMessage>();
     long id = message.gameId;
     JoinRequest request = new JoinRequest(OnGameJoined, id);
     GameClient.Instance.SendRequest(request);
 }
        public void TestDeserialize()
        {
            Assert.AreEqual(1, JoinRequest.Manipulator.InsertDataInto(TestConnection, TableName, Id1));
            JoinRequest toTest = JoinRequest.Manipulator.RetrieveDataWhere(TestConnection, TableName, "UserId=" + Id1.UserId)[0];

            Assert.AreEqual(Id1, toTest);
            Assert.AreEqual(1, JoinRequest.Manipulator.RemoveDataWhere(TestConnection, TableName, "UserId=" + Id1.UserId));
        }
Ejemplo n.º 24
0
        public void JoinGame(string name)
        {
            var cmd = new JoinRequest {
                GameName = name
            };
            var proto = BinaryProcolHelper <JoinRequest> .GetProtocol(cmd);

            _tcp.SendData(proto);
        }
Ejemplo n.º 25
0
    public void OnGameCreated(JObject jsonObject)
    {
        Debug.Log("Game created: " + jsonObject);
        GameCreatedMessage message = jsonObject.ToObject <GameCreatedMessage>();
        long        id             = message.gameId;
        JoinRequest request        = new JoinRequest(OnGameJoined, id);

        GameClient.Instance.SendRequest(request);
    }
Ejemplo n.º 26
0
    // Start is called before the first frame update
    void Start()
    {
        if (joinButton != null)
        {
            joinButton.onClick.AddListener(OnJoinButton);
        }

        joinRequest = GetComponent <JoinRequest>();
    }
Ejemplo n.º 27
0
        private async Task JoinServer(HttpClient httpClient, string serverName, string clientBaseAddress, string playerName)
        {
            var joinRequest = new JoinRequest {
                CallbackBaseAddress = clientBaseAddress, Name = playerName
            };
            var response = await httpClient.PostAsJsonAsync($"{serverName}/join", joinRequest);

            //await response.Content.ReadFromJsonAsync<JoinResponse>();
        }
Ejemplo n.º 28
0
        private async void JoinServer(HttpClient httpClient, string serverName, string clientBaseAddress, string playerName)
        {
            await Task.Delay(TimeSpan.FromSeconds(5));

            var joinRequest = new JoinRequest {
                CallbackBaseAddress = clientBaseAddress, Name = playerName
            };
            var response = await httpClient.PostAsJsonAsync($"{serverName}/join", joinRequest);
        }
Ejemplo n.º 29
0
        public async Task AcceptAsync_WithCorrectId_WorksCorrectly()
        {
            // Arrange
            var context = new PoolItDbContext(new DbContextOptionsBuilder <PoolItDbContext>()
                                              .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                              .Options);

            var ride = new Ride
            {
                Title = "Test Ride",
                Car   = new Car
                {
                    Owner = new PoolItUser
                    {
                        UserName = "******"
                    },
                    Model = new CarModel
                    {
                        Manufacturer = new CarManufacturer()
                    }
                },
                Conversation = new Conversation()
            };

            var user = new PoolItUser
            {
                UserName = "******"
            };

            var request = new JoinRequest
            {
                Ride    = ride,
                User    = user,
                Message = "Test Message"
            };

            await context.JoinRequests.AddAsync(request);

            await context.SaveChangesAsync();

            var joinRequestsService = new JoinRequestsService(new EfRepository <JoinRequest>(context), null, null, new EfRepository <UserRide>(context));

            // Act
            var result = await joinRequestsService.AcceptAsync(request.Id);

            // Assert
            Assert.True(result);

            var joinRequestExists = await context.JoinRequests.AnyAsync();

            Assert.False(joinRequestExists);

            var userRideExists = await context.UserRides.AnyAsync(u => u.UserId == user.Id && u.RideId == ride.Id);

            Assert.True(userRideExists);
        }
        public async Task <IActionResult> JoinClass([FromBody] JoinRequest request)
        {
            string response = await _enrollmentService.Join(request);

            if (string.IsNullOrEmpty(response))
            {
                return(Ok());
            }
            return(BadRequest(response));
        }
Ejemplo n.º 31
0
 private void Connect(string serverUrl)
 {
     var joinRequest = new JoinRequest
     {
         Sources     = new[] { "audio:mic", "video:cam" },
         DisplayName = null,
         AppData     = null,
     };
     var result = MediasoupClient.Connect(serverUrl, joinRequest.ToJson());
 }
Ejemplo n.º 32
0
		public async Task Join(int channelId)
		{
			_channelId = channelId;
			JoinRequest request = new JoinRequest(channelId);
			var response = await _client.Get<JoinRequest, JoinResponse>(request);

			_authorizationKey = response.AuthorizationKey;
			_permissions = response.Permissions;
			_endpoints = new Queue<Uri>(response.Endpoints.OrderBy(_ => Guid.NewGuid()));

			await Connect();
		}