/*
* This file is part of laurelin/server
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
use bevy_ecs::{event::EventReader, system::Res};
use bevy_log::info;
use laurelin_shared::{
api::user::{login, register, ResponseLogin, ResponseRegister},
server::{
channels::AfterAuthChannel,
messages::{AfterAuth, Auth},
},
};
use naia_bevy_server::{
events::{AuthEvents, ConnectEvent, DisconnectEvent, ErrorEvent, TickEvent},
Server,
};
use crate::Config;
pub(crate) fn auth_events(
mut ev: EventReader<AuthEvents>,
mut server: Server,
config: Res<Config>,
) {
for events in ev.iter() {
for (user_key, auth) in events.read::<Auth>() {
match auth.username {
Some(username) => {
// register
let wrapped =
register(&config.api_address, &username, &auth.email, &auth.password);
match wrapped.response {
ResponseRegister::Error(_) => server.reject_connection(&user_key),
ResponseRegister::Ok(user) => {
server.accept_connection(&user_key);
server.send_message::<AfterAuthChannel, AfterAuth>(
&user_key,
&AfterAuth {
username: user.username,
cookie: wrapped.cookie,
},
)
}
}
}
None => {
// login
let wrapped = login(&config.api_address, &auth.email, &auth.password);
match wrapped.response {
ResponseLogin::Error(_) => server.reject_connection(&user_key),
ResponseLogin::Ok(user) => {
server.accept_connection(&user_key);
server.send_message::<AfterAuthChannel, AfterAuth>(
&user_key,
&AfterAuth {
username: user.username,
cookie: wrapped.cookie,
},
)
}
}
}
}
}
}
}
pub(crate) fn connect_events(mut ev: EventReader<ConnectEvent>, mut server: Server) {
for ConnectEvent(user_key) in ev.iter() {
let address = server.user(user_key).address();
info!("Naia Server connected to: {:?}", address);
}
}
pub(crate) fn disconnect_events(mut ev: EventReader<DisconnectEvent>) {
for DisconnectEvent(_user_key, user) in ev.iter() {
info!("Naia Server disconnected from: {:?}", user.address);
}
}
pub(crate) fn error_events(mut ev: EventReader<ErrorEvent>) {
for ErrorEvent(error) in ev.iter() {
info!("Naia Server Error: {:?}", error);
}
}
pub(crate) fn tick_events(mut ev: EventReader<TickEvent>, mut server: Server) {
let mut has_ticked = false;
for TickEvent(_server_tick) in ev.iter() {
has_ticked = true;
// Handle messages coming from clients
//let messages = server.receive_tick_buffer_messages(server_tick);
}
if has_ticked {
// Update scopes of entities
// Not sure if this will come into play,
// but see naia/demos/bevy/server/src/systems/events.rs::tick_events
//for (_, user_key, entity) in server.scope_checks() {
// ...
//}
server.send_all_updates();
}
}