Skip to content

Commit

Permalink
restructure serverfn
Browse files Browse the repository at this point in the history
  • Loading branch information
Arunscape committed Aug 17, 2023
1 parent 5fcd6b5 commit 3d49f65
Show file tree
Hide file tree
Showing 16 changed files with 243 additions and 191 deletions.
142 changes: 73 additions & 69 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions atb-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ serde = {version = "*", features = ["derive"]}
serde_json = "1.0"
gloo = "0.10"
wasm-bindgen = "0.2"
minecraft-msa-auth = "0.3"
oauth2 = "4.4"
once_cell = "1.18.0"
atb_types = { path = "../atb_backend/atb_types" }


[features]
Expand Down
16 changes: 3 additions & 13 deletions atb-web/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
use crate::components::status::McStatusComponent;
use crate::error_template::{AppError, ErrorTemplate};
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use crate::components::status::McStatusComponent;

#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();

view! {
// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
view! {
<Stylesheet id="leptos" href="/pkg/atb-web.css"/>

// sets the document title
Expand Down Expand Up @@ -55,12 +53,7 @@ fn HomePage() -> impl IntoView {

#[component]
fn Navbar() -> impl IntoView {

let paths = move || { vec![
("Home", "/"),
("Server Status", "/status"),
("idk", "/idk"),
]};
let paths = move || vec![("Home", "/"), ("Server Status", "/status"), ("idk", "/idk")];
view! {
<nav>
<div class="flex flex-row space-x-4">
Expand All @@ -81,7 +74,6 @@ fn Navbar() -> impl IntoView {
}
}


#[component]
fn Idk() -> impl IntoView {
view! { <h1>"Idk"</h1> }
Expand All @@ -94,5 +86,3 @@ fn Status() -> impl IntoView {
<McStatusComponent/>
}
}


1 change: 0 additions & 1 deletion atb-web/src/components/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod status;

96 changes: 27 additions & 69 deletions atb-web/src/components/status.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,10 @@
use crate::serverfns::server_status::ping_minecraft_server;
use atb_types::McServerStatus;
use leptos::*;
use serde_json::Value;

#[cfg(feature="ssr")]
use tokio::net::TcpStream;
#[cfg(feature="ssr")]
use craftping::tokio::ping;
use serde::{Serialize, Deserialize};

#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct McStatus {
pub version: String,
pub max_players: usize,
pub online_players: usize,
pub sample: Vec<(String, String)>,
pub favicon: Vec<u8>,
}

#[server(McPing, "/api")]
pub async fn ping_minecraft_server() -> Result<McStatus, ServerFnError> {
// todo : extract out to a variable for configurability
let hostname = "mc.arun.gg";
let port = 25565;
let mut stream = TcpStream::connect((hostname, port)).await?;

let pong: craftping::Response = ping(&mut stream, hostname, port).await?;

let sample = match pong.sample {
None => vec![],
Some(s) => s.into_iter().map(|craftping::Player { name, id }| (name, id)).collect::<Vec<_>>()
};

let favicon = pong.favicon.unwrap_or(vec![]);

let res = McStatus {
version: pong.version,
max_players: pong.max_players,
online_players: pong.online_players,
sample,
favicon,
};

Ok(res)
}

#[component]
fn Status(status: McStatus) -> impl IntoView {
fn Status(status: Result<McServerStatus, ServerFnError>) -> impl IntoView {
let status = status.unwrap();
let version = format!("Version: {}", status.version);
let players = move || status.sample.clone();

Expand All @@ -54,43 +14,43 @@ fn Status(status: McStatus) -> impl IntoView {
use gloo::file::{Blob, ObjectUrl};

if let Some(img) = imgref.get() {

let favicon = status.favicon.as_slice();
let blob = Blob::new_with_options(favicon, Some("image/png"));
let url = ObjectUrl::from(blob);

img.set_src(&url);

}

});

// todo: use Error Boundary to handle error
// https://leptos-rs.github.io/leptos/view/07_errors.html?highlight=error#error-handling
view! {
<p>{version}</p>
// <img src=url/>
<img node_ref=imgref/>
<p>{format!("Players: {}/{}", status.online_players, status.max_players)}</p>
<For
each=players
key=|(_name, id)| id.clone()
view=move |(name, _id)| {
view! { <p>{name}</p> }
}
/>
<>
<p>{version}</p>
<img node_ref=imgref/>
<p>{format!("Players: {}/{}", status.online_players, status.max_players)}</p>
<For
each=players
key=|(_name, id)| id.clone()
view=move |(name, _id)| {
view! { <p>{name}</p> }
}
/>
</>
}
}
#[component]
pub fn McStatusComponent() -> impl IntoView {
let once = create_resource(
// todo: add refresh button
move || (),
move |_| async move {
let r = ping_minecraft_server().await;
r
},
);


let once = create_resource(move || () , move |_| async move {
let r = ping_minecraft_server().await;
let r = r.unwrap_or(McStatus::default());
r
});


let x = move || { once.read().map(|v| view! { <Status status=v/> }) };
let x = move || once.read().map(|v| view! { <Status status=v/> });

view! {
<h1>"Server Status"</h1>
Expand All @@ -102,6 +62,4 @@ pub fn McStatusComponent() -> impl IntoView {
</div>
</Suspense>
}

}

3 changes: 2 additions & 1 deletion atb-web/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use cfg_if::cfg_if;
pub mod app;
pub mod components;
pub mod error_template;
pub mod fileserv;
pub mod components;
pub mod serverfns;

cfg_if! { if #[cfg(feature = "hydrate")] {
use leptos::*;
Expand Down
10 changes: 7 additions & 3 deletions atb-web/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{routing::post, Router};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use atb_web::app::*;
use atb_web::fileserv::file_and_error_handler;
use axum::{
routing::{get, post},
Router,
};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};

simple_logger::init_with_level(log::Level::Debug).expect("couldn't initialize logging");

Expand All @@ -22,6 +25,7 @@ async fn main() {
// build our application with a route
let app = Router::new()
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
.route("/api/*fn_name", get(leptos_axum::handle_server_fns))
.leptos_routes(&leptos_options, routes, || view! { <App/> })
.fallback(file_and_error_handler)
.with_state(leptos_options);
Expand Down
24 changes: 24 additions & 0 deletions atb-web/src/pages/login.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use leptos::*;
use minecraft_msa_auth::MinecraftAuthorizationFlow;
use minecraft_msa_auth::MinecraftAccessToken;
use oauth2::basic::BasicClient;
use oauth2::reqwest::async_http_client;
use oauth2::{
AuthType, AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse,
TokenUrl, ClientSecret
};



#[component]
pub fn Login() -> View {
view! {
<div>
<h1>
Login
</h1>
</div>
}
}


1 change: 1 addition & 0 deletions atb-web/src/pages/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod login;
1 change: 1 addition & 0 deletions atb-web/src/serverfns/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod server_status;
38 changes: 38 additions & 0 deletions atb-web/src/serverfns/server_status.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use leptos::*;

#[cfg(feature = "ssr")]
use craftping::tokio::ping;
#[cfg(feature = "ssr")]
use tokio::net::TcpStream;

use atb_types::McServerStatus;

#[server(McServerStatusInternalLeptosName, "/api", "GetJson", "ping_mc_server")]
pub async fn ping_minecraft_server() -> Result<McServerStatus, ServerFnError> {
// todo : extract out to a variable for configurability
let hostname = "mc.arun.gg";
let port = 25565;
let mut stream = TcpStream::connect((hostname, port)).await?;

let pong: craftping::Response = ping(&mut stream, hostname, port).await?;

let sample = match pong.sample {
None => vec![],
Some(s) => s
.into_iter()
.map(|craftping::Player { name, id }| (name, id))
.collect::<Vec<_>>(),
};

let favicon = pong.favicon.unwrap_or(vec![]);

let res = McServerStatus {
version: pong.version,
max_players: pong.max_players,
online_players: pong.online_players,
sample,
favicon,
};

Ok(res)
}
6 changes: 1 addition & 5 deletions atb_backend/atb_backend/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use sqlx::Connection;

// load_dotenv!();


lazy_static! {
static ref DB_URL: String =
env::var("DATABASE_URL").unwrap_or("postgres://postgres@localhost/postgres".into());
Expand Down Expand Up @@ -81,10 +80,7 @@ pub async fn delete_account(
Ok(account)
}

pub async fn get_accounts_for_user(
pool: &PgPool,
id: Uuid,
) -> Result<Vec<Account>, sqlx::Error> {
pub async fn get_accounts_for_user(pool: &PgPool, id: Uuid) -> Result<Vec<Account>, sqlx::Error> {
let accounts = query_file_as!(Account, "./src/db/queries/get_accounts_for_user.sql", id)
.fetch_all(pool)
.await?;
Expand Down
Loading

0 comments on commit 3d49f65

Please sign in to comment.