/// <summary>
        /// Handles an incoming game server selection
        /// </summary>
        /// <param name="session">The session instance</param>
        /// <param name="length">The length of the packet</param>
        /// <param name="opcode">The opcode of the incoming packet</param>
        /// <param name="data">The packet data</param>
        /// <returns></returns>
        public override bool Handle(ServerSession session, int length, int opcode, byte[] data)
        {
            // If the length is not 5
            if (length != 5)
            {
                return(true);
            }

            var bldr = new PacketBuilder(opcode);

            int serverId = (data[0] & 0xFF);

            // TODO: not sure why, but here is always -1. If someone can ever answer me I would be very grateful.
            int clientVersion = ((data[1] & 0xFF) + ((data[2] & 0xFF) << 8) + ((data[3] & 0xFF) << 16) + ((data[4] & 0xFF) << 24));

            using (var dbContext = new ServersDbContext())
            {
                // TODO: somehow check client version...
                var foundServer = dbContext.Servers.SingleOrDefault(s => s.Id == serverId);
                if (foundServer is null) // Server not found.
                {
                    bldr.WriteByte(unchecked ((byte)SelectServer.CannotConnect));
                    session.Write(bldr.ToPacket());
                    return(true);
                }

                // TODO: remove || true, when you get how to check client version.
                if (clientVersion == foundServer.ClientVersion || true)
                {
                    bldr.WriteByte((byte)SelectServer.Success);

                    IPAddress ipAddress = IPAddress.Parse(foundServer.IpAddress.Trim());
                    foreach (var i in ipAddress.GetAddressBytes())
                    {
                        bldr.WriteByte(i);
                    }
                }
                session.Write(bldr.ToPacket());
            }
            return(true);
        }
Example #2
0
        public CommandLineApplication(params string[] args)
        {
            _console = new StringOutputConsole();
            FakeHttpClientHandler = A.Fake <ServersListApiClientHandler>(o => o.CallsBaseMethods());

            _host = new HostBuilder()
                    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureContainer <ContainerBuilder>(HostConfiguration.Container)
                    .ConfigureServices(HostConfiguration.Services)
                    .ConfigureLogging(HostConfiguration.Logging)
                    .ConfigureCommandLineApplication <RootCommandHandler>(args, out var state)
                    .ConfigureContainer <ContainerBuilder>(containerBuilder =>
            {
                containerBuilder.RegisterInstance(_console);
                containerBuilder.RegisterInstance <HttpClientHandler>(FakeHttpClientHandler);
                containerBuilder.RegisterInstance(new ServersListRenderer(false));
            })
                    .Build();

            _state           = state;
            _databaseContext = _host.Services.GetRequiredService <ServersDbContext>();
        }
Example #3
0
        public async Task SavesServerListToPersistentStorage()
        {
            await new PersistentJsonConfiguration().Save(new
            {
                ServerListApi = new
                {
                    Username    = "******",
                    Password    = "******",
                    BaseAddress = "https://host/"
                }
            });

            var expectedServers = new[]
            {
                new Server(Guid.NewGuid(), "Lithuania #1", 20),
                new Server(Guid.NewGuid(), "Latvia #1", 500),
                new Server(Guid.NewGuid(), "Germany #1", 1234),
                new Server(Guid.NewGuid(), "United Kingdom #1", 2500)
            };

            await using var application = new CommandLineApplication("server_list");
            var handler = application.FakeHttpClientHandler;

            var callToAuthorize = A.CallTo(() => handler.SendAsyncOverride(
                                               A <HttpRequestMessage> .That.Matches(message =>
                                                                                    message.Method == HttpMethod.Post &&
                                                                                    message.RequestUri !.ToString().EndsWith("tokens")),
                                               A <CancellationToken> ._));

            var callToGetServerList = A.CallTo(() => handler.SendAsyncOverride(
                                                   A <HttpRequestMessage> .That.Matches(message =>
                                                                                        message.Method == HttpMethod.Get &&
                                                                                        message.RequestUri !.ToString().EndsWith("servers") &&
                                                                                        message.Headers.Authorization !.Scheme == "Bearer" &&
                                                                                        message.Headers.Authorization !.Parameter == "1234567890"),
                                                   A <CancellationToken> ._));

            callToAuthorize.Returns(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{""token"":""1234567890""}")
            });

            callToGetServerList.Returns(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonSerializer.Serialize(expectedServers))
            });

            var returnCode = await application.RunAsync();

            await using var dbContext = new ServersDbContext();
            foreach (var(id, name, distance) in expectedServers)
            {
                var server = await dbContext.FindAsync <Server>(id);

                Assert.Equal(name, server.Name);
                Assert.Equal(distance, server.Distance);
            }

            callToAuthorize.MustHaveHappenedOnceExactly();
            callToGetServerList.MustHaveHappenedOnceExactly();

            Assert.Equal(0, returnCode);
        }
Example #4
0
 public ChatController(ServersDbContext dbContext)
 {
     context = dbContext;
 }
Example #5
0
 public RepositoryTests()
 {
     _dbContext  = new ServersDbContext("Data Source=InMemory;Mode=Memory;Cache=Shared");
     _repository = new ServersRepository(_dbContext);
 }