diff --git a/controllers/game.go b/controllers/game.go new file mode 100644 index 0000000..ab11dd7 --- /dev/null +++ b/controllers/game.go @@ -0,0 +1,35 @@ +package controllers + +import ( + "cds/dao" + "fmt" + + "github.com/gofiber/fiber/v2" + "go.mongodb.org/mongo-driver/mongo" +) + +// @Summary Renvoie les informations sur un jeu. +// @Produce json +// @Success 200 {object} models.Game +// @Failure 403 +// @Failure 404 +// @Failure 500 +// @Router /games/{id} [get] +func GetGameById(c *fiber.Ctx) error { + token := c.Cookies("token", "") + if token == "" { + return c.SendStatus(fiber.StatusForbidden) + } else { + id := c.Params("id") + game, err := dao.GetGameById(id) + if err == mongo.ErrNoDocuments { + return c.SendStatus(fiber.StatusNotFound) + } else if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ + "error": fmt.Sprint(err), + }) + } else { + return c.Status(fiber.StatusOK).JSON(game) + } + } +} diff --git a/front/Cargo.toml b/front/Cargo.toml index 41aeb02..4ce25ba 100644 --- a/front/Cargo.toml +++ b/front/Cargo.toml @@ -15,3 +15,5 @@ wasm-bindgen-futures = "0.4" gloo-storage = "0.2.2" patternfly-yew = "0.2.0" +wasm-logger = "0.2.0" +log = "0.4.17" diff --git a/front/src/main.rs b/front/src/main.rs index d5f7994..a65d826 100644 --- a/front/src/main.rs +++ b/front/src/main.rs @@ -16,6 +16,8 @@ struct User { level: u32, money: u32, moneylimit: u32, + steamid: String, + discordid: String, discordname: String, } @@ -34,14 +36,11 @@ enum Route { #[function_component(About)] fn about() -> Html { let _history = use_history().unwrap(); - //LocalStorage::set("test", "coucou"); let test: String = LocalStorage::get("test").unwrap_or(String::from("nop")); - //let onclick = Callback::once(move |_| history.push(Route::Home)); html! { <>

{ "À propos" }

{ test }

- //{ "Index" } } } @@ -135,18 +134,28 @@ impl Component for Home { }); } - let onclick = ctx.link().callback(|_| TestMessage::Test); + //let onclick = ctx.link().callback(|_| TestMessage::Test); html! { <> if let Some(user) = &self.user {

{ format!("Bienvenue {} !", user.discordname) }

+ if user.discordid.is_empty() { +

{ "SE CONNECTER VIA DISCORD ICI" }

+ } + + if user.steamid.is_empty() { +

{ "SE CONNECTER VIA STEAM ICI" }

+ } +
+ +
} else {

{ "SE CONNECTER VIA DISCORD ICI" }

{ "SE CONNECTER VIA STEAM ICI" }

} - + // } } @@ -193,103 +202,159 @@ impl Component for Home { } } -/* -#[function_component(Home)] -fn home() -> Html { - // check if the cookie is set - let state = use_state(|| StatusConnection::NotConnected); - //let connected = use_state_eq(|| false); - { - let state = state.clone(); - use_effect(move || { - //let connected = connected.clone(); - wasm_bindgen_futures::spawn_local(async move { - if let Ok(resp) = Request::get("/api/users/current").send().await { - if resp.ok() { - let json: Result = resp.json().await; - if let Ok(json) = json { - LocalStorage::set("auth", json); - state.set(StatusConnection::UpdateConnection); - } else if let Err(err) = json { - LocalStorage::delete("auth"); - state.set(StatusConnection::Error(err.to_string())); - } - } else { - state.set(StatusConnection::NotConnected); +#[derive(Deserialize, Serialize)] +struct Game { + name: String, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +struct Group { + pub name: String, + pub game: String, +} + +impl Group { + pub async fn get_game_name(&mut self) { + match Request::get(&format!("/api/games/{}", self.game)) + .send() + .await + { + Ok(resp) => { + if resp.ok() { + let json: Result = resp.json().await; + match json { + Ok(json) => self.game = json.name, + Err(err) => log::info!("{}", err.to_string()), } } - }); - || () - }); - } - - /* - let client = Client::new(); - if let Ok(resp) = client.get("/users/current").send() { - if resp.status() == StatusCode::OK { - if let Ok(json) = resp.json::() { - LocalStorage::set("auth", json); } + Err(err) => (), } } - */ - - let _user: Result = LocalStorage::get("auth"); - if let Ok(user) = LocalStorage::get("auth") { - if *state == StatusConnection::UpdateConnection { - let state = state.clone(); - state.set(StatusConnection::Connected(user)); - } - } - - - match &*state { - StatusConnection::NotConnected => { - html! { - <> -

