formatting

This commit is contained in:
cupcakearmy 2022-03-12 14:07:33 +01:00
parent 44f43dbc2c
commit 19022e7cb5
No known key found for this signature in database
GPG Key ID: 3235314B4D31232F
8 changed files with 143 additions and 143 deletions

View File

@ -4,9 +4,9 @@ use crate::note;
use crate::status; use crate::status;
pub fn init(cfg: &mut web::ServiceConfig) { pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service( cfg.service(
web::scope("/api") web::scope("/api")
.service(note::init()) .service(note::init())
.service(status::init()), .service(status::init()),
); );
} }

View File

@ -2,13 +2,13 @@ use actix_files::{Files, NamedFile};
use actix_web::{web, Result}; use actix_web::{web, Result};
pub fn init(cfg: &mut web::ServiceConfig) { pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service( cfg.service(
Files::new("/", "./frontend/build") Files::new("/", "./frontend/build")
.index_file("index.html") .index_file("index.html")
.use_etag(true), .use_etag(true),
); );
} }
pub async fn index() -> Result<NamedFile> { pub async fn index() -> Result<NamedFile> {
Ok(NamedFile::open("./frontend/build/index.html")?) Ok(NamedFile::open("./frontend/build/index.html")?)
} }

View File

@ -4,10 +4,10 @@ use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct Note { pub struct Note {
pub meta: String, pub meta: String,
pub contents: String, pub contents: String,
pub views: Option<u32>, pub views: Option<u32>,
pub expiration: Option<u32>, pub expiration: Option<u32>,
} }
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
@ -15,13 +15,13 @@ pub struct NoteInfo {}
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct NotePublic { pub struct NotePublic {
pub meta: String, pub meta: String,
pub contents: String, pub contents: String,
} }
pub fn generate_id() -> String { pub fn generate_id() -> String {
let mut id: [u8; 32] = [0; 32]; let mut id: [u8; 32] = [0; 32];
let sr = ring::rand::SystemRandom::new(); let sr = ring::rand::SystemRandom::new();
let _ = sr.fill(&mut id); let _ = sr.fill(&mut id);
return bs62::encode_data(&id); return bs62::encode_data(&id);
} }

View File

