Skip to content

Commit

Permalink
upload game progress
Browse files Browse the repository at this point in the history
  • Loading branch information
RobDavenport committed Apr 16, 2024
1 parent 15b1f19 commit fb90c1d
Show file tree
Hide file tree
Showing 8 changed files with 472 additions and 76 deletions.
358 changes: 318 additions & 40 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion gamercade_app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ path = "src/main.rs"
[dependencies]
gamercade_interface = { path = "../gamercade_interface" }

rfd = "0.11.3"

tokio = { version = "1.28.1", features = ["full"] }
tokio-stream = "0.1.14"
tonic = "0.10.2"
hyper = "1.2.0"
reqwest = "0.12.3"

eframe = "0.22.0"
rusqlite = { version = "0.30.0", features = ["bundled"] }
Expand Down
62 changes: 57 additions & 5 deletions gamercade_app/src/modes/arcade_mode/creator_dashboard.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
use gamercade_interface::game::UpdateGameRequest;
use gamercade_interface::{game::UpdateGameRequest, release::CreateReleaseRequest};
use rfd::FileDialog;

use crate::{app::AppDrawContext, task_manager::GameRequest, urls::WithSession};
use crate::{
app::AppDrawContext,
task_manager::{GameRequest, UploadReleaseRequest},
urls::WithSession,
};

#[derive(Default)]
pub struct CreatorDashboardView {}
pub struct CreatorDashboardView {
game_id: String,
release_name: String,
}

impl CreatorDashboardView {
pub fn draw(&mut self, context: &mut AppDrawContext) {
Expand All @@ -30,8 +38,52 @@ impl CreatorDashboardView {
}))
}

if ui.button("Manage Game").clicked() {}
ui.separator();

ui.label("Game Id:");
ui.text_edit_singleline(&mut self.game_id);

ui.label("Release Name or ID:");
ui.text_edit_singleline(&mut self.release_name);

if ui.button("Manage Game").clicked() {
println!("TODO!");
}

let game_id = self.game_id.parse();

if ui.button("Create Release").clicked() {}
if ui.button("Create Release").clicked() {
if let Ok(game_id) = game_id {
context.task_manager.release.try_create_release(
CreateReleaseRequest {
game_id,
release_name: self.release_name.clone(),
},
&context.auth_state.get_session().unwrap(),
)
} else {
self.game_id = String::new()
}
}

if ui.button("Upload Release").clicked() {
if let (Ok(game_id), Ok(release_id)) = (game_id, self.release_name.parse()) {
if let Some(file) = FileDialog::new()
.add_filter("gcrom (.gcrom)", &["gcrom"])
.pick_file()
{
let bytes = std::fs::read(file).unwrap();

context.task_manager.release.try_upload_release(
UploadReleaseRequest {
game_id,
release_id,
bytes,
},
&context.auth_state.get_session().unwrap(),
)
}
}
}
}
}
90 changes: 78 additions & 12 deletions gamercade_app/src/task_manager/release.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use gamercade_interface::release::release_service_client::ReleaseServiceClient;
use hyper::Request;
use gamercade_interface::{
release::{release_service_client::ReleaseServiceClient, CreateReleaseRequest},
Session, SESSION_METADATA_KEY,
};

use tokio::sync::OnceCell;
use tonic::transport::Channel;

use crate::urls;
use crate::urls::{self, WithSession, SERVICE_IP_GRPC};

use super::{TaskManager, TaskRequest};

Expand All @@ -15,45 +18,108 @@ pub struct ReleaseManagerState {
client: OnceCell<ReleaseServiceClient<Channel>>,
}

async fn init_release_client() -> ReleaseServiceClient<Channel> {
ReleaseServiceClient::connect(SERVICE_IP_GRPC)
.await
.unwrap()
}

#[derive(Debug)]
pub enum ReleaseRequest {
CreateRelease(WithSession<CreateReleaseRequest>),
DownloadRelease(DownloadReleaseRequest),
UploadRelease(WithSession<UploadReleaseRequest>),
}

#[derive(Debug)]
pub struct DownloadReleaseRequest {
game_id: u64,
release_id: u64,
pub game_id: i64,
pub release_id: i64,
}

#[derive(Debug)]
pub struct UploadReleaseRequest {
pub game_id: i64,
pub release_id: i64,
pub bytes: Vec<u8>,
}