{ "SE CONNECTER VIA DISCORD ICI" }

-

{ "SE CONNECTER VIA STEAM ICI" }

- - } - }, - StatusConnection::UpdateConnection => { - html!{

{ "Connexion en cours..." }

} - }, - StatusConnection::Connected(user) => html!{

{ format!("Bienvenue {} !", user.discordname) }

}, - StatusConnection::Error(err) => { - html! { - <> -

{ "Erreur !!" }

-

{ err }

- - } - } - } - - /* - let tmp: Result = LocalStorage::get("auth"); - if let Ok(o) = tmp { - } else { - let check_auth = use_state(|| None::); - - wasm_bindgen_futures::spawn_local(async move { - if let Ok(resp) = Request::get("/users/current").send().await { - if let Ok(user) = resp.json().await { - check_auth.set(Some(user)) - } - }; - }); - - if let Some(user) = (*check_auth).clone() { - LocalStorage::set("auth", user); - - } - - //html! { "Vous êtes connecté !" } - } - */ } -*/ + +struct ListGroups { + idUser: String, + groups: Vec, + nb_show: usize, +} + +#[derive(PartialEq, Properties)] +struct PropGroups { + id: String, +} + +#[derive(PartialEq)] +enum MsgListGroups { + Done(Vec), + Info(String, String), + Error(String, String), + More, +} + +impl Component for ListGroups { + type Message = MsgListGroups; + type Properties = PropGroups; + + fn create(ctx: &Context) -> Self { + Self { + idUser: ctx.props().id.clone(), + groups: Vec::new(), + nb_show: 0, + } + } + + fn view(&self, ctx: &Context) -> Html { + if self.groups.len() == 0 { + let id = self.idUser.clone(); + ctx.link().send_future(async move { + match Request::get(&format!("/api/users/{}/groups", id)) + .send() + .await + { + Ok(resp) => { + if resp.ok() { + let json: Result, Error> = resp.json().await; + match json { + Ok(mut json) => { + for item in json.iter_mut() { + item.get_game_name().await; + } + return MsgListGroups::Done(json); + } + Err(err) => { + log::info!("{}", err.to_string()); + () + } + } + } + } + Err(err) => (), + }; + MsgListGroups::Info(String::from("Ok"), String::new()) + }); + } + + let onclick = ctx.link().callback(|_| MsgListGroups::More); + + html! { + <> + + if self.groups.len() > 0 { + { + self.groups[..self.nb_show].iter().map(|group| { html!{ +

{ group.name.clone() }

+ } }).collect::() + } + + if self.nb_show < self.groups.len() { + + } + } else { +

{ "Vous n'êtes dans aucun groupe." }

+ } + //

{ "coucou" }

+ + } + } + + fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { + match msg { + MsgListGroups::Info(title, body) => { + if let Some(parent) = ctx.link().get_parent() { + (parent.clone()) + .downcast::() + .send_message(TestMessage::Toast(ToastType::Info(ToastFields { + title, + body, + }))) + } + } + MsgListGroups::Error(title, body) => { + if let Some(parent) = ctx.link().get_parent() { + (parent.clone()) + .downcast::() + .send_message(TestMessage::Toast(ToastType::Error(ToastFields { + title, + body, + }))) + } + } + MsgListGroups::Done(groups) => { + self.groups = groups; + return true; + } + MsgListGroups::More => { + self.nb_show += 3; + if self.nb_show > self.groups.len() { + self.nb_show -= self.nb_show - self.groups.len(); + } + return true; + } + } + false + } +} fn switch(route: &Route) -> Html { match route { @@ -307,39 +372,13 @@ fn app() -> Html { render={Switch::render(switch)} /> } - /* - html! { -
-

{ "Chasseurs De Succès" }

-

{ "Bienvenue sur le site pour gérer les groupes de chasses" }

-
- } - */ } fn main() { + wasm_logger::init(wasm_logger::Config::default()); yew::start_app::(); } -/* -#[derive(Clone, Deserialize, PartialEq, Serialize)] -struct Group { - name: String, -} - -struct ListGroups { - list: Vec, -} - -impl Component for ListGroups { - fn create(_ctx: &Context) -> Self { - Self { - - } - } -} -*/ - #[function_component(Test)] fn test() -> Html { let test = use_state(|| String::from("")); diff --git a/main.go b/main.go index fe895ea..11a2f92 100644 --- a/main.go +++ b/main.go @@ -27,6 +27,7 @@ func setupRoutes(app *fiber.App) { api := app.Group("/api") routes.GroupRoute(api.Group("/groups")) routes.UserRoute(api.Group("/users")) + routes.GameRoute(api.Group("/games")) app.Get("/swagger/*", swagger.HandlerDefault) app.Get("/login/:provider", goth_fiber.BeginAuthHandler) diff --git a/models/game.go b/models/game.go index 64ee347..70e6dba 100644 --- a/models/game.go +++ b/models/game.go @@ -8,7 +8,7 @@ type Game struct { HasAchievements bool `bson:"hasAchievements"` IsCoop bool `bson:"isCoop"` IsMulti bool `bson:"isMulti"` - Name string `bson:"name"` + Name string `bson:"name" json:"name"` } func NewGame() *Game { diff --git a/models/group.go b/models/group.go index 7e46301..08cf4b4 100644 --- a/models/group.go +++ b/models/group.go @@ -4,11 +4,11 @@ import "go.mongodb.org/mongo-driver/bson/primitive" type Group struct { Id primitive.ObjectID `bson:"_id", omitempty` - Name string `bson:"name"` + Name string `bson:"name" json:"name"` Desc string `bson:"desc"` NbMax int `bson:"nbMax"` Members []primitive.ObjectID `bson:"members"` - Game primitive.ObjectID `bson:"game"` + Game primitive.ObjectID `bson:"game" json:"game"` } func NewGroup() *Group { diff --git a/models/user.go b/models/user.go index c35d5ea..63aa44a 100644 --- a/models/user.go +++ b/models/user.go @@ -11,8 +11,8 @@ type User struct { Level uint `bson:"level" json:"level"` Money uint `bson:"money" json:"money"` MoneyLimit uint `bson:"moneyLimit" json:"moneylimit"` - DiscordId string `bson:"userId,omitempty" json:"userid"` - SteamId string `bson:"steamId,omitempty" json:"steamid"` + DiscordId string `bson:"userId" json:"discordid"` + SteamId string `bson:"steamId" json:"steamid"` DiscordName string `bson:"username,omitempty" json:"discordname"` } diff --git a/routes/game.go b/routes/game.go new file mode 100644 index 0000000..efcddf7 --- /dev/null +++ b/routes/game.go @@ -0,0 +1,11 @@ +package routes + +import ( + "cds/controllers" + + "github.com/gofiber/fiber/v2" +) + +func GameRoute(route fiber.Router) { + route.Get("/:id", controllers.GetGameById) +}