internal static async Task <WebSocketApiResult> ReceiveApiMessage(this WebSocket socket, byte[] buffer, CancellationToken?cancellationToken = null) { if (cancellationToken == null) { cancellationToken = CancellationToken.None; } WebSocketStringResult res = await socket.ReceiveString(buffer, cancellationToken); var result = new WebSocketApiResult { SocketResult = res.SocketResult }; if (res.SocketResult.MessageType != WebSocketMessageType.Text) { result.JsonException = new JsonException("Can't read binary messages as JSON."); } else if (string.IsNullOrEmpty(res.Message)) { result.JsonException = new JsonException("The message was empty."); } else { try { result.Obj = JsonApiObject.Deserialize(res.Message); } catch (JsonException ex) { result.JsonException = ex; } } return(result); }
// POST api/games public JsonApiObject <Game> Post([FromBody] string json) { NullCheck(json); var game = JsonConvert.DeserializeObject <Game>(json); var toReturn = new JsonApiObject <Game>(); if (game.IsValid()) { if (game.Id == Guid.Empty) { game.Id = Guid.NewGuid(); } toReturn.Data = new List <Game> { game }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, Name, OwnerId) VALUES (@Id, @Name, @OwnerId)", game); } else { toReturn.Errors = new string[] { "Validation failed." }; } return(toReturn); }
private async Task HandlePeripheralMessage(JsonApiObject message, CancellationToken token) { PeripheralRequestCode msgCode; try { msgCode = Enum.Parse <PeripheralRequestCode>(message.message_code); } catch (Exception) { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"{message.message_code} is not a valid message code (or I forgot it)."), token); return; } switch (msgCode) { case PeripheralRequestCode.get_pairing_code: string pairingCode; ActivePairingCode dbCode = _db.ActivePairingCodes.SingleOrDefault(c => c.PeripheralId == Device.Id); if (dbCode != null) { pairingCode = dbCode.Code; } else { pairingCode = Cryptography.CreatePairingCode(); var codeEntry = new ActivePairingCode { Code = pairingCode, PeripheralId = Device.Id }; _db.ActivePairingCodes.Add(codeEntry); _db.SaveChanges(); } await _socket.SendJson(PeripheralJsonApiObjectFactory.CreateGetPairingCodeResponse(pairingCode), token); break; default: await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"Function {msgCode.ToString()} not implemented yet."), token); _logger.LogWarning($"PeripheralRequestCode.{msgCode.ToString()} not implemented."); break; } }
private async Task <bool> HandleSharedMessage(JsonApiObject message, CancellationToken token) { SharedJsonRequestCode msgCode; try { msgCode = Enum.Parse <SharedJsonRequestCode>(message.message_code); } catch (Exception) { return(false); } switch (msgCode) { case SharedJsonRequestCode.login: case SharedJsonRequestCode.register: await _socket.SendJson( SharedJsonApiObjectFactory.CreateError("You can't login while you're logged in ..."), token); break; case SharedJsonRequestCode.set_own_name: if (message.data.TryGetValue("name", out string newName)) { if (string.IsNullOrWhiteSpace(newName)) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateChangeOwnNameResponse(false, _device.Name)); } else { _db.Hosts.Find(_device.Id).Name = newName; _db.SaveChanges(); await _socket.SendJson(SharedJsonApiObjectFactory.CreateChangeOwnNameResponse(true, newName)); } } else { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError("name not defined")); } break; default: throw new ArgumentOutOfRangeException(); } return(true); }
// POST api/<controller> public JsonApiObject<GameSession> Post([FromBody]string json) { var session = JsonConvert.DeserializeObject<GameSession>(json); var toReturn = new JsonApiObject<GameSession>(); if (session.IsValid()) { toReturn.Data = new List<GameSession> { session }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, GameId, Platform, PlayerId, StartTimeUtc) VALUES (@Id, @GameId, @Platform, @PlayerId, @StartTimeUtc)", session); } else { toReturn.Errors = new string[] { "Validation failed." }; } return toReturn; }
// POST api/<controller> public JsonApiObject <GameSession> Post([FromBody] string json) { var session = JsonConvert.DeserializeObject <GameSession>(json); var toReturn = new JsonApiObject <GameSession>(); if (session.IsValid()) { toReturn.Data = new List <GameSession> { session }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, GameId, Platform, PlayerId, StartTimeUtc) VALUES (@Id, @GameId, @Platform, @PlayerId, @StartTimeUtc)", session); } else { toReturn.Errors = new string[] { "Validation failed." }; } return(toReturn); }
// POST api/games public JsonApiObject<Game> Post([FromBody]string json) { NullCheck(json); var game = JsonConvert.DeserializeObject<Game>(json); var toReturn = new JsonApiObject<Game>(); if (game.IsValid()) { if (game.Id == Guid.Empty) { game.Id = Guid.NewGuid(); } toReturn.Data = new List<Game> { game }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, Name, OwnerId) VALUES (@Id, @Name, @OwnerId)", game); } else { toReturn.Errors = new string[] { "Validation failed." }; } return toReturn; }
internal static async Task SendJson(this WebSocket socket, JsonApiObject obj, CancellationToken?cancellationToken = null, Encoding encoding = null) { await SendString(socket, obj.Serialize(), cancellationToken, encoding); }
private async Task HandleHostMessage(JsonApiObject message, CancellationToken token) { HostRequestCode msgCode; try { msgCode = Enum.Parse <HostRequestCode>(message.message_code); } catch (Exception) { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"{message.message_code} is not a valid message code (or I forgot it)."), token); return; } switch (msgCode) { case HostRequestCode.pair: if (!message.data.TryGetValue("code", out string code)) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError("Parameter code not set or null."), token); return; } try { ActivePairingCode pairingCode = _db.ActivePairingCodes.SingleOrDefault(p => p.Code.Equals(code)); if (pairingCode == null) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError("Pairing code was not valid."), token); return; } Peripheral deviceToPair = _db.Peripherals.Find(pairingCode.PeripheralId); if (deviceToPair != null) { if (deviceToPair.PairedDevices.All(hp => hp.PeripheralId != deviceToPair.Id)) { deviceToPair.PairedDevices.Add(new HostPeripheral { HostId = Device.Id, PeripheralId = deviceToPair.Id }); _db.ActivePairingCodes.Remove(pairingCode); } } else { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError( "The device you want to pair isn't known to me :(")); return; } _db.Remove(pairingCode); _db.SaveChanges(); AuthenticatedWebSocketConnection conn = _anperiManager.GetConnectionForId(deviceToPair.Id); if (conn != null) { OnPairedDeviceLogin(null, new AuthenticatedWebSocketEventArgs(conn)); } await _socket.SendJson(HostJsonApiObjectFactory.CreatePairingResponse(true, deviceToPair.Id)); } catch (Exception e) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError($"Internal error handling this request: {e.GetType()} - {e.Message}"), token); } break; case HostRequestCode.unpair: if (message.data.TryGetValue("id", out int peripheralId)) { HostPeripheral connection = _db.HostPeripherals.SingleOrDefault(hp => hp.HostId == _device.Id && hp.PeripheralId == peripheralId); if (connection != null) { try { _db.HostPeripherals.Remove(connection); (_device as Host)?.PairedDevices.Remove(connection); _db.SaveChanges(); AuthenticatedWebSocketConnection loggedInPeripheral; lock (_syncRootLoggedInPairedDevices) { loggedInPeripheral = _loggedInPairedDevices.SingleOrDefault(c => c.Device.Id == peripheralId); } if (loggedInPeripheral != null) { OnPairedDeviceLogoff(null, new AuthenticatedWebSocketEventArgs(loggedInPeripheral)); } await _socket.SendJson( HostJsonApiObjectFactory.CreateUnpairFromPeripheralResponse(true)); } catch (Exception ex) { _logger.LogError(ex, "Error unpairing devices."); await _socket.SendJson( HostJsonApiObjectFactory.CreateUnpairFromPeripheralResponse(false)); } } } else { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError("id not defined")); } break; case HostRequestCode.get_available_peripherals: IEnumerable <Peripheral> peripherals = _db.HostPeripherals.Where(hp => hp.HostId == _device.Id).Select(p => p.Peripheral); IEnumerable <HostJsonApiObjectFactory.ApiPeripheral> apiPeris = peripherals.Select( p => new HostJsonApiObjectFactory.ApiPeripheral { id = p.Id, name = p.Name }).ToList(); lock (_syncRootLoggedInPairedDevices) { _loggedInPairedDevices.ForEach(d => { apiPeris.Single(p => p.id == d.Device.Id).online = true; }); } await _socket.SendJson( HostJsonApiObjectFactory.CreateAvailablePeripheralResponse(apiPeris), token); break; case HostRequestCode.connect_to_peripheral: if (message.data.TryGetValue("id", out int id)) { if (!_db.HostPeripherals.Any(hp => hp.HostId == _device.Id && hp.PeripheralId == id)) { await _socket.SendJson( HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); return; } AuthenticatedWebSocketConnection conn = _anperiManager.GetConnectionForId(id); if (conn != null) { if (await conn.PartnerConnect(this)) { lock (_syncRootPartner) { _partner = conn; } await _socket.SendJson( HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(true, id)); } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } break; case HostRequestCode.disconnect_from_peripheral: lock (_syncRootPartner) { _partner?.PartnerCloseConnection(); _partner = null; } await _socket.SendJson(HostJsonApiObjectFactory.CreateDisconnectFromPeripheralResponse(true), token); break; case HostRequestCode.change_peripheral_name: if (message.data.TryGetValue("name", out string newName) && message.data.TryGetValue("id", out int periId)) { HostPeripheral hp = _db.HostPeripherals.SingleOrDefault(e => e.HostId == _device.Id && e.PeripheralId == periId); if (hp == null) { await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(false, null, periId)); return; } if (string.IsNullOrWhiteSpace(newName)) { await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(false, hp.Peripheral.Name, periId)); return; } Peripheral p = hp.Peripheral; p.Name = newName; _db.SaveChanges(); await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(true, newName, periId)); } else { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError("name or id not defined")); } break; default: await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"Function {msgCode.ToString()} not implemented yet."), token); _logger.LogWarning($"HostRequestCode.{msgCode.ToString()} not implemented."); break; } }
private async void PartnerSendMessage(JsonApiObject msg) { await _socket.SendJson(msg); }