Skip to content

Commit

Permalink
Refactors the posts
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbrain-za committed Nov 11, 2023
1 parent 0cd0ed3 commit 2e912e3
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 253 deletions.
88 changes: 16 additions & 72 deletions src/apps/binary_upload.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::borrow::BorrowMut;

use crate::helpers::{
refresh,
submission::{Submission, SubmissionPromise, SubmissionResult},
fetchers::Requestor,
submission::{Submission, SubmissionResult},
Challenges, Languages,
};
use gloo_net::http;
use poll_promise::Promise;
use std::future::Future;
use std::sync::mpsc::{channel, Receiver, Sender};
use web_sys::RequestCredentials;

struct Binary {
filename: String,
Expand All @@ -17,8 +16,6 @@ struct Binary {
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct BinaryUpload {
#[serde(skip)]
promise: SubmissionPromise,
#[serde(skip)]
last_result: SubmissionResult,
url: String,
Expand All @@ -27,15 +24,12 @@ pub struct BinaryUpload {
#[serde(skip)]
binary_channel: (Sender<Binary>, Receiver<Binary>),
#[serde(skip)]
submit: bool,
#[serde(skip)]
token_refresh_promise: refresh::RefreshPromise,
submitter: Option<Requestor>,
}

impl Default for BinaryUpload {
fn default() -> Self {
Self {
promise: Default::default(),
url: option_env!("BACKEND_URL")
.unwrap_or("http://123.4.5.6:3000/")
.to_string(),
Expand All @@ -44,59 +38,17 @@ impl Default for BinaryUpload {
..Default::default()
},
binary_channel: channel(),
submit: false,
token_refresh_promise: None,
submitter: None,
last_result: SubmissionResult::NotStarted,
}
}
}

impl BinaryUpload {
fn submit(&mut self, ctx: &egui::Context) {
if !self.submit {
return;
}
self.submit = false;
fn submit(&mut self) {
let submission = self.run.clone();

let url = format!("{}api/game/binary", self.url);
log::debug!("Sending to {}", url);
let ctx = ctx.clone();

let promise = Promise::spawn_local(async move {
let formdata = submission.to_formdata();

let response = http::Request::post(&url)
.credentials(RequestCredentials::Include)
.body(formdata)
.unwrap()
.send()
.await
.unwrap();

let result: SubmissionResult = match response.status() {
200 => response.json().await.unwrap(),
401 => {
let text = response.text().await;
let text = text.map(|text| text.to_owned());
let text = match text {
Ok(text) => text,
Err(e) => e.to_string(),
};
log::warn!("Auth Error: {:?}", text);
SubmissionResult::NotAuthorized
}
_ => {
return Err(format!("Failed to submit code: {:?}", response));
}
};

ctx.request_repaint(); // wake up UI thread
log::info!("Result: {:?}", result);
Ok(result)
});

self.promise = Some(promise);
let url = format!("{}api/game/submit", self.url);
self.submitter = submission.sender(&url);
}
}

Expand All @@ -116,27 +68,19 @@ impl super::App for BinaryUpload {
self.run.filename = f.filename;
self.run.binary = Some(f.bytes);
}
self.submit(ctx);
match refresh::check_refresh_promise(&mut self.token_refresh_promise) {
refresh::RefreshStatus::InProgress => {}
refresh::RefreshStatus::Success => {
self.submit = true;
}
refresh::RefreshStatus::Failed(_) => {}
_ => (),
}

let submission = Submission::check_submit_promise(&mut self.promise);
let submission = Submission::check_sender(&mut self.submitter);
match submission {
SubmissionResult::NotStarted => {}
SubmissionResult::NotAuthorized => {
self.token_refresh_promise = refresh::submit_refresh();
self.last_result = submission;
}
_ => {
self.last_result = submission;
}
}
if let Some(fetcher) = self.submitter.borrow_mut() {
if fetcher.refresh_context() {
ctx.request_repaint();
}
}
}
}

Expand Down Expand Up @@ -191,7 +135,7 @@ impl super::View for BinaryUpload {
if ui.button("Submit").clicked() {
match self.run.validate() {
Ok(_) => {
self.submit = true;
self.submit();
}
Err(e) => {
self.last_result = SubmissionResult::Failure { message: e };
Expand Down
4 changes: 2 additions & 2 deletions src/apps/challenge_info.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::helpers::{fetchers::Getter, Challenges};
use crate::helpers::{fetchers::Requestor, Challenges};
use egui_commonmark::*;
use std::borrow::BorrowMut;

Expand All @@ -15,7 +15,7 @@ pub struct ChallengeInfoApp {
#[serde(skip)]
active_challenge: Challenges,
#[serde(skip)]
info_fetcher: Option<Getter>,
info_fetcher: Option<Requestor>,
instructions: String,
}

Expand Down
86 changes: 16 additions & 70 deletions src/apps/code_editor.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
use std::borrow::BorrowMut;

use crate::helpers::{
refresh,
submission::{Submission, SubmissionPromise, SubmissionResult},
fetchers::Requestor,
submission::{Submission, SubmissionResult},
Challenges, Languages,
};
use gloo_net::http;
use poll_promise::Promise;
use web_sys::RequestCredentials;

#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct CodeEditor {
#[serde(skip)]
promise: SubmissionPromise,
#[serde(skip)]
url: String,
#[serde(skip)]
run: Submission,
#[serde(skip)]
last_result: SubmissionResult,
#[serde(skip)]
submit: bool,
#[serde(skip)]
code: String,
#[serde(skip)]
token_refresh_promise: refresh::RefreshPromise,
submitter: Option<Requestor>,
}

impl Default for CodeEditor {
Expand All @@ -34,62 +29,22 @@ impl Default for CodeEditor {
};
run.language = Languages::Python;
Self {
promise: Default::default(),
url: option_env!("BACKEND_URL")
.unwrap_or("http://123.4.5.6:3000/")
.to_string(),
run,
code: "#A very simple example\nprint(\"Hello world!\")".into(),
submit: false,
token_refresh_promise: None,
last_result: SubmissionResult::NotStarted,
submitter: None,
}
}
}

impl CodeEditor {
fn submit(&mut self, ctx: &egui::Context) {
if !self.submit {
return;
}
self.submit = false;
fn submit(&mut self) {
let submission = self.run.clone();

let url = format!("{}api/game/submit", self.url);
log::debug!("Sending to {}", url);
let ctx = ctx.clone();

let promise = Promise::spawn_local(async move {
let response = http::Request::post(&url)
.credentials(RequestCredentials::Include)
.json(&submission)
.unwrap()
.send()
.await
.unwrap();

let result: SubmissionResult = match response.status() {
200 => response.json().await.unwrap(),
401 => {
let text = response.text().await;
let text = text.map(|text| text.to_owned());
let text = match text {
Ok(text) => text,
Err(e) => e.to_string(),
};
log::warn!("Auth Error: {:?}", text);
SubmissionResult::NotAuthorized
}
_ => {
return Err(format!("Failed to submit code: {:?}", response));
}
};

ctx.request_repaint(); // wake up UI thread
Ok(result)
});

self.promise = Some(promise);
self.submitter = submission.sender(&url);
}

fn as_test_submission(&mut self) {
Expand All @@ -109,33 +64,24 @@ impl super::App for CodeEditor {
}

fn show(&mut self, ctx: &egui::Context, open: &mut bool) {
self.submit(ctx);
use super::View as _;
egui::Window::new(self.name())
.open(open)
.default_height(500.0)
.show(ctx, |ui| self.ui(ui));

match refresh::check_refresh_promise(&mut self.token_refresh_promise) {
refresh::RefreshStatus::InProgress => {}
refresh::RefreshStatus::Success => {
self.submit = true;
}
refresh::RefreshStatus::Failed(_) => {}
_ => (),
}

let submission = Submission::check_submit_promise(&mut self.promise);
let submission = Submission::check_sender(&mut self.submitter);
match submission {
SubmissionResult::NotStarted => {}
SubmissionResult::NotAuthorized => {
self.token_refresh_promise = refresh::submit_refresh();
self.last_result = submission;
}
_ => {
self.last_result = submission;
}
}
if let Some(fetcher) = self.submitter.borrow_mut() {
if fetcher.refresh_context() {
ctx.request_repaint();
}
}
}
}

Expand Down Expand Up @@ -211,7 +157,7 @@ impl super::View for CodeEditor {
self.as_submission();
match self.run.validate() {
Ok(_) => {
self.submit = true;
self.submit();
}
Err(e) => {
self.last_result = SubmissionResult::Failure { message: e };
Expand All @@ -223,7 +169,7 @@ impl super::View for CodeEditor {
self.as_test_submission();
match self.run.validate() {
Ok(_) => {
self.submit = true;
self.submit();
}
Err(e) => {
self.last_result = SubmissionResult::Failure { message: e };
Expand Down
8 changes: 4 additions & 4 deletions src/apps/scoreboard_app.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::helpers::{
fetchers::{GetStatus, Getter},
fetchers::{GetStatus, Requestor},
Challenges,
};
use scoreboard_db::Builder as FilterBuilder;
Expand Down Expand Up @@ -36,7 +36,7 @@ pub struct ScoreBoardApp {
url: String,

#[serde(skip)]
score_fetcher: Option<Getter>,
score_fetcher: Option<Requestor>,
}

impl Default for ScoreBoardApp {
Expand Down Expand Up @@ -65,8 +65,8 @@ impl ScoreBoardApp {
let url = format!("{}api/game/scores/{}", self.url, self.challenge);

log::debug!("Fetching challenge info");
let mut getter = Getter::new(&url, true);
getter.get();
let mut getter = Requestor::new_get(&url, true);
getter.send();
self.score_fetcher = Some(getter);
}

Expand Down
Loading

0 comments on commit 2e912e3

Please sign in to comment.