private async Task <bool> Connect(string host, int port, string userName, string password = null) { _logger.LogInformation("Connecting to {0}:{1} as {2}", host, port, userName); try { _gameClient = new OpenRCT2Client(); _gameClient.ChatMessageReceived += async(object sender, IOpenRCT2String e) => { await Send(e.ToHtml()); }; await _gameClient.Connect(host, port); AuthenticationResult result = await _gameClient.Authenticate(userName, password); if (result != AuthenticationResult.OK) { await SendError("Access denied: " + result); return(false); } return(true); } catch (SocketException ex) { await SendError("Unable to connect to server: " + ex.Message); } catch (Exception ex) { _logger.LogError(ex.Message, ex); await SendError("An error occured whilst connecting to the server."); } return(false); }
public async Task <IJResponse> AdvertiseServerAsync( [FromServices] IServerRepository serverRepository, [FromServices] Random random, [FromBody] JAdvertiseServerRequest body) { var remoteAddress = GetRemoteAddress(); if (String.IsNullOrEmpty(remoteAddress)) { return(JResponse.Error(JErrorMessages.ServerError)); } Server serverInfo; try { string serverInfoJson; using (var client = new OpenRCT2Client()) { _logger.LogInformation("Connecting to {0}:{1}", remoteAddress, body.Port); await client.Connect(remoteAddress, body.Port); _logger.LogInformation("Requesting server info from {0}:{1}", remoteAddress, body.Port); serverInfoJson = await client.RequestServerInfo(); } serverInfo = JsonConvert.DeserializeObject <Server>(serverInfoJson); } catch (SocketException) { return(ConvertResponse(JResponse.Error("Unable to connect to server, make sure your ports are open."))); } catch (TimeoutException) { return(ConvertResponse(JResponse.Error("Timed out while waiting for server response."))); } catch { return(ConvertResponse(JResponse.Error("Unable to advertise server."))); } var token = random.NextBytes(8) .ToHexString(); var server = new Server() { Token = token, LastHeartbeat = DateTime.Now, Addresses = new ServerAddressList() { IPv4 = new string[] { remoteAddress }, IPv6 = new string[0] }, Port = body.Port, Name = serverInfo.Name, Description = serverInfo.Description, Provider = serverInfo.Provider, RequiresPassword = serverInfo.RequiresPassword, Players = serverInfo.Players, MaxPlayers = serverInfo.MaxPlayers, Version = serverInfo.Version }; _logger.LogInformation("Registering server {0} [{1}:{2}]", serverInfo.Name, remoteAddress, body.Port); await serverRepository.AddOrUpdateAsync(server); var response = new JAdvertiseServerResponse() { status = JStatus.OK, Token = token }; return(ConvertResponse(response)); }