summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorache <ache@ache.one>2024-02-14 11:50:43 +0100
committerache <ache@ache.one>2024-02-14 11:50:43 +0100
commitf02b2de49da14ad1ebece8e6bc7cf7126f1932c7 (patch)
treec68de70f94fd0d469711b84c4ffdbdf2b22674f2 /src
parentFix avalaible articles (diff)
Support for others locales
Diffstat (limited to 'src')
-rw-r--r--src/locales/en.toml11
-rw-r--r--src/locales/fr.toml11
-rw-r--r--src/main.rs53
3 files changed, 56 insertions, 19 deletions
diff --git a/src/locales/en.toml b/src/locales/en.toml
new file mode 100644
index 0000000..0a904be
--- /dev/null
+++ b/src/locales/en.toml
@@ -0,0 +1,11 @@
+hidden_ip="Sorry, your ID is hidden."
+invalid_ip="Sorry, your IP isn't valid: "
+method_not_allowed="Method not allowed."
+bad_endpoint="The endpoint is: "
+bad_request="What did you expect ?"
+done="Done !"
+thanks="Thank you ! 💕"
+too_many_hears="Too many hearts !"
+wait_prefix="Wait"
+wait_message_suffix="before you can send another heart."
+unknow_error="There is a problem. (>﹏<)"
diff --git a/src/locales/fr.toml b/src/locales/fr.toml
new file mode 100644
index 0000000..b906cee
--- /dev/null
+++ b/src/locales/fr.toml
@@ -0,0 +1,11 @@
+hidden_ip="Désolé, votre IP est cachée."
+invalid_ip="Désolé, votre IP n'est pas valide: "
+method_not_allowed="C'est quoi ces manières ?!"
+bad_endpoint="Le point de sortie est: "
+bad_request="Tu t'attends à quoi au juste ?"
+done="Fait !"
+thanks="Merci ! 💕"
+too_many_hears="Trop de cœurs !"
+wait_prefix="Attendez"
+wait_message_suffix="avant de pouvoir envoyer un autre cœur."
+unknow_error="💕 Il y a un soucis. (>﹏<)"
diff --git a/src/main.rs b/src/main.rs
index 04da18e..d400e6e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,6 @@
+// Init translations for current crate.
+rust_i18n::i18n!("src/locales");
+
use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr, Ipv4Addr};
use std::collections::HashMap;
@@ -7,8 +10,6 @@ use std::{thread, time::Duration};
use std::sync::Arc;
use std::fs;
-
-
use serde_derive::{Serialize, Deserialize};
use toml;
@@ -17,8 +18,9 @@ use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server, StatusCode, Method, header::HeaderValue};
use rusqlite::{Connection, Transaction};
-
use blake3;
+use rust_i18n::t;
+
enum VustQuery {
Get,
@@ -48,29 +50,42 @@ fn wrap_cors(mut res: Response<Body>, config :Arc<Config>) -> Response<Body> {
}
fn handle(req: Request<Body>, addr: SocketAddr, tx: Sender<VustMessage>, config: Arc<Config>) -> Response<Body> {
- const PREFIX_PATH: &str = "/like/";
+ const PREFIX_PATH :&str = "/like/";
+ const DEFAULT_LOCALE :&str = "fr";
let path: String = req.uri().path().to_string();
+ rust_i18n::set_locale(match req.headers().contains_key("lang") {
+ true => match req.headers().get("lang") {
+ Some(h) => match h.to_str() {
+ Ok(l) => l,
+ Err(_) => DEFAULT_LOCALE,
+ },
+ None => DEFAULT_LOCALE,
+ },
+ false => DEFAULT_LOCALE,
+ });
+
+
let addr = match req.headers().contains_key("real-ip") {
false => addr,
true => {
let real_ip_str = match req.headers().get("real-ip") {
Some(ip) => ip.to_str(),
None => {
- return respond(StatusCode::SERVICE_UNAVAILABLE, "Désolé, votre IP est cachée".to_string());
+ return respond(StatusCode::SERVICE_UNAVAILABLE, t!("hidden_ip").to_string());
},
};
let real_ip_str = match real_ip_str {
Ok(addr) => addr,
- Err(_) => {
- return respond(StatusCode::SERVICE_UNAVAILABLE, format!("Désolé, votre IP nous pose problème. ({:?})", real_ip_str).to_string());
+ Err(s) => {
+ return respond(StatusCode::SERVICE_UNAVAILABLE, format!("{}: {}.", t!("invalid_ip").to_string(), s.to_string()));
}
};
let ip :IpAddr = match real_ip_str.parse() {
Ok(addr) => addr,
Err(_) => {
- return respond(StatusCode::SERVICE_UNAVAILABLE, format!("Désolé, votre IP nous pose problème. ({:?})", real_ip_str).to_string());
+ return respond(StatusCode::SERVICE_UNAVAILABLE, format!("{} {}.", t!("invalid_ip").to_string(), real_ip_str));
}
};
SocketAddr::new(ip, 0)
@@ -85,18 +100,18 @@ fn handle(req: Request<Body>, addr: SocketAddr, tx: Sender<VustMessage>, config:
return respond(StatusCode::OK, "WHAT ?".to_string());
},
_ => {
- return respond(StatusCode::METHOD_NOT_ALLOWED, "C'est quoi ces manières ?".to_string());
+ return respond(StatusCode::METHOD_NOT_ALLOWED, t!("method_not_allowed").to_string());
},
};
if !path.starts_with(PREFIX_PATH) {
- return respond(StatusCode::BAD_REQUEST, format!("Le point d'entrée est {}", PREFIX_PATH).to_string());
+ return respond(StatusCode::BAD_REQUEST, format!("{} {}.", t!("bad_endpoint"), PREFIX_PATH));
}
let path : String = path.chars().skip(PREFIX_PATH.len()).collect();
if path.contains("/") || path.len() > 128 || path.len() == 0 || !config.list_articles.contains(&path) {
- return respond(StatusCode::BAD_REQUEST, "Tu t'attends à quoi au juste ?".to_string());
+ return respond(StatusCode::BAD_REQUEST, t!("bad_request").to_string());
}
let article_key_db = if config.aliases.contains_key(&path) {
@@ -116,7 +131,7 @@ fn handle(req: Request<Body>, addr: SocketAddr, tx: Sender<VustMessage>, config:
tx.send(message).unwrap();
match *req.method() {
- Method::PUT => respond(StatusCode::OK, "Fait !".to_string()),
+ Method::PUT => respond(StatusCode::OK, t!("done").to_string()),
_ => rx.recv().unwrap(),
}
}
@@ -171,11 +186,11 @@ fn do_like(tr: &Transaction, ip : SocketAddr, path : String) -> Response<Body> {
Ok(None) => {
let res = tr.execute("INSERT OR IGNORE INTO likes VALUES (?, ?, unixepoch(), 1)", [hash_ip.as_str(), path.as_str()]);
if res.is_err() {
- println!("Error doing the request {:?}", res.err());
+ eprintln!("Error doing the request {:?}", res.err());
continue;
}
- return respond(StatusCode::OK, "Merci ! 💕".to_string())
+ return respond(StatusCode::OK, t!("thanks").to_string())
},
Ok(Some(t)) => {
let number : u64 = t.get(0).unwrap();
@@ -183,7 +198,7 @@ fn do_like(tr: &Transaction, ip : SocketAddr, path : String) -> Response<Body> {
let now : u64= t.get(2).unwrap();
if number > 31 {
- return respond(StatusCode::RANGE_NOT_SATISFIABLE, format!("Trop de cœurs ! 💕 x ({})", number).to_string());
+ return respond(StatusCode::RANGE_NOT_SATISFIABLE, format!("{} 💕 x ({})", t!("too_many_hears"), number).to_string());
}
let limite = (1 << number) / 10; // 2^likes / Cst
@@ -191,17 +206,17 @@ fn do_like(tr: &Transaction, ip : SocketAddr, path : String) -> Response<Body> {
if dtime < limite {
let time_remaining = limite - dtime;
- return respond(StatusCode::TOO_MANY_REQUESTS, format!("Attendez {}s avant de pouvoir envoyer un autre cœur.", time_remaining));
+ return respond(StatusCode::TOO_MANY_REQUESTS, format!("{} {}s {}", time_remaining, t!("wait_prefix"), t!("wait_message_suffix")));
}
let res = tr.execute("UPDATE likes SET number = number + 1, lastMod = unixepoch() WHERE ip_hash = ? and path = ?", [hash_ip.as_str(), path.as_str()]);
if res.is_err() {
- println!("Error doing the request {:?}", res.err());
+ eprintln!("Error doing the request {:?}", res.err());
continue
}
- return respond(StatusCode::OK, format!("Merci ! 💕 x {}", number + 1).to_string())
+ return respond(StatusCode::OK, format!("{} 💕 x {}", t!("thanks") , number + 1).to_string())
},
Err(_) => {
continue
@@ -209,7 +224,7 @@ fn do_like(tr: &Transaction, ip : SocketAddr, path : String) -> Response<Body> {
};
}
- respond(StatusCode::INTERNAL_SERVER_ERROR, "💕 Erreur, il y a un soucis. (>﹏<)".to_string())
+ respond(StatusCode::INTERNAL_SERVER_ERROR, t!("unknow_error").to_string())
}
#[derive(Serialize, Deserialize)]