impl TaskRequest<ReleaseManagerState> for ReleaseRequest {
async fn handle_request(
self,
sender: &tokio::sync::mpsc::Sender<super::TaskNotification>,
_sender: &tokio::sync::mpsc::Sender<super::TaskNotification>,
state: &tokio::sync::Mutex<ReleaseManagerState>,
) {
let mut lock = state.lock().await;
lock.client.get_or_init(init_release_client).await;
let client = lock.client.get_mut().unwrap();

match self {
ReleaseRequest::DownloadRelease(request) => {
let requst = Request::builder().uri(urls::download_release_url(
request.game_id,
request.release_id,
));
// TODO: This
todo!()
println!("TODO: Download a release");
}
ReleaseRequest::CreateRelease(request) => {
match client
.create_new_release(request.authorized_request())
.await
{
Ok(response) => println!("Release created: {response:?}"),
Err(e) => {
println!("Error creating release: {e}")
}
}
}
ReleaseRequest::UploadRelease(request) => {
let WithSession {
data: request,
session,
} = request;
let session = u128::from_ne_bytes(*session.bytes());
match reqwest::Client::new()
.post(urls::game_release_url(request.game_id, request.release_id))
.header(SESSION_METADATA_KEY, format!("{session:x}"))
.body(request.bytes)
.send()
.await
{
Ok(response) => {
let status = response.status();
let body = response.text().await;
println!("Upload release response ({status}): {body:?}");
}
Err(err) => println!("Upload release Error: {err}"),
}
}
}
}
}

impl ReleaseManager {
pub fn try_download(&mut self, game_id: u64, release_id: u64) {
pub fn try_download(&mut self, game_id: i64, release_id: i64) {
self.sender
.try_send(ReleaseRequest::DownloadRelease(DownloadReleaseRequest {
game_id,
release_id,
}))
.unwrap();
}

pub fn try_create_release(&mut self, request: CreateReleaseRequest, session: &Session) {
self.sender
.try_send(ReleaseRequest::CreateRelease(WithSession {
session: session.clone(),
data: request,
}))
.unwrap()
}

pub fn try_upload_release(&mut self, request: UploadReleaseRequest, session: &Session) {
self.sender
.try_send(ReleaseRequest::UploadRelease(WithSession {
session: session.clone(),
data: request,
}))
.unwrap()
}
}
6 changes: 2 additions & 4 deletions gamercade_app/src/urls.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
use std::str::FromStr;

use gamercade_interface::{Session, SESSION_METADATA_KEY};
use tonic::{metadata::MetadataValue, Request};

pub const SERVICE_IP_GRPC: &str = "http://127.0.0.1:50051";
pub const SERVICE_IP_HTTP: &str = "http://127.0.0.1:3000";

pub fn download_release_url(game_id: u64, release_id: u64) -> String {
format!("{SERVICE_IP_HTTP}/games/{game_id}/releases/{release_id}")
pub fn game_release_url(game_id: i64, release_id: i64) -> String {
format!("{SERVICE_IP_HTTP}/games/{game_id:x}/releases/{release_id:x}")
}

#[derive(Debug)]
Expand Down
2 changes: 1 addition & 1 deletion gamercade_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ pub use input::*;

pub const BYTES_PER_PIXEL: usize = 4;

pub const MAX_ROM_SIZE: usize = 1_048_576 * 16; // 16mb
pub const MAX_ROM_SIZE: usize = 1024 * 1024 * 16; // 16mb
21 changes: 8 additions & 13 deletions gamercade_fs/src/rom.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use std::{
fs,
io::{Read, Write},
path::PathBuf,
};
use std::{fs, io::Write, path::PathBuf};

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -45,19 +41,18 @@ impl Rom {
self.resolution.width()
}

pub fn try_load_bytes(bytes: &[u8]) -> Result<Self, String> {
let reader = zstd::Decoder::new(bytes).map_err(|e| e.to_string())?;
Ok(bincode::deserialize_from::<_, Self>(reader).map_err(|e| e.to_string())?)
}

pub fn try_load(path: &PathBuf) -> Result<Self, String> {
let file = fs::File::open(path).map_err(|e| e.to_string())?;

match path.extension().and_then(|path| path.to_str()) {
Some("gcrom") => {
let mut reader = zstd::Decoder::new(file).map_err(|e| e.to_string())?;

let mut buffer = Vec::new();

// We don't care about how many bytes are read
let _ = reader.read_to_end(&mut buffer).map_err(|e| e.to_string());

bincode::deserialize_from::<_, Rom>(&*buffer).map_err(|e| e.to_string())
let reader = zstd::Decoder::new(file).map_err(|e| e.to_string())?;
bincode::deserialize_from::<_, Self>(reader).map_err(|e| e.to_string())
}
Some("wasm") => {
println!("No assets provided. Using default Asset pack.");
Expand Down
6 changes: 6 additions & 0 deletions gamercade_interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,9 @@ impl TryFrom<&[u8]> for Session {
))
}
}

impl From<u128> for Session {
fn from(value: u128) -> Self {
Self(value.to_le_bytes())
}
}

0 comments on commit fb90c1d

Please sign in to comment.