69 lines
1.6 KiB
Rust
69 lines
1.6 KiB
Rust
use std::sync::Arc;
|
|
|
|
use chrono::{Duration, Utc};
|
|
use rand::distributions::Alphanumeric;
|
|
use rand::Rng;
|
|
|
|
use geoffrey_models::models::link::Link;
|
|
use geoffrey_models::models::parameters::link_params::LinkParameters;
|
|
use geoffrey_models::models::player::Player;
|
|
use geoffrey_models::models::CommandLevel;
|
|
use geoffrey_models::GeoffreyDatabaseModel;
|
|
|
|
use crate::api_endpoint::{ApiEndpoint, RequestType};
|
|
use crate::commands::Command;
|
|
use crate::context::Context;
|
|
use crate::Result;
|
|
|
|
pub struct LinkCommand {}
|
|
|
|
impl ApiEndpoint for LinkCommand {
|
|
fn endpoint_name() -> String {
|
|
"link".to_string()
|
|
}
|
|
|
|
fn request_type() -> RequestType {
|
|
RequestType::POST
|
|
}
|
|
}
|
|
|
|
impl Command for LinkCommand {
|
|
type Req = LinkParameters;
|
|
type Resp = Link;
|
|
|
|
fn command_level() -> CommandLevel {
|
|
CommandLevel::REGISTERED
|
|
}
|
|
|
|
fn run_command(
|
|
ctx: Arc<Context>,
|
|
_req: &Self::Req,
|
|
player: Option<Player>,
|
|
) -> Result<Self::Resp> {
|
|
let player = player.unwrap();
|
|
|
|
let links: Vec<Link> = ctx
|
|
.db
|
|
.filter(|_, link: &Link| player.id().unwrap() == link.player_id)?
|
|
.collect();
|
|
|
|
for link in links {
|
|
ctx.db.remove::<Link>(link.id().unwrap())?;
|
|
}
|
|
|
|
let link_code: String = rand::thread_rng()
|
|
.sample_iter(&Alphanumeric)
|
|
.take(10)
|
|
.map(char::from)
|
|
.collect();
|
|
|
|
let expire_time = Utc::now() + Duration::days(1);
|
|
|
|
let link = Link::new(player.id.unwrap(), link_code, expire_time);
|
|
|
|
let link = ctx.db.insert(link)?;
|
|
|
|
Ok(link)
|
|
}
|
|
}
|