@ -7,118 +7,118 @@ use crate::note::{generate_id, Note, NoteInfo, NotePublic};
use crate::store; use crate::store;
pub fn now() -> u32 { pub fn now() -> u32 {
SystemTime::now() SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH) .duration_since(SystemTime::UNIX_EPOCH)
.unwrap() .unwrap()
.as_secs() as u32 .as_secs() as u32
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct NotePath { struct NotePath {
id: String, id: String,
} }
#[get("/{id}")] #[get("/{id}")]
async fn one(path: web::Path<NotePath>) -> impl Responder { async fn one(path: web::Path<NotePath>) -> impl Responder {
let p = path.into_inner(); let p = path.into_inner();
let note = store::get(&p.id); let note = store::get(&p.id);
match note { match note {
None => return HttpResponse::NotFound().finish(), None => return HttpResponse::NotFound().finish(),
Some(_) => return HttpResponse::Ok().json(NoteInfo {}), Some(_) => return HttpResponse::Ok().json(NoteInfo {}),
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct CreateResponse { struct CreateResponse {
id: String, id: String,
} }
#[post("/")] #[post("/")]
async fn create(note: web::Json<Note>) -> impl Responder { async fn create(note: web::Json<Note>) -> impl Responder {
let mut n = note.into_inner(); let mut n = note.into_inner();
let id = generate_id(); let id = generate_id();
let bad_req = HttpResponse::BadRequest().finish(); let bad_req = HttpResponse::BadRequest().finish();
if n.views == None && n.expiration == None { if n.views == None && n.expiration == None {
return bad_req;
}
if !*config::ALLOW_ADVANCED {
n.views = Some(1);
n.expiration = None;
}
match n.views {
Some(v) => {
if v > *config::MAX_VIEWS {
return bad_req; return bad_req;
}
n.expiration = None; // views overrides expiration
} }
_ => {} if !*config::ALLOW_ADVANCED {
} n.views = Some(1);
match n.expiration { n.expiration = None;
Some(e) => {
if e > *config::MAX_EXPIRATION {
return bad_req;
}
let expiration = now() + (e * 60);
n.expiration = Some(expiration);
} }
_ => {} match n.views {
} Some(v) => {
store::set(&id.clone(), &n.clone()); if v > *config::MAX_VIEWS {
return HttpResponse::Ok().json(CreateResponse { id: id }); return bad_req;
}
n.expiration = None; // views overrides expiration
}
_ => {}
}
match n.expiration {
Some(e) => {
if e > *config::MAX_EXPIRATION {
return bad_req;
}
let expiration = now() + (e * 60);
n.expiration = Some(expiration);
}
_ => {}
}
store::set(&id.clone(), &n.clone());
return HttpResponse::Ok().json(CreateResponse { id: id });
} }
#[delete("/{id}")] #[delete("/{id}")]
async fn delete(path: web::Path<NotePath>) -> impl Responder { async fn delete(path: web::Path<NotePath>) -> impl Responder {
let p = path.into_inner(); let p = path.into_inner();
let note = store::get(&p.id); let note = store::get(&p.id);
match note { match note {
None => return HttpResponse::NotFound().finish(), None => return HttpResponse::NotFound().finish(),
Some(note) => { Some(note) => {
let mut changed = note.clone(); let mut changed = note.clone();
if changed.views == None && changed.expiration == None { if changed.views == None && changed.expiration == None {
return HttpResponse::BadRequest().finish(); return HttpResponse::BadRequest().finish();
} }
match changed.views { match changed.views {
Some(v) => { Some(v) => {
changed.views = Some(v - 1); changed.views = Some(v - 1);
let id = p.id.clone(); let id = p.id.clone();
if v <= 1 { if v <= 1 {
store::del(&id); store::del(&id);
} else { } else {
store::set(&id, &changed.clone()); store::set(&id, &changed.clone());
} }
} }
_ => {} _ => {}
} }
let n = now(); let n = now();
match changed.expiration { match changed.expiration {
Some(e) => { Some(e) => {
if e < n { if e < n {
store::del(&p.id.clone()); store::del(&p.id.clone());
return HttpResponse::BadRequest().finish(); return HttpResponse::BadRequest().finish();
} }
}
_ => {}
}
return HttpResponse::Ok().json(NotePublic {
contents: changed.contents,
meta: changed.meta,
});
} }
_ => {}
}
return HttpResponse::Ok().json(NotePublic {
contents: changed.contents,
meta: changed.meta,
});
} }
}
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Status { struct Status {
version: String, version: String,
max_size: usize, max_size: usize,
} }
pub fn init() -> Scope { pub fn init() -> Scope {
web::scope("/notes") web::scope("/notes")
.service(one) .service(one)
.service(create) .service(create)
.service(delete) .service(delete)
} }

View File

@ -3,16 +3,16 @@ use byte_unit::Byte;
use mime; use mime;
lazy_static! { lazy_static! {
pub static ref LIMIT: usize = pub static ref LIMIT: usize =
Byte::from_str(std::env::var("SIZE_LIMIT").unwrap_or("1 KiB".to_string())) Byte::from_str(std::env::var("SIZE_LIMIT").unwrap_or("1 KiB".to_string()))
.unwrap() .unwrap()
.get_bytes() as usize; .get_bytes() as usize;
} }
pub fn init(cfg: &mut web::ServiceConfig) { pub fn init(cfg: &mut web::ServiceConfig) {
let json = web::JsonConfig::default().limit(*LIMIT); let json = web::JsonConfig::default().limit(*LIMIT);
let plain = web::PayloadConfig::default() let plain = web::PayloadConfig::default()
.limit(*LIMIT) .limit(*LIMIT)
.mimetype(mime::STAR_STAR); .mimetype(mime::STAR_STAR);
cfg.app_data(json).app_data(plain); cfg.app_data(json).app_data(plain);
} }

View File

@ -2,9 +2,9 @@ use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct Status { pub struct Status {
pub version: String, pub version: String,
pub max_size: u32, pub max_size: u32,
pub max_views: u32, pub max_views: u32,
pub max_expiration: u32, pub max_expiration: u32,
pub allow_advanced: bool, pub allow_advanced: bool,
} }

View File

@ -5,15 +5,15 @@ use crate::status::Status;
#[get("/")] #[get("/")]
async fn get_status() -> impl Responder { async fn get_status() -> impl Responder {
return HttpResponse::Ok().json(Status { return HttpResponse::Ok().json(Status {
version: config::VERSION.to_string(), version: config::VERSION.to_string(),
max_size: *config::LIMIT, max_size: *config::LIMIT,
max_views: *config::MAX_VIEWS, max_views: *config::MAX_VIEWS,
max_expiration: *config::MAX_EXPIRATION, max_expiration: *config::MAX_EXPIRATION,
allow_advanced: *config::ALLOW_ADVANCED, allow_advanced: *config::ALLOW_ADVANCED,
}); });
} }
pub fn init() -> Scope { pub fn init() -> Scope {
web::scope("/status").service(get_status) web::scope("/status").service(get_status)
} }

View File

@ -4,33 +4,33 @@ use crate::note::now;
use crate::note::Note; use crate::note::Note;
lazy_static! { lazy_static! {
static ref CLIENT: memcache::Client = memcache::connect(format!( static ref CLIENT: memcache::Client = memcache::connect(format!(
"memcache://{}?timeout=10&tcp_nodelay=true", "memcache://{}?timeout=10&tcp_nodelay=true",
std::env::var("MEMCACHE").unwrap_or("127.0.0.1:11211".to_string()) std::env::var("MEMCACHE").unwrap_or("127.0.0.1:11211".to_string())
)) ))
.unwrap(); .unwrap();
} }
pub fn set(id: &String, note: &Note) { pub fn set(id: &String, note: &Note) {
let serialized = serde_json::to_string(&note.clone()).unwrap(); let serialized = serde_json::to_string(&note.clone()).unwrap();
let expiration: u32 = match note.expiration { let expiration: u32 = match note.expiration {
Some(e) => e - now(), Some(e) => e - now(),
None => 0, None => 0,
}; };
CLIENT.set(id, serialized, expiration).unwrap(); CLIENT.set(id, serialized, expiration).unwrap();
} }
pub fn get(id: &String) -> Option<Note> { pub fn get(id: &String) -> Option<Note> {
let value: Option<String> = CLIENT.get(&id).unwrap(); let value: Option<String> = CLIENT.get(&id).unwrap();
match value { match value {
None => return None, None => return None,
Some(s) => { Some(s) => {
let deserialize: Note = serde_json::from_str(&s).unwrap(); let deserialize: Note = serde_json::from_str(&s).unwrap();
return Some(deserialize); return Some(deserialize);
}
} }
}
} }
pub fn del(id: &String) { pub fn del(id: &String) {
CLIENT.delete(id).unwrap(); CLIENT.delete(id).unwrap();
} }