This commit is contained in:
Tomasz Sidoruk 2022-06-19 15:06:19 +02:00
parent 103ec0bb23
commit 752055b95f

View File

@ -1,27 +1,36 @@
use std::collections::HashMap; use std::collections::HashMap;
use serde_derive::{Serialize, Deserialize}; use serde_derive::{Serialize, Deserialize};
use mysql::*; use mysql::*;
use mysql::prelude::*; use mysql::prelude::*;
use std::convert::Infallible; use std::convert::Infallible;
use std::net::SocketAddr; use std::net::SocketAddr;
use hyper::{Body, Client, Method, Request, Response, Server, StatusCode}; use hyper::{Body, Client, Method, Request, Response, Server, StatusCode};
use hyper::service::{make_service_fn, service_fn}; use hyper::service::{make_service_fn, service_fn};
use bcrypt::{DEFAULT_COST, hash, verify}; use bcrypt::{DEFAULT_COST, hash, verify};
use rand::{OsRng, Rng}; use rand::{OsRng, Rng};
use serde_json::Map; use serde_json::Map;
use std::thread;
use std::time::Duration;
use tokio::time::sleep;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Proposal { struct SearchResult {
name: String,
surname: String,
}
#[derive(Serialize, Deserialize)]
struct Proposal {
id: i32, id: i32,
ladderid: i32, ladderid: i32,
winner: String, winner: String,
proposer: i32, proposer: i32,
approver: i32, approver: i32,
score: String, score: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct User { struct User {
id: i32, id: i32,
name: String, name: String,
surname: String, surname: String,
@ -30,17 +39,17 @@ struct User {
phone: String, phone: String,
mail: String, mail: String,
ranking: i32, ranking: i32,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct leaderboard { struct leaderboard {
name: String, name: String,
surname: String, surname: String,
ranking: i32, ranking: i32,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct ladderRaw { struct ladderRaw {
id: i32, id: i32,
inAtype: String, inAtype: String,
inA: String, inA: String,
@ -49,21 +58,21 @@ struct ladderRaw {
winner: String, winner: String,
round: String, round: String,
scores: String, scores: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Registration { struct Registration {
id: i32, id: i32,
userid: i32, userid: i32,
tournamentid: String, tournamentid: String,
paymenttype: String, paymenttype: String,
paymentstatus: String, paymentstatus: String,
approval: String, approval: String,
partner: i32, partner: i32
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Usera { struct Usera {
id: i32, id: i32,
name: String, name: String,
surname: String, surname: String,
@ -73,10 +82,10 @@ struct Usera {
mail: String, mail: String,
deleted: i32, deleted: i32,
ranking: i32, ranking: i32,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct tournament { struct tournament {
id: i32, id: i32,
name: String, name: String,
typeOfLadder: String, typeOfLadder: String,
@ -87,10 +96,21 @@ struct tournament {
approved: i32, approved: i32,
state: i32, state: i32,
currentRound: i32, currentRound: i32,
} from: String,
to: String,
place: String,
categotry: String,
rang: String,
entryFee: i32,
director: String,
phone: String,
entriesTo: String,
additionalInformations: String,
visibility: String,
}
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct tournamenta { struct tournamenta {
id: i32, id: i32,
name: String, name: String,
typeOfLadder: String, typeOfLadder: String,
@ -102,13 +122,52 @@ struct tournamenta {
deleted: i32, deleted: i32,
state: i32, state: i32,
currentRound: i32, currentRound: i32,
} from: String,
to: String,
place: String,
categotry: String,
rang: String,
entryFee: i32,
director: String,
phone: String,
entriesTo: String,
additionalInformations: String,
visibility: String,
}
thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://inz:HaLzqw68CbabS8Smz3Vx!@10.1.6.101:3306/inz").unwrap()).unwrap()); thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://inz:****!@*****:3306/inz").unwrap()).unwrap());
async fn hello_world(req: Request<Body>) -> Result<Response<Body>> { async fn hello_world(req: Request<Body>) -> Result<Response<Body>> {
let mut response = Response::new(Body::empty()); let mut response = Response::new(Body::empty());
response.headers_mut().insert("Access-Control-Allow-Origin","*".parse().unwrap());
response.headers_mut().insert("Access-Control-Allow-Methods","POST, GET, OPTIONS, PUT, DELETE".parse().unwrap());
response.headers_mut().insert("Access-Control-Allow-Headers","*".parse().unwrap());
if req.method() == &Method::OPTIONS{
return Ok(response);
}
match (req.method(), req.uri().path()) { match (req.method(), req.uri().path()) {
(&Method::GET, "/user/byId") => {
let query: &str = req.uri().query().unwrap();
let mut splited = query.split("=");
let id = splited.next().unwrap();
let val = splited.next().unwrap();
if id != "id" {
*response.body_mut() = "{\"error\":\"id required\"}".into();
return Ok(response);
}
POOL.with(|poola| {
let res = poola.get_conn().unwrap()
.exec_map(
"SELECT name, surname FROM users where deleted =0 and id = ? ;", (&val, ),
|(name,surname)| {
SearchResult { name,surname }
},
);
*response.body_mut() = serde_json::to_string(&res.unwrap().get(0)).unwrap().into();
});
}
(&Method::GET, "/proposals/pending") => { (&Method::GET, "/proposals/pending") => {
if req.headers().contains_key("Authorization") { if req.headers().contains_key("Authorization") {
let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" ");
@ -251,13 +310,13 @@ async fn hello_world(req: Request<Body>) -> Result<Response<Body>> {
POOL.with(|poola| { POOL.with(|poola| {
res3 = poola.get_conn().unwrap() res3 = poola.get_conn().unwrap()
.exec_iter("WITH RECURSIVE menu_tree .exec_iter("WITH RECURSIVE menu_tree
AS ( AS (
SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =? SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =?
UNION ALL UNION ALL
SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null)))
FROM menu_tree mn, inz.ladder la FROM menu_tree mn, inz.ladder la
WHERE mn.val= la.id and mn.type != 'R' WHERE mn.val= la.id and mn.type != 'R'
) )
SELECT * FROM menu_tree where type = 'R'", (&ladderid, ), SELECT * FROM menu_tree where type = 'R'", (&ladderid, ),
).unwrap().iter().unwrap().next(); ).unwrap().iter().unwrap().next();
}); });
@ -274,13 +333,13 @@ SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val'
POOL.with(|poola| { POOL.with(|poola| {
res3 = poola.get_conn().unwrap() res3 = poola.get_conn().unwrap()
.exec_iter("WITH RECURSIVE menu_tree .exec_iter("WITH RECURSIVE menu_tree
AS ( AS (
SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =? SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =?
UNION ALL UNION ALL
SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null)))
FROM menu_tree mn, inz.ladder la FROM menu_tree mn, inz.ladder la
WHERE mn.val= la.id and mn.type != 'R' WHERE mn.val= la.id and mn.type != 'R'
) )
SELECT * FROM menu_tree where type = 'R'", (&ladderid, ), SELECT * FROM menu_tree where type = 'R'", (&ladderid, ),
).unwrap().iter().unwrap().next(); ).unwrap().iter().unwrap().next();
}); });
@ -350,24 +409,24 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
).unwrap().iter().unwrap().next(); ).unwrap().iter().unwrap().next();
let res2 = poola.get_conn().unwrap() let res2 = poola.get_conn().unwrap()
.exec_iter("WITH RECURSIVE menu_tree .exec_iter("WITH RECURSIVE menu_tree
AS ( AS (
SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =? SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =?
UNION ALL UNION ALL
SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null)))
FROM menu_tree mn, inz.ladder la FROM menu_tree mn, inz.ladder la
WHERE mn.val= la.id and mn.type != 'R' WHERE mn.val= la.id and mn.type != 'R'
) )
SELECT * FROM menu_tree where type = 'R'", (val, ), SELECT * FROM menu_tree where type = 'R'", (val, ),
).unwrap().iter().unwrap().next(); ).unwrap().iter().unwrap().next();
let res3 = poola.get_conn().unwrap() let res3 = poola.get_conn().unwrap()
.exec_iter("WITH RECURSIVE menu_tree .exec_iter("WITH RECURSIVE menu_tree
AS ( AS (
SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =? SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =?
UNION ALL UNION ALL
SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null)))
FROM menu_tree mn, inz.ladder la FROM menu_tree mn, inz.ladder la
WHERE mn.val= la.id and mn.type != 'R' WHERE mn.val= la.id and mn.type != 'R'
) )
SELECT * FROM menu_tree where type = 'R'", (val, ), SELECT * FROM menu_tree where type = 'R'", (val, ),
).unwrap().iter().unwrap().next(); ).unwrap().iter().unwrap().next();
let ur = res.unwrap().unwrap(); let ur = res.unwrap().unwrap();
@ -565,14 +624,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
*response.body_mut() = "{\"error\":\"no all fields\"}".into(); *response.body_mut() = "{\"error\":\"no all fields\"}".into();
return Ok(response); return Ok(response);
} }
if s.get("inBtype").unwrap() != "R" && s.get("inBtype").unwrap() != "W" && s.get("inBtype").unwrap() != "L" {
*response.body_mut() = "{\"error\":\"inBtype must be R, W or L\"}".into();
return Ok(response);
}
if s.get("inAtype").unwrap() != "R" && s.get("inAtype").unwrap() != "W" && s.get("inAtype").unwrap() != "L" {
*response.body_mut() = "{\"error\":\"inAtype must be R, W or L\"}".into();
return Ok(response);
}
let mut row: Option<Result<Row>> = None; let mut row: Option<Result<Row>> = None;
let mut row3: Option<Result<Row>> = None; let mut row3: Option<Result<Row>> = None;
POOL.with(|poola| { POOL.with(|poola| {
@ -585,11 +637,71 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
*response.status_mut() = StatusCode::FORBIDDEN; *response.status_mut() = StatusCode::FORBIDDEN;
return Ok(response); return Ok(response);
} }
let tournamentid = s.get("tournamentid");
if s.get("inBtype").unwrap() == "R" {
let mut row4: Option<Result<Row>> = None;
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("Select id from registrations where id= ? and paymentstatus = 'DONE' and tournamentid =?", (&s.get("inB"),&tournamentid )).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
if row4.is_none() {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
}else {
if s.get("inBtype").unwrap() == "W" || s.get("inBtype").unwrap() == "L" {
let mut row4: Option<Result<Row>> = None;
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("Select id from ladder where id= ? and tournamentid=?", (&s.get("inB"),&tournamentid )).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
if row4.is_none() {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
} else {
*response.body_mut() = "{\"error\":\"inBtype must be R, W or L\"}".into();
return Ok(response);
}
}
if s.get("inAtype").unwrap() == "R" {
let mut row4: Option<Result<Row>> = None;
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("Select id from registrations where id= ? and paymentstatus = 'DONE' and tournamentid=?", (&s.get("inA"),&tournamentid )).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
if row4.is_none() {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
}else {
if s.get("inAtype").unwrap() == "W" || s.get("inAtype").unwrap() == "L" {
let mut row4: Option<Result<Row>> = None;
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("Select id from ladder where id= ? and tournamentid=?", (&s.get("inA"),&tournamentid )).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
if row4.is_none() {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
} else {
*response.body_mut() = "{\"error\":\"inAtype must be R, W or L\"}".into();
return Ok(response);
}
}
let urow = row.unwrap().unwrap(); let urow = row.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap(); let id: i32 = urow.get(0).unwrap();
let role: String = urow.get(1).unwrap(); let role: String = urow.get(1).unwrap();
let tournamentid = s.get("tournamentid");
if role == "2" { if role == "2" {
POOL.with(|poola| { POOL.with(|poola| {
let mut con3 = poola.get_conn().unwrap(); let mut con3 = poola.get_conn().unwrap();
@ -917,7 +1029,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
if role == "1" { if role == "1" {
let res = poola.get_conn().unwrap() let res = poola.get_conn().unwrap()
.exec_map( .exec_map(
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner -?);", (&val, id, id), "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner =?);", (&val, id, id),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
}, },
@ -934,7 +1046,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
if userid != id { if userid != id {
let res = poola.get_conn().unwrap() let res = poola.get_conn().unwrap()
.exec_map( .exec_map(
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner -?);", (&val, id, id), "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner =?);", (&val, id, id),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
}, },
@ -1154,6 +1266,39 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
if s.contains_key("currentRound") { if s.contains_key("currentRound") {
poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ?", (s.get("currentRound"), &s.get("id"))).unwrap(); poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ?", (s.get("currentRound"), &s.get("id"))).unwrap();
} }
if s.contains_key("from") {
poola.get_conn().unwrap().exec_drop("Update tournaments set `from` =? where id = ? ", (s.get("from"), &s.get("id"))).unwrap();
}
if s.contains_key("to") {
poola.get_conn().unwrap().exec_drop("Update tournaments set `to` =? where id = ? ", (s.get("to"), &s.get("id"))).unwrap();
}
if s.contains_key("place") {
poola.get_conn().unwrap().exec_drop("Update tournaments set place =? where id = ? ", (s.get("place"), &s.get("id"))).unwrap();
}
if s.contains_key("categotry") {
poola.get_conn().unwrap().exec_drop("Update tournaments set categotry =? where id = ? ", (s.get("categotry"), &s.get("id"))).unwrap();
}
if s.contains_key("rang") {
poola.get_conn().unwrap().exec_drop("Update tournaments set rang =? where id = ? ", (s.get("rang"), &s.get("id"))).unwrap();
}
if s.contains_key("entryFee") {
poola.get_conn().unwrap().exec_drop("Update tournaments set entryFee =? where id = ? ", (s.get("entryFee"), &s.get("id"))).unwrap();
}
if s.contains_key("director") {
poola.get_conn().unwrap().exec_drop("Update tournaments set director =? where id = ? ", (s.get("director"), &s.get("id"))).unwrap();
}
if s.contains_key("phone") {
poola.get_conn().unwrap().exec_drop("Update tournaments set phone =? where id = ? ", (s.get("phone"), &s.get("id"))).unwrap();
}
if s.contains_key("entriesTo") {
poola.get_conn().unwrap().exec_drop("Update tournaments set entriesTo =? where id = ? ", (s.get("entriesTo"), &s.get("id"))).unwrap();
}
if s.contains_key("additionalInformations") {
poola.get_conn().unwrap().exec_drop("Update tournaments set additionalInformations =? where id = ? ", (s.get("additionalInformations"), &s.get("id"))).unwrap();
}
if s.contains_key("visibility") {
poola.get_conn().unwrap().exec_drop("Update tournaments set visibility =? where id = ? ", (s.get("visibility"), &s.get("id"))).unwrap();
}
}); });
} else { } else {
*response.status_mut() = StatusCode::UNAUTHORIZED; *response.status_mut() = StatusCode::UNAUTHORIZED;
@ -1178,14 +1323,16 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
*response.status_mut() = StatusCode::FORBIDDEN; *response.status_mut() = StatusCode::FORBIDDEN;
return; return;
} }
let res = poola.get_conn().unwrap() let mut res = Vec::new() ;
.query_map( poola.get_conn().unwrap()
"SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved,deleted, state, currentRound from tournaments ", .query_iter(
|(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved, deleted, state, currentRound)| { "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved,deleted, state, currentRound,`from`, `to`, place, categotry, rang, entryFee, director, phone,entriesTo, additionalInformations,visibility from tournaments ",
tournamenta { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved, deleted, state, currentRound } ).unwrap().for_each(|row| {
}, let result_set = row.unwrap();
); res.push(tournamenta { id: result_set.get(0).unwrap(), name:result_set.get(1).unwrap(), typeOfLadder: result_set.get(2).unwrap(), places:result_set.get(4).unwrap(), roles:result_set.get(5).unwrap(), creator:result_set.get(6).unwrap(), pointsForTournament: result_set.get(3).unwrap(), approved:result_set.get(7).unwrap(), deleted:result_set.get(8).unwrap(), state:result_set.get(9).unwrap(), currentRound:result_set.get(10).unwrap() ,from:result_set.get(11).unwrap(), to:result_set.get(12).unwrap(), place:result_set.get(13).unwrap(), categotry:result_set.get(14).unwrap(), rang:result_set.get(15).unwrap(), entryFee:result_set.get(16).unwrap(), director:result_set.get(17).unwrap(), phone:result_set.get(18).unwrap(), entriesTo:result_set.get(19).unwrap(),additionalInformations:result_set.get(20).unwrap(),visibility:result_set.get(21).unwrap()});
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); });
*response.body_mut() = serde_json::to_string(&res).unwrap().into();
}); });
} else { } else {
*response.status_mut() = StatusCode::UNAUTHORIZED; *response.status_mut() = StatusCode::UNAUTHORIZED;
@ -1361,9 +1508,9 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
let client = Client::new(); let client = Client::new();
let req = Request::builder() let req = Request::builder()
.method(Method::GET) .method(Method::GET)
.uri("http://10.1.6.101:8082/api/v1/stores/6N6yuxW7HGSbHnsLM1csvFqRz72DP2EkY5YFBz4jGdQK/invoices/".to_owned() + &paymentreference) .uri("http://10.1.6.101:8082/api/v1/stores/****/invoices/".to_owned() + &paymentreference)
.header("content-type", "application/json") .header("content-type", "application/json")
.header("Authorization", "token 305562c7ec5f6d6870e534abf86084b085696f92").body(Body::empty()).unwrap(); .header("Authorization", "token *****").body(Body::empty()).unwrap();
let resp = client.request(req).await.unwrap(); let resp = client.request(req).await.unwrap();
let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap(); let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap();
let stat: String = parsed.get("status").unwrap().as_str().unwrap().into(); let stat: String = parsed.get("status").unwrap().as_str().unwrap().into();
@ -1387,7 +1534,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
} else { } else {
*response.body_mut() = Body::from("{\"status\":\"".to_owned() + &stat + "\"}"); *response.body_mut() = Body::from("{\"status\":\"".to_owned() + &stat + "\"}");
POOL.with(|poola| { POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus ='?' where id = ?", (stat, val)).unwrap(); poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus =? where id = ?", (stat, val)).unwrap();
}); });
} }
} }
@ -1414,6 +1561,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
let s: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap(); let s: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
let mut row: Option<Result<Row>> = None; let mut row: Option<Result<Row>> = None;
let mut row2: Option<Result<Row>> = None; let mut row2: Option<Result<Row>> = None;
let mut row3: Option<Result<Row>> = None;
if s.contains_key("tournament") && s.contains_key("paymentmethod") && s.contains_key("partner") { if s.contains_key("tournament") && s.contains_key("paymentmethod") && s.contains_key("partner") {
let tournament = s.get("tournament").unwrap().to_string(); let tournament = s.get("tournament").unwrap().to_string();
let partner = s.get("partner").unwrap().to_string(); let partner = s.get("partner").unwrap().to_string();
@ -1426,9 +1574,14 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
row = it.next(); row = it.next();
let mut con2 = poola.get_conn().unwrap(); let mut con2 = poola.get_conn().unwrap();
let mut result2 = con2.exec_iter("Select id from tournaments where state = 0 and id =?;", (&tournament, )).unwrap(); let mut result2 = con2.exec_iter("Select id, entryFee from tournaments where state = 0 and id =?;", (&tournament, )).unwrap();
let mut it2 = result2.iter().unwrap(); let mut it2 = result2.iter().unwrap();
row2 = it2.next(); row2 = it2.next();
let mut con3 = poola.get_conn().unwrap();
let mut result3 = con3.exec_iter("SELECT id FROM inz.users where id= ?;", (&partner, )).unwrap();
let mut it3 = result3.iter().unwrap();
row3 = it3.next();
}); });
if row.is_none() { if row.is_none() {
*response.status_mut() = StatusCode::FORBIDDEN; *response.status_mut() = StatusCode::FORBIDDEN;
@ -1438,24 +1591,31 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
*response.status_mut() = StatusCode::BAD_REQUEST; *response.status_mut() = StatusCode::BAD_REQUEST;
return Ok(response); return Ok(response);
} }
if row3.is_none() {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
let urow = row.unwrap().unwrap(); let urow = row.unwrap().unwrap();
let urow2 = row2.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap(); let id: i32 = urow.get(0).unwrap();
let fee: i32 = urow2.get(1).unwrap();
let paymentmethod = s.get("paymentmethod").unwrap().to_string(); let paymentmethod = s.get("paymentmethod").unwrap().to_string();
if paymentmethod == "btc" { if paymentmethod == "btc" {
let client = Client::new(); let client = Client::new();
let req = Request::builder() let req = Request::builder()
.method(Method::POST) .method(Method::POST)
.uri("http://10.1.6.101:8082/api/v1/stores/6N6yuxW7HGSbHnsLM1csvFqRz72DP2EkY5YFBz4jGdQK/invoices") .uri("http://10.1.6.101:8082/api/v1/stores/*****/invoices")
.header("content-type", "application/json") .header("content-type", "application/json")
.header("Authorization", "token 305562c7ec5f6d6870e534abf86084b085696f92") .header("X-Forwarded-Host", "btcpay.dragonmaster.pl")
.body(Body::from("{\"metadata\": {\"orderId\": \"id123\"},\"checkout\": {\"speedPolicy\": \"LowMediumSpeed\",\"redirectURL\":\"https://www.google.com\"},\"amount\": \"1.00\",\"currency\": \"PLN\"}")).unwrap(); .header("X-Forwarded-Proto", "https")
.header("Authorization", "token *****")
.body(Body::from("{\"metadata\": {\"orderId\": \"id123\"},\"checkout\": {\"speedPolicy\": \"LowMediumSpeed\",\"redirectURL\":\"https://example.com\"},\"amount\": \"".to_owned()+ &*fee.to_string() +"\",\"currency\": \"PLN\"}")).unwrap();
let resp = client.request(req).await.unwrap(); let resp = client.request(req).await.unwrap();
let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap(); let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap();
POOL.with(|poola| { POOL.with(|poola| {
let tmp: String = parsed.get("id").unwrap().as_str().unwrap().into(); let tmp: String = parsed.get("id").unwrap().as_str().unwrap().into();
let nid: String = poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`, `partner`)VALUES(?,?,'btc','PENDING',0,?,?);", (id, tournament, &tmp, partner)).unwrap().last_insert_id().unwrap().to_string(); let nid: String = poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`, `partner`)VALUES(?,?,'btc','PENDING',0,?,?);", (id, tournament, &tmp, partner)).unwrap().last_insert_id().unwrap().to_string();
let mut checkout: String = parsed.get("checkoutLink").unwrap().as_str().unwrap().into(); let mut checkout: String = parsed.get("checkoutLink").unwrap().as_str().unwrap().into();
checkout = checkout.replace("http://10.1.6.101:8082/", "https://btcpay.dragonmaster.pl/");
*response.body_mut() = Body::from("{\"id\":\"".to_owned() + &nid + "\",\"url\":\"" + &*checkout + "\"}"); *response.body_mut() = Body::from("{\"id\":\"".to_owned() + &nid + "\",\"url\":\"" + &*checkout + "\"}");
}); });
} else { } else {
@ -1529,6 +1689,40 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
if s.contains_key("currentRound") { if s.contains_key("currentRound") {
poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ? and deleted =0", (s.get("currentRound"), &tid)).unwrap(); poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ? and deleted =0", (s.get("currentRound"), &tid)).unwrap();
} }
if s.contains_key("from") {
poola.get_conn().unwrap().exec_drop("Update tournaments set `from` =? where id = ? and deleted =0", (s.get("from"), &tid)).unwrap();
}
if s.contains_key("to") {
poola.get_conn().unwrap().exec_drop("Update tournaments set `to` =? where id = ? and deleted =0", (s.get("to"), &tid)).unwrap();
}
if s.contains_key("place") {
poola.get_conn().unwrap().exec_drop("Update tournaments set place =? where id = ? and deleted =0", (s.get("place"), &tid)).unwrap();
}
if s.contains_key("categotry") {
poola.get_conn().unwrap().exec_drop("Update tournaments set categotry =? where id = ? and deleted =0", (s.get("categotry"), &tid)).unwrap();
}
if s.contains_key("rang") {
poola.get_conn().unwrap().exec_drop("Update tournaments set rang =? where id = ? and deleted =0", (s.get("rang"), &tid)).unwrap();
}
if s.contains_key("entryFee") {
poola.get_conn().unwrap().exec_drop("Update tournaments set entryFee =? where id = ? and deleted =0", (s.get("entryFee"), &tid)).unwrap();
}
if s.contains_key("director") {
poola.get_conn().unwrap().exec_drop("Update tournaments set director =? where id = ? and deleted =0", (s.get("director"), &tid)).unwrap();
}
if s.contains_key("phone") {
poola.get_conn().unwrap().exec_drop("Update tournaments set phone =? where id = ? and deleted =0", (s.get("phone"), &tid)).unwrap();
}
if s.contains_key("entriesTo") {
poola.get_conn().unwrap().exec_drop("Update tournaments set entriesTo =? where id = ? and deleted =0", (s.get("entriesTo"), &tid)).unwrap();
}
if s.contains_key("additionalInformations") {
poola.get_conn().unwrap().exec_drop("Update tournaments set additionalInformations =? where id = ? and deleted =0", (s.get("additionalInformations"), &tid)).unwrap();
}
if s.contains_key("visibility") {
poola.get_conn().unwrap().exec_drop("Update tournaments set visibility =? where id = ? and deleted =0", (s.get("visibility"), &tid)).unwrap();
}
*response.body_mut() = "{}".into(); *response.body_mut() = "{}".into();
} else { } else {
*response.body_mut() = "{\"error\":\"not all fields\"}".into(); *response.body_mut() = "{\"error\":\"not all fields\"}".into();
@ -1587,14 +1781,18 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
} }
(&Method::GET, "/tournaments") => { (&Method::GET, "/tournaments") => {
POOL.with(|poola| { POOL.with(|poola| {
let res = poola.get_conn().unwrap() let mut res = Vec::new() ;
.query_map( poola.get_conn().unwrap()
"SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved, state, currentRound from tournaments where deleted =0", .query_iter(
|(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved, state, currentRound)| { "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved, state, currentRound,`from`, `to`, place, categotry, rang, entryFee, director, phone,entriesTo, additionalInformations, visibility from tournaments where deleted =0 order by id desc",
tournament { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved, state, currentRound } ).unwrap().for_each(|row| {
}, let result_set = row.unwrap();
); res.push(tournament { id:from_value(result_set.get(0).unwrap()), name:from_value(result_set.get(1).unwrap()), typeOfLadder:from_value(result_set.get(2).unwrap()), places:from_value(result_set.get(4).unwrap()), roles:from_value(result_set.get(5).unwrap()), creator:from_value(result_set.get(6).unwrap()), pointsForTournament:from_value(result_set.get(3).unwrap()), approved:from_value(result_set.get(7).unwrap()), state:from_value(result_set.get(8).unwrap()), currentRound:from_value(result_set.get(9).unwrap()),from:from_value(result_set.get(10).unwrap()), to:from_value(result_set.get(11).unwrap()), place:from_value(result_set.get(12).unwrap()), categotry:from_value(result_set.get(13).unwrap()), rang:from_value(result_set.get(14).unwrap()), entryFee:from_value(result_set.get(15).unwrap()), director:from_value(result_set.get(16).unwrap()), phone:from_value(result_set.get(17).unwrap()),entriesTo:from_value(result_set.get(18).unwrap()), additionalInformations:from_value(result_set.get(19).unwrap()),
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); visibility:from_value( result_set.get(20).unwrap())
});
});
*response.body_mut() = serde_json::to_string(&res).unwrap().into();
}); });
} }
(&Method::PUT, "/tournament") => { (&Method::PUT, "/tournament") => {
@ -1625,7 +1823,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
*response.status_mut() = StatusCode::FORBIDDEN; *response.status_mut() = StatusCode::FORBIDDEN;
return; return;
} }
if s.contains_key("name") && s.contains_key("typeOfLadder") && s.contains_key("pointsForTournament") && s.contains_key("places") && s.contains_key("roles") && s.contains_key("ranked") { if s.contains_key("name") && s.contains_key("typeOfLadder") && s.contains_key("pointsForTournament") && s.contains_key("places") && s.contains_key("roles") && s.contains_key("ranked") && s.contains_key("from") && s.contains_key("to") && s.contains_key("place") && s.contains_key("categotry") && s.contains_key("rang") && s.contains_key("entryFee") && s.contains_key("director") && s.contains_key("phone") && s.contains_key("entriesTo")&& s.contains_key("additionalInformations") && s.contains_key("visibility"){
let name = s.get("name").unwrap().to_string(); let name = s.get("name").unwrap().to_string();
let type_of_ladder = s.get("typeOfLadder").unwrap().to_string(); let type_of_ladder = s.get("typeOfLadder").unwrap().to_string();
let points_for_tournament = s.get("pointsForTournament").unwrap().to_string(); let points_for_tournament = s.get("pointsForTournament").unwrap().to_string();
@ -1635,7 +1833,20 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
if ranked != "0" && ranked != "1" { if ranked != "0" && ranked != "1" {
ranked = String::from("0"); ranked = String::from("0");
} }
let str = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`tournaments`(`name`,`typeOfLadder`,`pointsForTournament`,`places`,`roles`,`creator`,`deleted`,`approved`,`state`,`currentRound`) VALUES (?,?,?,?,?,?,0,?,0,0);", (name, type_of_ladder, points_for_tournament, places, roles, id, ranked)).unwrap().last_insert_id().unwrap().to_string() + "}"; let from = s.get("from").unwrap().to_string();
let to = s.get("to").unwrap().to_string();
let place = s.get("place").unwrap().to_string();
let categotry = s.get("categotry").unwrap().to_string();
let rang = s.get("rang").unwrap().to_string();
let entryFee = s.get("entryFee").unwrap().to_string();
let director = s.get("director").unwrap().to_string();
let phone = s.get("phone").unwrap().to_string();
let entriesTo = s.get("entriesTo").unwrap().to_string();
let visibility = s.get("visibility").unwrap().to_string();
let additionalInformations = s.get("additionalInformations").unwrap().to_string();
let id2 = &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`tournaments`(`name`,`typeOfLadder`,`pointsForTournament`,`places`,`roles`,`creator`,`deleted`,`approved`,`state`,`currentRound`,`from`,`to`,`place`,`categotry`,`rang`,`entryFee`,`director`,`phone`,`entriesTo`,`additionalInformations`,`visibility`) VALUES (?,?,?,?,?,?,0,?,0,0,'1000-01-01 01:01:01','1000-01-01 01:01:01','','','',0,'','','1000-01-01 01:01:01','','TRUE');", (name, type_of_ladder, points_for_tournament, places, roles, id, ranked)).unwrap().last_insert_id().unwrap().to_string();
let _ = &poola.get_conn().unwrap().exec_drop("Update tournaments set `from` =?, `to`=?, `place`=?, `categotry`=?, `rang`=?, `entryFee`=?, `director`=?, `phone`=?, `entriesTo`=?, `additionalInformations`=?, `visibility`=? where id = ?;", (from,to,place,categotry,rang,entryFee,director,phone,entriesTo,additionalInformations,visibility, &id2 )).unwrap();
let str = "{\"id\":".to_owned() + id2 + "}";
*response.body_mut() = str.into(); *response.body_mut() = str.into();
} else { } else {
*response.body_mut() = "{\"error\":\"not all fields\"}".into(); *response.body_mut() = "{\"error\":\"not all fields\"}".into();
@ -1746,7 +1957,7 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
let password = s.get("password").unwrap().to_string(); let password = s.get("password").unwrap().to_string();
*response.body_mut() = POOL.with(|poola| { *response.body_mut() = POOL.with(|poola| {
let mut con = poola.get_conn().unwrap(); let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("SELECT * FROM `inz`.`users` where login = ? and `deleted`=0;", (&username, )).unwrap(); let mut result = con.exec_iter("SELECT * FROM `inz`.`users` where (login = ? or mail = ?) and `deleted`=0;", (&username, &username)).unwrap();
let mut it = result.iter().unwrap(); let mut it = result.iter().unwrap();
let row = it.next(); let row = it.next();
if !row.is_none() { if !row.is_none() {
@ -1789,15 +2000,61 @@ SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val'
} }
}; };
Ok(response) Ok(response)
} }
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let addr = SocketAddr::from(([0, 0, 0, 0], 1000)); let addr = SocketAddr::from(([0, 0, 0, 0], 1000));
let make_svc = make_service_fn(|_conn| async { let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(hello_world)) Ok::<_, Infallible>(service_fn(hello_world))
}); });
let server = Server::bind(&addr).serve(make_svc); let server = Server::bind(&addr).serve(make_svc);
tokio::spawn(async move {
loop
{
sleep(Duration::from_secs(60*5)).await;
POOL.with(|poola| {
poola.get_conn().unwrap()
.query_iter(
"Select id, paymentreference from registrations where paymentstatus = 'PENDING' and paymenttype ='btc'",
).unwrap().for_each(|row| {
tokio::spawn(async move {
let result_set = row.unwrap();
let reference: &String = &from_value(result_set.get(1).unwrap());
let id: &String = &from_value(result_set.get(0).unwrap());
let client = Client::new();
let req = Request::builder()
.method(Method::GET)
.uri("http://10.1.6.101:8082/api/v1/stores/5QsjqLbqHNgiP4GnAqy2apKaTcxWDj7zFFSpNKZGEseR/invoices/".to_owned() + reference)
.header("content-type", "application/json")
.header("Authorization", "token 8b1d0a2a653e9f40ac402dbce66fccb3ccd1b9c5").body(Body::empty()).unwrap();
let resp = client.request(req).await.unwrap();
let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap();
let stat: String = parsed.get("status").unwrap().as_str().unwrap().into();
if stat == "New" {} else {
if stat == "Settled" {
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus ='DONE' where id = ?", (id, )).unwrap();
});
} else {
if stat == "Processing" {} else {
if stat == "Expired" {
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus ='EXPIRED' where id = ?", (id, )).unwrap();
});
} else {
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus =? where id = ?", (stat, id)).unwrap();
});
}
}
}
}
});
});
});
}
});
if let Err(e) = server.await { if let Err(e) = server.await {
eprintln!("server error: {}", e); eprintln!("server error: {}", e);
} }