Signed-off-by: Tomasz Sidoruk <tomsid@st.amu.edu.pl>
This commit is contained in:
Tomasz Sidoruk 2022-10-19 22:40:13 +02:00
parent 752055b95f
commit 458792a3fa
2 changed files with 2320 additions and 1920 deletions

View File

@ -14,4 +14,4 @@ serde = "*"
serde_derive = "*"
bcrypt = "0.12"
rand = "0.3.0"
lettre = "0.10.1"

View File

@ -1,3 +1,5 @@
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};
use std::collections::HashMap;
use serde_derive::{Serialize, Deserialize};
use mysql::*;
@ -9,7 +11,6 @@
use bcrypt::{DEFAULT_COST, hash, verify};
use rand::{OsRng, Rng};
use serde_json::Map;
use std::thread;
use std::time::Duration;
use tokio::time::sleep;
@ -29,6 +30,13 @@
score: String,
}
#[derive(Serialize, Deserialize)]
struct pendingApprovals {
id: i32,
inviter: i32,
tournamnet: String,
}
#[derive(Serialize, Deserialize)]
struct User {
id: i32,
@ -67,8 +75,10 @@
tournamentid: String,
paymenttype: String,
paymentstatus: String,
paymenttype2: String,
paymentstatus2: String,
approval: String,
partner: i32
partner: i32,
}
#[derive(Serialize, Deserialize)]
@ -135,9 +145,12 @@
visibility: String,
}
thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://inz:****!@*****:3306/inz").unwrap()).unwrap());
thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://*****").unwrap()).unwrap());
async fn hello_world(req: Request<Body>) -> Result<Response<Body>> {
let smtp_server = "****";
let smtp_username = "****";
let smtp_password = "****";
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());
@ -166,7 +179,6 @@
);
*response.body_mut() = serde_json::to_string(&res.unwrap().get(0)).unwrap().into();
});
}
(&Method::GET, "/proposals/pending") => {
if req.headers().contains_key("Authorization") {
@ -643,7 +655,7 @@
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 result = con.exec_iter("Select id from registrations where id= ? and informed = 1 and tournamentid =?", (&s.get("inB"), &tournamentid)).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
@ -673,7 +685,7 @@
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 result = con.exec_iter("Select id from registrations where id= ? and informed = 1 and tournamentid=?", (&s.get("inA"), &tournamentid)).unwrap();
let mut it = result.iter().unwrap();
row4 = it.next();
});
@ -978,17 +990,93 @@
let role: String = urow.get(1).unwrap();
if role == "2" {
let mut conn1 = poola.get_conn().unwrap();
let mut result1 = conn1.exec_iter("Select userid from registrations where id = ?", (&s.get("id"), )).unwrap();
let mut result1 = conn1.exec_iter("Select userid,approval,partnerAcceptance,(Select mail from users where users.id = userid),(Select mail from users where users.id = partner) from registrations where id = ?", (&s.get("id"), )).unwrap();
let mut it1 = result1.iter().unwrap();
let row1 = it1.next();
let urow1 = row1.unwrap().unwrap();
let userid: i32 = urow1.get(0).unwrap();
let approval: String = urow1.get(1).unwrap();
let partnerAcceptance: i32 = urow1.get(2).unwrap();
let usermail: String = urow1.get(3).unwrap();
let partnermail: String = urow1.get(4).unwrap();
if userid != id {
return;
}
if approval == "0" && partnerAcceptance == 1 {
poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap();
let email = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&usermail+">").parse().unwrap())
.subject("your registration has been accepted")
.body(String::from("now is time to pay <put your url here>")+s.get("id").unwrap())
.unwrap();
let creds = Credentials::new(smtp_username.to_string(), smtp_password.to_string());
let mailer = SmtpTransport::relay(smtp_server)
.unwrap()
.credentials(creds)
.build();
match mailer.send(&email) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
let email2 = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&partnermail+">").parse().unwrap())
.subject("your registration has been accepted")
.body(String::from("now is time to pay <put your url here>")+s.get("id").unwrap())
.unwrap();
match mailer.send(&email2) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
}
} else {
let mut conn1 = poola.get_conn().unwrap();
let mut result1 = conn1.exec_iter("Select userid,approval,partnerAcceptance,(Select mail from users where users.id = userid),(Select mail from users where users.id = partner) from registrations where id = ?", (&s.get("id"), )).unwrap();
let mut it1 = result1.iter().unwrap();
let row1 = it1.next();
let urow1 = row1.unwrap().unwrap();
let userid: i32 = urow1.get(0).unwrap();
let approval: String = urow1.get(1).unwrap();
let partnerAcceptance: i32 = urow1.get(2).unwrap();
let usermail: String = urow1.get(3).unwrap();
let partnermail: String = urow1.get(4).unwrap();
if approval == "0" && partnerAcceptance == 1 {
poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap();
let email = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&usermail+">").parse().unwrap())
.subject("your registration has been accepted")
.body(String::from("now is time to pay <put your url here>")+s.get("id").unwrap())
.unwrap();
let creds = Credentials::new(smtp_username.to_string(), smtp_password.to_string());
let mailer = SmtpTransport::relay(smtp_server)
.unwrap()
.credentials(creds)
.build();
match mailer.send(&email) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
let email2 = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&partnermail+">").parse().unwrap())
.subject("your registration has been accepted")
.body(String::from("now is time to pay <put your url here>")+s.get("id").unwrap())
.unwrap();
match mailer.send(&email2) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
}
}
});
} else {
@ -1029,9 +1117,9 @@
if role == "1" {
let res = poola.get_conn().unwrap()
.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),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`paymenttype2`,`registrations`.`paymentstatus2`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner =?);", (&val, id, id),
|(id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner }
},
);
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into();
@ -1046,9 +1134,9 @@
if userid != id {
let res = poola.get_conn().unwrap()
.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),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`paymenttype2`,`registrations`.`paymentstatus2`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner =?);", (&val, id, id),
|(id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner }
},
);
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into();
@ -1058,18 +1146,18 @@
let res = poola.get_conn().unwrap()
.exec_map(
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`paymenttype2`,`registrations`.`paymentstatus2`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ),
|(id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner }
},
);
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into();
} else {
let res = poola.get_conn().unwrap()
.exec_map(
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval` ,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ),
|(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner }
"SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`paymenttype2`,`registrations`.`paymentstatus2`,`registrations`.`approval` ,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ),
|(id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner)| {
Registration { id, userid, tournamentid, paymenttype, paymentstatus,paymenttype2, paymentstatus2, approval, partner }
},
);
*response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into();
@ -1481,7 +1569,7 @@
return;
}
let mut con2 = poola.get_conn().unwrap();
let mut result2 = con2.exec_iter("Select paymentstatus, paymentreference, userid, paymenttype from registrations where id =?;", (&val, )).unwrap();
let mut result2 = con2.exec_iter("Select paymentstatus, paymentreference, userid, paymenttype, paymentstatus2, paymentreference2, paymenttype2, partner from registrations where id =?;", (&val, )).unwrap();
let mut it2 = result2.iter().unwrap();
row2 = it2.next();
});
@ -1497,42 +1585,47 @@
let paymentreference: String = urow2.get(1).unwrap();
let userid: i32 = urow2.get(2).unwrap();
let paymenttype: String = urow2.get(3).unwrap();
let paymentstatus2: String = urow2.get(4).unwrap();
let paymentreference2: String = urow2.get(5).unwrap();
let paymenttype2: String = urow2.get(6).unwrap();
let partner: i32 = urow2.get(7).unwrap();
if role == "1" || role == "2" {
if userid != id {
if userid != id && partner != id {
*response.status_mut() = StatusCode::NOT_FOUND;
return Ok(response);
}
}
let mut respb= String::from("");
if paymentstatus == "PENDING" && paymenttype != "cash" {
if paymenttype == "btc" {
let client = Client::new();
let req = Request::builder()
.method(Method::GET)
.uri("http://10.1.6.101:8082/api/v1/stores/****/invoices/".to_owned() + &paymentreference)
.uri("http://****/api/v1/stores/****/invoices/".to_owned() + &paymentreference)
.header("content-type", "application/json")
.header("Authorization", "token *****").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" {
*response.body_mut() = Body::from("{\"status\":\"PENDING\"}");
respb = "{\"status\":\"PENDING\"".to_string();
} else {
if stat == "Settled" {
*response.body_mut() = Body::from("{\"status\":\"DONE\"}");
respb ="{\"status\":\"DONE\"".to_string();
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus ='DONE' where id = ?", (val, )).unwrap();
});
} else {
if stat == "Processing" {
*response.body_mut() = Body::from("{\"status\":\"PROCESSING\"}");
respb="{\"status\":\"PROCESSING\"".to_string();
} else {
if stat == "Expired" {
*response.body_mut() = Body::from("{\"status\":\"EXPIRED\"}");
respb="{\"status\":\"EXPIRED\"".to_string();
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus ='EXPIRED' where id = ?", (val, )).unwrap();
});
} else {
*response.body_mut() = Body::from("{\"status\":\"".to_owned() + &stat + "\"}");
respb="{\"status\":\"".to_owned() + &stat + "\"";
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus =? where id = ?", (stat, val)).unwrap();
});
@ -1542,8 +1635,51 @@
}
}
} else {
*response.body_mut() = Body::from("{\"status\":\"".to_owned() + &paymentstatus + "\"}");
respb="{\"status\":\"".to_owned() + &paymentstatus + "\"";
}
if paymentstatus2 == "PENDING" && paymenttype2 != "cash" {
if paymenttype2 == "btc" {
let client = Client::new();
let req = Request::builder()
.method(Method::GET)
.uri("http://****/api/v1/stores/****/invoices/".to_owned() + &paymentreference2)
.header("content-type", "application/json")
.header("Authorization", "token ****").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" {
respb += ",\"status2\":\"PENDING\"}";
} else {
if stat == "Settled" {
respb +=",\"status2\":\"DONE\"}";
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus2 ='DONE' where id = ?", (val, )).unwrap();
});
} else {
if stat == "Processing" {
respb+=",\"status2\":\"PROCESSING\"}";
} else {
if stat == "Expired" {
respb+=",\"status2\":\"EXPIRED\"}";
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus2 ='EXPIRED' where id = ?", (val, )).unwrap();
});
} else {
respb+= &*(",\"status2\":\"".to_owned() + &stat + "\"}");
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus2 =? where id = ?", (stat, val)).unwrap();
});
}
}
}
}
}
} else {
respb+= &*(",\"status2\":\"".to_owned() + &paymentstatus + "\"}");
}
*response.body_mut() = respb.into();
} else {
*response.status_mut() = StatusCode::UNAUTHORIZED;
}
@ -1562,7 +1698,7 @@
let mut row: 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("partner") {
let tournament = s.get("tournament").unwrap().to_string();
let partner = s.get("partner").unwrap().to_string();
@ -1598,38 +1734,200 @@
let urow = row.unwrap().unwrap();
let urow2 = row2.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap();
let fee: i32 = urow2.get(1).unwrap();
POOL.with(|poola| {
let nid = "{\"id\":\"".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`,`partner`,`partnerAcceptance`,`paymenttype2`,`paymentstatus2`,`paymentreference2`,`informed`)VALUES(?,?,'','NOTSTARTED',0,'',?,0,'','NOTSTARTED','',0);", (id, tournament, partner)).unwrap().last_insert_id().unwrap().to_string() + "\"}";
*response.body_mut() = nid.into();
});
} else {
*response.body_mut() = "{\"error\":\"not all fields\"}".into();
}
} else {
*response.status_mut() = StatusCode::UNAUTHORIZED;
}
}
(&Method::POST, "/payForRegistration") => {
if req.headers().contains_key("Authorization") {
let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" ");
let aa = tmp.next().unwrap().to_string();
let token = tmp.next().unwrap().to_string();
let byte_stream = hyper::body::to_bytes(req).await.unwrap();
let s: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
if !s.contains_key("id")||!s.contains_key("paymentmethod") {
*response.body_mut() = "id and paymentmethod is required".into();
}else {
let paymentmethod = s.get("paymentmethod").unwrap().to_string();
let rid = s.get("id").unwrap().to_string();
let mut isowner = false;
let mut isinvited = false;
let mut fee = -1;
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
if aa != "Bearer" {
*response.status_mut() = StatusCode::UNAUTHORIZED;
return;
}
let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap();
let mut it = result.iter().unwrap();
let row = it.next();
if row.is_none() {
*response.status_mut() = StatusCode::FORBIDDEN;
return;
}
let uid: i32 = row.unwrap().unwrap().get(0).unwrap();
let mut con2 = poola.get_conn().unwrap();
let mut result2 = con2.exec_iter("SELECT id FROM inz.registrations where userid=? and id = ? and approval =1", (&uid, &rid)).unwrap();
let mut it2 = result2.iter().unwrap();
let row2 = it2.next();
if !row2.is_none() {
isowner = true;
}
let mut con3 = poola.get_conn().unwrap();
let mut result3 = con3.exec_iter("SELECT id FROM inz.registrations where partner=? and id = ? and approval =1", (&uid, &rid)).unwrap();
let mut it3 = result3.iter().unwrap();
let row3 = it3.next();
if !row3.is_none() {
isinvited = true;
}
if isowner == false && isinvited == false {
*response.status_mut() = StatusCode::BAD_REQUEST;
return;
}
let mut conn4 = poola.get_conn().unwrap();
let mut result4 = conn4.exec_iter("SELECT entryFee FROM inz.tournaments where id = (SELECT tournamentid FROM inz.registrations where id = ?)", (&rid, )).unwrap();
let mut it4 = result4.iter().unwrap();
let row4 = it4.next();
fee = row4.unwrap().unwrap().get(0).unwrap();
});
if paymentmethod == "btc" {
let client = Client::new();
let req = Request::builder()
.method(Method::POST)
.uri("http://10.1.6.101:8082/api/v1/stores/*****/invoices")
.uri("http://****/api/v1/stores/*****/invoices")
.header("content-type", "application/json")
.header("X-Forwarded-Host", "btcpay.dragonmaster.pl")
.header("X-Forwarded-Proto", "https")
.header("Authorization", "token *****")
.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 parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap();
POOL.with(|poola| {
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();
if isowner {
poola.get_conn().unwrap().exec_iter("Update registrations set paymenttype = 'btc',paymentstatus = 'PENDING', paymentreference=? where id = ? ;", (&tmp, rid)).unwrap();
} else {
poola.get_conn().unwrap().exec_iter("Update registrations set paymenttype2 = 'btc',paymentstatus2 = 'PENDING',paymentreference2=? where id = ? ;", (&tmp, rid)).unwrap();
}
let mut checkout: String = parsed.get("checkoutLink").unwrap().as_str().unwrap().into();
*response.body_mut() = Body::from("{\"id\":\"".to_owned() + &nid + "\",\"url\":\"" + &*checkout + "\"}");
//checkout = checkout.replace("http://10.1.6.101:8082/", "https://btcpay.dragonmaster.pl/");
*response.body_mut() = Body::from("{\"url\":\"".to_owned() + &*checkout + "\"}");
});
} else {
if paymentmethod == "cash" {
POOL.with(|poola| {
let nid = "{\"id\":\"".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`, `partner`)VALUES(?,?,'cash','PENDING',0,'N/A',?);", (id, tournament, partner)).unwrap().last_insert_id().unwrap().to_string() + "\"}";
*response.body_mut() = nid.into();
if isowner {
poola.get_conn().unwrap().exec_iter("Update registrations set paymenttype = 'cash',paymentstatus = 'PENDING', paymentreference='N/A' where id = ? ;", (rid, )).unwrap();
} else {
poola.get_conn().unwrap().exec_iter("Update registrations set paymenttype2 = 'cash',paymentstatus2 = 'PENDING',paymentreference2='N/A' where id = ? ;", (rid, )).unwrap();
}
*response.body_mut() = "{}".into();
});
} else {
*response.body_mut() = "{\"error\":\"bad payment method\"}".into();
}
}
}
} else {
*response.body_mut() = "{\"error\":\"not all fields\"}".into();
*response.status_mut() = StatusCode::UNAUTHORIZED;
}
}
(&Method::GET, "/pendingApprovals") => {
if req.headers().contains_key("Authorization") {
let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" ");
let aa = tmp.next().unwrap();
if aa != "Bearer" {
*response.status_mut() = StatusCode::UNAUTHORIZED;
return Ok(response);
}
let token = tmp.next().unwrap().to_string();
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW();", (&token, )).unwrap();
let mut it = result.iter().unwrap();
let row = it.next();
let urow = row.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap();
let mut res = Vec::new();
poola.get_conn().unwrap()
.exec_iter(
"SELECT id, userid, tournamentid from registrations where partner =? and partnerAcceptance = 0", (id, ),
).unwrap().for_each(|row| {
let result_set = row.unwrap();
res.push(pendingApprovals { id: from_value(result_set.get(0).unwrap()), inviter: from_value(result_set.get(1).unwrap()), tournamnet: from_value(result_set.get(2).unwrap()) });
});
*response.body_mut() = serde_json::to_string(&res).unwrap().into();
});
} else {
*response.status_mut() = StatusCode::UNAUTHORIZED;
}
}
(&Method::POST, "/acceptInvite") => {
if req.headers().contains_key("Authorization") {
let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" ");
let aa = tmp.next().unwrap();
if aa != "Bearer" {
*response.status_mut() = StatusCode::UNAUTHORIZED;
return Ok(response);
}
let token = tmp.next().unwrap().to_string();
let byte_stream = hyper::body::to_bytes(req).await.unwrap();
let s: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
if(s.contains_key("id")) {
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW();", (&token, )).unwrap();
let mut it = result.iter().unwrap();
let row = it.next();
let urow = row.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap();
poola.get_conn().unwrap().exec_drop("Update registrations set partnerAcceptance =1 where partner = ? and id = ?", (id, s.get("id").unwrap().to_string())).unwrap();
*response.body_mut() = "{}".into();
});
}else{
*response.body_mut() = "id is required".into();
}
} else {
*response.status_mut() = StatusCode::UNAUTHORIZED;
}
}
(&Method::POST, "/rejectInvite") => {
if req.headers().contains_key("Authorization") {
let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" ");
let aa = tmp.next().unwrap();
if aa != "Bearer" {
*response.status_mut() = StatusCode::UNAUTHORIZED;
return Ok(response);
}
let token = tmp.next().unwrap().to_string();
let byte_stream = hyper::body::to_bytes(req).await.unwrap();
let s: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
if(s.contains_key("id")) {
POOL.with(|poola| {
let mut con = poola.get_conn().unwrap();
let mut result = con.exec_iter("SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW();", (&token, )).unwrap();
let mut it = result.iter().unwrap();
let row = it.next();
let urow = row.unwrap().unwrap();
let id: i32 = urow.get(0).unwrap();
poola.get_conn().unwrap().exec_drop("delete from registrations where partner = ? and id = ?", (id, s.get("id").unwrap().to_string())).unwrap();
*response.body_mut() = "{}".into();
});
}else{
*response.body_mut() = "id is required".into();
}
} else {
*response.status_mut() = StatusCode::UNAUTHORIZED;
@ -1787,8 +2085,28 @@
"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",
).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()),
visibility:from_value( result_set.get(20).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()),
visibility: from_value(result_set.get(20).unwrap()),
});
});
@ -1844,8 +2162,11 @@
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 mut tr = poola.start_transaction(TxOpts::default()).unwrap();
let id2 = &tr.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 _ = &tr.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();
tr.commit().unwrap();
let str = "{\"id\":".to_owned() + id2 + "}";
*response.body_mut() = str.into();
} else {
@ -2012,22 +2333,26 @@
tokio::spawn(async move {
loop
{
sleep(Duration::from_secs(60*5)).await;
sleep(Duration::from_secs(60 * 15)).await;
POOL.with(|poola| {
poola.get_conn().unwrap()
.query_iter(
"Select id, paymentreference from registrations where paymentstatus = 'PENDING' and paymenttype ='btc'",
let mut conn = poola.get_conn().unwrap();
conn.query_iter(
"Select id, paymentreference, paymentstatus ,paymentreference2 ,paymentstatus2 from registrations where (paymentstatus = 'PENDING' or paymentstatus2 = '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 status: &String = &from_value(result_set.get(2).unwrap());
let reference2: &String = &from_value(result_set.get(3).unwrap());
let status2: &String = &from_value(result_set.get(4).unwrap());
let id: &String = &from_value(result_set.get(0).unwrap());
if status == "PENDING" {
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)
.uri("http://****/api/v1/stores/****/invoices/".to_owned() + reference)
.header("content-type", "application/json")
.header("Authorization", "token 8b1d0a2a653e9f40ac402dbce66fccb3ccd1b9c5").body(Body::empty()).unwrap();
.header("Authorization", "token *****").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();
@ -2050,7 +2375,82 @@
}
}
}
}
if status2 == "PENDING" {
let client = Client::new();
let req = Request::builder()
.method(Method::GET)
.uri("http://*****/api/v1/stores/****/invoices/".to_owned() + reference2)
.header("content-type", "application/json")
.header("Authorization", "token ****").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 paymentstatus2 ='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 paymentstatus2 ='EXPIRED' where id = ?", (id, )).unwrap();
});
} else {
POOL.with(|poola| {
poola.get_conn().unwrap().exec_drop("Update registrations set paymentstatus2 =? where id = ?", (stat, id)).unwrap();
});
}
}
}
}
}
});
});
let smtp_server = "****";
let smtp_username = "****";
let smtp_password = "****";
let smtp_password = "****";
let mut conn2 = poola.get_conn().unwrap();
conn2.query_iter(
"Select id, (Select mail from users where users.id = userid),(Select mail from users where users.id = partner) from registrations where paymentstatus = 'DONE' and paymentstatus2 = 'DONE' and informed = 1",
).unwrap().for_each(|row| {
let result_set = row.unwrap();
let id: &String = &from_value(result_set.get(0).unwrap());
let usermail: &String = &from_value(result_set.get(1).unwrap());
let partnermail: &String = &from_value(result_set.get(2).unwrap());
let email = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&usermail+">").parse().unwrap())
.subject("your registration has payed")
.body(String::from("thank you"))
.unwrap();
let creds = Credentials::new(smtp_username.to_string(), smtp_password.to_string());
let mailer = SmtpTransport::relay(smtp_server)
.unwrap()
.credentials(creds)
.build();
match mailer.send(&email) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
let email2 = Message::builder()
.from(("NoBody <".to_owned()+smtp_username+">").parse().unwrap())
.to(("Yuin <".to_owned()+&partnermail+">").parse().unwrap())
.subject("your registration has payed")
.body(String::from("thank you"))
.unwrap();
match mailer.send(&email2) {
Ok(_) => { },
Err(e) => panic!("Could not send email: {:?}", e),
_ => {}
}
let mut conn3 = poola.get_conn().unwrap();
conn3.exec_drop("Update registrations set informed =1 where id = ?", (id,)).unwrap();
});
});
}