From 25649e62802f7332489961b1dde4a99a4b29679c Mon Sep 17 00:00:00 2001 From: hole-thu Date: Wed, 6 Jul 2022 17:56:11 +0800 Subject: [PATCH] fix clippy & rustfmt --- rust-toolchain | 1 + src/api/attention.rs | 6 ++-- src/api/comment.rs | 18 +++++------ src/api/mod.rs | 76 ++++++++++++++++++++++---------------------- src/api/operation.rs | 18 +++++------ src/api/post.rs | 32 +++++++++---------- src/api/search.rs | 12 +++---- src/api/systemlog.rs | 6 ++-- src/api/upload.rs | 6 ++-- src/api/vote.rs | 13 +++----- src/cache.rs | 12 +++---- src/cors.rs | 31 +++++++++--------- src/db_conn.rs | 8 ++--- src/main.rs | 2 +- src/models.rs | 2 +- src/rds_conn.rs | 3 +- src/rds_models.rs | 8 ++--- src/schema.rs | 6 +--- 18 files changed, 123 insertions(+), 137 deletions(-) create mode 100644 rust-toolchain diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..2bf5ad0 --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +stable diff --git a/src/api/attention.rs b/src/api/attention.rs index a86c7dc..0ad9c50 100644 --- a/src/api/attention.rs +++ b/src/api/attention.rs @@ -1,5 +1,5 @@ use crate::api::post::ps2outputs; -use crate::api::{CurrentUser, JsonAPI, PolicyError::*, UGC}; +use crate::api::{CurrentUser, JsonApi, PolicyError::*, Ugc}; use crate::db_conn::Db; use crate::libs::diesel_logger::LoggingConnection; use crate::models::*; @@ -23,7 +23,7 @@ pub async fn attention_post( user: CurrentUser, db: Db, rconn: RdsConn, -) -> JsonAPI { +) -> JsonApi { // 临时用户不允许手动关注 user.id.ok_or(YouAreTmp)?; @@ -68,7 +68,7 @@ pub async fn attention_post( } #[get("/getattention")] -pub async fn get_attention(user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn get_attention(user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { let mut ids = Attention::init(&user.namehash, &rconn).all().await?; ids.sort_by_key(|x| -x); let ps = Post::get_multi(&db, &rconn, &ids).await?; diff --git a/src/api/comment.rs b/src/api/comment.rs index fc41c0d..8cf72c4 100644 --- a/src/api/comment.rs +++ b/src/api/comment.rs @@ -1,4 +1,4 @@ -use crate::api::{APIError, CurrentUser, JsonAPI, PolicyError::*, UGC}; +use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc}; use crate::cache::BlockDictCache; use crate::db_conn::Db; use crate::libs::diesel_logger::LoggingConnection; @@ -40,7 +40,7 @@ pub struct CommentOutput { pub async fn c2output<'r>( p: &'r Post, - cs: &Vec, + cs: &[Comment], user: &CurrentUser, cached_block_dict: &HashMap, rconn: &RdsConn, @@ -66,10 +66,10 @@ pub async fn c2output<'r>( text: (if can_view { &c.content } else { "" }).to_string(), author_title: c.author_title.to_string(), can_del: c.check_permission(user, "wd").is_ok(), - name_id: name_id, + name_id, is_tmp: c.is_tmp, create_time: c.create_time.timestamp(), - is_blocked: is_blocked, + is_blocked, blocked_count: if user.is_admin { BlockCounter::get_count(rconn, &c.author_hash) .await @@ -85,18 +85,18 @@ pub async fn c2output<'r>( })) .await .into_iter() - .filter_map(|x| x) + .flatten() .collect() } #[get("/getcomment?")] -pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { let p = Post::get(&db, &rconn, pid).await?; if p.is_deleted { - return Err(APIError::PcError(IsDeleted)); + return Err(ApiError::Pc(IsDeleted)); } let cs = p.get_comments(&db, &rconn).await?; - let hash_list = cs.iter().map(|c| &c.author_hash).collect(); + let hash_list = cs.iter().map(|c| &c.author_hash).collect::>(); let cached_block_dict = BlockDictCache::init(&user.namehash, p.id, &rconn) .get_or_create(&user, &hash_list) .await?; @@ -118,7 +118,7 @@ pub async fn add_comment( user: CurrentUser, db: Db, rconn: RdsConn, -) -> JsonAPI { +) -> JsonApi { let mut p = Post::get(&db, &rconn, ci.pid).await?; let c = Comment::create( &db, diff --git a/src/api/mod.rs b/src/api/mod.rs index 635e17f..82fc249 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -91,7 +91,7 @@ impl<'r> FromRequest<'r> for CurrentUser { Outcome::Failure((Status::Forbidden, ())) } else { Outcome::Success(CurrentUser { - id: id, + id, custom_title: CustomTitle::get(&rconn, &nh) .await .ok() @@ -99,7 +99,7 @@ impl<'r> FromRequest<'r> for CurrentUser { .unwrap_or_default(), auto_block_rank: AutoBlockRank::get(&rconn, &nh).await.unwrap_or(2), namehash: nh, - is_admin: is_admin, + is_admin, }) } } @@ -119,20 +119,20 @@ pub enum PolicyError { } #[derive(Debug)] -pub enum APIError { - DbError(diesel::result::Error), - RdsError(redis::RedisError), - PcError(PolicyError), - IoError(std::io::Error), +pub enum ApiError { + Db(diesel::result::Error), + Rds(redis::RedisError), + Pc(PolicyError), + IO(std::io::Error), } -impl<'r> Responder<'r, 'static> for APIError { +impl<'r> Responder<'r, 'static> for ApiError { fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> { match self { - APIError::DbError(e) => e2s!(e).respond_to(req), - APIError::RdsError(e) => e2s!(e).respond_to(req), - APIError::IoError(e) => e2s!(e).respond_to(req), - APIError::PcError(e) => json!({ + ApiError::Db(e) => e2s!(e).respond_to(req), + ApiError::Rds(e) => e2s!(e).respond_to(req), + ApiError::IO(e) => e2s!(e).respond_to(req), + ApiError::Pc(e) => json!({ "code": -1, "msg": match e { PolicyError::IsReported => "内容被举报,处理中", @@ -148,60 +148,60 @@ impl<'r> Responder<'r, 'static> for APIError { } } -impl From for APIError { - fn from(err: diesel::result::Error) -> APIError { - APIError::DbError(err) +impl From for ApiError { + fn from(err: diesel::result::Error) -> ApiError { + ApiError::Db(err) } } -impl From for APIError { - fn from(err: redis::RedisError) -> APIError { - APIError::RdsError(err) +impl From for ApiError { + fn from(err: redis::RedisError) -> ApiError { + ApiError::Rds(err) } } -impl From for APIError { - fn from(err: std::io::Error) -> APIError { - APIError::IoError(err) +impl From for ApiError { + fn from(err: std::io::Error) -> ApiError { + ApiError::IO(err) } } -impl From for APIError { - fn from(err: PolicyError) -> APIError { - APIError::PcError(err) +impl From for ApiError { + fn from(err: PolicyError) -> ApiError { + ApiError::Pc(err) } } -pub type API = Result; -pub type JsonAPI = API; +pub type Api = Result; +pub type JsonApi = Api; #[rocket::async_trait] -pub trait UGC { +pub trait Ugc { fn get_author_hash(&self) -> &str; fn get_is_deleted(&self) -> bool; fn get_is_reported(&self) -> bool; fn extra_delete_condition(&self) -> bool; - async fn do_set_deleted(&mut self, db: &Db) -> API<()>; - fn check_permission(&self, user: &CurrentUser, mode: &str) -> API<()> { + async fn do_set_deleted(&mut self, db: &Db) -> Api<()>; + fn check_permission(&self, user: &CurrentUser, mode: &str) -> Api<()> { if user.is_admin { return Ok(()); } if mode.contains('r') && self.get_is_deleted() { - return Err(APIError::PcError(PolicyError::IsDeleted)); + return Err(ApiError::Pc(PolicyError::IsDeleted)); } if mode.contains('o') && self.get_is_reported() { - return Err(APIError::PcError(PolicyError::IsReported)); + return Err(ApiError::Pc(PolicyError::IsReported)); } if mode.contains('w') && self.get_author_hash() != user.namehash { - return Err(APIError::PcError(PolicyError::NotAllowed)); + return Err(ApiError::Pc(PolicyError::NotAllowed)); } if mode.contains('d') && !self.extra_delete_condition() { - return Err(APIError::PcError(PolicyError::NotAllowed)); + return Err(ApiError::Pc(PolicyError::NotAllowed)); } Ok(()) } - async fn soft_delete(&mut self, user: &CurrentUser, db: &Db) -> API<()> { + async fn soft_delete(&mut self, user: &CurrentUser, db: &Db) -> Api<()> { self.check_permission(user, "rwd")?; self.do_set_deleted(db).await?; @@ -210,7 +210,7 @@ pub trait UGC { } #[rocket::async_trait] -impl UGC for Post { +impl Ugc for Post { fn get_author_hash(&self) -> &str { &self.author_hash } @@ -223,14 +223,14 @@ impl UGC for Post { fn extra_delete_condition(&self) -> bool { !self.content.starts_with("[系统自动代发]\n") } - async fn do_set_deleted(&mut self, db: &Db) -> API<()> { + async fn do_set_deleted(&mut self, db: &Db) -> Api<()> { update!(*self, posts, db, { is_deleted, to true }); Ok(()) } } #[rocket::async_trait] -impl UGC for Comment { +impl Ugc for Comment { fn get_author_hash(&self) -> &str { &self.author_hash } @@ -243,7 +243,7 @@ impl UGC for Comment { fn extra_delete_condition(&self) -> bool { true } - async fn do_set_deleted(&mut self, db: &Db) -> API<()> { + async fn do_set_deleted(&mut self, db: &Db) -> Api<()> { update!(*self, comments, db, { is_deleted, to true }); Ok(()) } diff --git a/src/api/operation.rs b/src/api/operation.rs index 210080a..dcfd252 100644 --- a/src/api/operation.rs +++ b/src/api/operation.rs @@ -1,4 +1,4 @@ -use crate::api::{APIError, CurrentUser, JsonAPI, PolicyError::*, UGC}; +use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc}; use crate::cache::*; use crate::db_conn::Db; use crate::libs::diesel_logger::LoggingConnection; @@ -20,7 +20,7 @@ pub struct DeleteInput { } #[post("/delete", data = "")] -pub async fn delete(di: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn delete(di: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { let (author_hash, p) = match di.id_type.as_str() { "cid" => { let mut c = Comment::get(&db, di.id).await?; @@ -98,7 +98,7 @@ pub struct ReportInput { } #[post("/report", data = "")] -pub async fn report(ri: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn report(ri: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { // 临时用户不允许举报 user.id.ok_or(NotAllowed)?; @@ -154,10 +154,10 @@ pub struct BlockInput { } #[post("/block", data = "")] -pub async fn block(bi: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { - user.id.ok_or_else(|| NotAllowed)?; +pub async fn block(bi: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { + user.id.ok_or(NotAllowed)?; - let mut blk = BlockedUsers::init(user.id.ok_or_else(|| NotAllowed)?, &rconn); + let mut blk = BlockedUsers::init(user.id.ok_or(NotAllowed)?, &rconn); let pid; let nh_to_block = match bi.content_type.as_str() { @@ -171,7 +171,7 @@ pub async fn block(bi: Form, user: CurrentUser, db: Db, rconn: RdsCo pid = c.post_id; c.author_hash } - _ => return Err(APIError::PcError(NotAllowed)), + _ => return Err(ApiError::Pc(NotAllowed)), }; if nh_to_block.eq(&user.namehash) { @@ -203,7 +203,7 @@ pub struct TitleInput { } #[post("/title", data = "")] -pub async fn set_title(ti: Form, user: CurrentUser, rconn: RdsConn) -> JsonAPI { +pub async fn set_title(ti: Form, user: CurrentUser, rconn: RdsConn) -> JsonApi { if CustomTitle::set(&rconn, &user.namehash, &ti.title).await? { code0!() } else { @@ -221,7 +221,7 @@ pub async fn set_auto_block( ai: Form, user: CurrentUser, rconn: RdsConn, -) -> JsonAPI { +) -> JsonApi { AutoBlockRank::set(&rconn, &user.namehash, ai.rank).await?; code0!() } diff --git a/src/api/post.rs b/src/api/post.rs index 82fd159..6a8615a 100644 --- a/src/api/post.rs +++ b/src/api/post.rs @@ -1,6 +1,6 @@ use crate::api::comment::{c2output, CommentOutput}; use crate::api::vote::get_poll_dict; -use crate::api::{CurrentUser, JsonAPI, PolicyError::*, API, UGC}; +use crate::api::{CurrentUser, JsonApi, PolicyError::*, Api, Ugc}; use crate::cache::*; use crate::db_conn::Db; use crate::libs::diesel_logger::LoggingConnection; @@ -63,7 +63,7 @@ pub struct CwInput { cw: String, } -async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> API { +async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> Api { let comments: Option> = if p.n_comments < 5 { Some(p.get_comments(db, rconn).await?) } else { @@ -74,10 +74,10 @@ async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> API .flatten() .map(|c| &c.author_hash) .chain(std::iter::once(&p.author_hash)) - .collect(); + .collect::>(); //dbg!(&hash_list); let cached_block_dict = BlockDictCache::init(&user.namehash, p.id, rconn) - .get_or_create(&user, &hash_list) + .get_or_create(user, &hash_list) .await?; let is_blocked = cached_block_dict[&p.author_hash]; let can_view = @@ -100,9 +100,9 @@ async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> API ) .await, can_del: p.check_permission(user, "wd").is_ok(), - attention: Attention::init(&user.namehash, &rconn).has(p.id).await?, + attention: Attention::init(&user.namehash, rconn).has(p.id).await?, hot_score: user.is_admin.then(|| p.hot_score), - is_blocked: is_blocked, + is_blocked, blocked_count: if user.is_admin { BlockCounter::get_count(rconn, &p.author_hash).await? } else { @@ -122,20 +122,20 @@ async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> API } pub async fn ps2outputs( - ps: &Vec, + ps: &[Post], user: &CurrentUser, db: &Db, rconn: &RdsConn, -) -> API> { +) -> Api> { future::try_join_all( ps.iter() - .map(|p| async { Ok(p2output(p, &user, &db, &rconn).await?) }), + .map(|p| async { p2output(p, user, db, rconn).await }), ) .await } #[get("/getone?")] -pub async fn get_one(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn get_one(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { let p = Post::get(&db, &rconn, pid).await?; p.check_permission(&user, "ro")?; Ok(json!({ @@ -151,8 +151,8 @@ pub async fn get_list( user: CurrentUser, db: Db, rconn: RdsConn, -) -> JsonAPI { - user.id.ok_or_else(|| YouAreTmp)?; +) -> JsonApi { + user.id.ok_or(YouAreTmp)?; let page = p.unwrap_or(1); let page_size = 25; let start = (page - 1) * page_size; @@ -173,7 +173,7 @@ pub async fn publish_post( user: CurrentUser, db: Db, rconn: RdsConn, -) -> JsonAPI { +) -> JsonApi { let p = Post::create( &db, NewPost { @@ -199,7 +199,7 @@ pub async fn publish_post( } #[post("/editcw", data = "")] -pub async fn edit_cw(cwi: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { +pub async fn edit_cw(cwi: Form, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { let mut p = Post::get(&db, &rconn, cwi.pid).await?; p.check_permission(&user, "w")?; update!(p, posts, &db, { cw, to cwi.cw.to_string() }); @@ -208,8 +208,8 @@ pub async fn edit_cw(cwi: Form, user: CurrentUser, db: Db, rconn: RdsCo } #[get("/getmulti?")] -pub async fn get_multi(pids: Vec, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI { - user.id.ok_or_else(|| YouAreTmp)?; +pub async fn get_multi(pids: Vec, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi { + user.id.ok_or(YouAreTmp)?; let ps = Post::get_multi(&db, &rconn, &pids).await?; let ps_data = ps2outputs(&ps, &user, &db, &rconn).await?; diff --git a/src/api/search.rs b/src/api/search.rs index 7e95faa..116fd7d 100644 --- a/src/api/search.rs +++ b/src/api/search.rs @@ -1,5 +1,5 @@ use crate::api::post::ps2outputs; -use crate::api::{CurrentUser, JsonAPI, PolicyError::*}; +use crate::api::{CurrentUser, JsonApi, PolicyError::*}; use crate::db_conn::Db; use crate::models::*; use crate::rds_conn::RdsConn; @@ -13,17 +13,13 @@ pub async fn search( user: CurrentUser, db: Db, rconn: RdsConn, -) -> JsonAPI { - user.id.ok_or_else(|| YouAreTmp)?; +) -> JsonApi { + user.id.ok_or(YouAreTmp)?; let page_size = 25; let start = (page - 1) * page_size; - let kws = keywords - .split(" ") - .filter(|x| !x.is_empty()) - .collect::>(); - let ps = if kws.is_empty() { + let ps = if !keywords.chars().any(|c| !c.eq(&' ')) { vec![] } else { Post::search( diff --git a/src/api/systemlog.rs b/src/api/systemlog.rs index 7ccd2ae..f399360 100644 --- a/src/api/systemlog.rs +++ b/src/api/systemlog.rs @@ -1,12 +1,12 @@ -use crate::api::{CurrentUser, JsonAPI}; +use crate::api::{CurrentUser, JsonApi}; use crate::random_hasher::RandomHasher; use crate::rds_conn::RdsConn; -use crate::rds_models::{Systemlog}; +use crate::rds_models::Systemlog; use rocket::serde::json::{json, Value}; use rocket::State; #[get("/systemlog")] -pub async fn get_systemlog(user: CurrentUser, rh: &State, rconn: RdsConn) -> JsonAPI { +pub async fn get_systemlog(user: CurrentUser, rh: &State, rconn: RdsConn) -> JsonApi { let logs = Systemlog::get_list(&rconn, 50).await?; Ok(json!({ diff --git a/src/api/upload.rs b/src/api/upload.rs index 1b7ea8a..f329470 100644 --- a/src/api/upload.rs +++ b/src/api/upload.rs @@ -1,10 +1,10 @@ -use crate::api::{CurrentUser, JsonAPI}; +use crate::api::{CurrentUser, JsonApi}; use rocket::fs::TempFile; use rocket::serde::json::json; use std::process::Command; #[post("/upload", data = "")] -pub async fn ipfs_upload(_user: CurrentUser, file: TempFile<'_>) -> JsonAPI { +pub async fn ipfs_upload(_user: CurrentUser, file: TempFile<'_>) -> JsonApi { // dbg!(&file); // dbg!(&file.path()); @@ -21,7 +21,7 @@ pub async fn ipfs_upload(_user: CurrentUser, file: TempFile<'_>) -> JsonAPI { // dbg!(&output); let hash = std::str::from_utf8(&output.stdout) .unwrap() - .split_terminator("\n") + .split_terminator('\n') .last() .unwrap_or_else(|| { dbg!(&output); diff --git a/src/api/vote.rs b/src/api/vote.rs index 8a39ca0..c74f363 100644 --- a/src/api/vote.rs +++ b/src/api/vote.rs @@ -1,4 +1,4 @@ -use crate::api::{CurrentUser, JsonAPI, PolicyError::*}; +use crate::api::{CurrentUser, JsonApi, PolicyError::*}; use crate::rds_conn::RdsConn; use crate::rds_models::*; use rocket::form::Form; @@ -22,7 +22,7 @@ pub async fn get_poll_dict(pid: i32, rconn: &RdsConn, namehash: &str) -> Option< })) .await .into_iter() - .filter_map(|x| x) + .flatten() .collect::>() .pop(); Some(json!({ @@ -46,8 +46,8 @@ pub struct VoteInput { } #[post("/vote", data = "")] -pub async fn vote(vi: Form, user: CurrentUser, rconn: RdsConn) -> JsonAPI { - user.id.ok_or_else(|| NotAllowed)?; +pub async fn vote(vi: Form, user: CurrentUser, rconn: RdsConn) -> JsonApi { + user.id.ok_or(NotAllowed)?; let pid = vi.pid; let opts = PollOption::init(pid, &rconn).get_list().await?; @@ -61,10 +61,7 @@ pub async fn vote(vi: Form, user: CurrentUser, rconn: RdsConn) -> Jso } } - let idx: usize = opts - .iter() - .position(|x| x.eq(&vi.vote)) - .ok_or_else(|| NotAllowed)?; + let idx: usize = opts.iter().position(|x| x.eq(&vi.vote)).ok_or(NotAllowed)?; PollVote::init(pid, idx, &rconn).add(&user.namehash).await?; diff --git a/src/cache.rs b/src/cache.rs index 1056e72..4fdfd19 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -28,7 +28,7 @@ pub struct PostCache { impl PostCache { init!(); - pub async fn sets(&mut self, ps: &Vec<&Post>) { + pub async fn sets(&mut self, ps: &[&Post]) { if ps.is_empty() { return; } @@ -61,7 +61,7 @@ impl PostCache { }) } - pub async fn gets(&mut self, pids: &Vec) -> Vec> { + pub async fn gets(&mut self, pids: &[i32]) -> Vec> { // 长度为1时会走GET而非MGET,返回值格式不兼容。愚蠢的设计。 match pids.len() { 0 => vec![], @@ -128,7 +128,7 @@ pub struct PostCommentCache { impl PostCommentCache { init!(i32, "hole_v2:cache:post_comments:{}"); - pub async fn set(&mut self, cs: &Vec) { + pub async fn set(&mut self, cs: &[Comment]) { self.rconn .set_ex( &self.key, @@ -183,7 +183,7 @@ impl PostListCommentCache { pub fn init(mode: u8, rconn: &RdsConn) -> Self { Self { key: format!("hole_v2:cache:post_list:{}", &mode), - mode: mode, + mode, rconn: rconn.clone(), length: 0, } @@ -229,7 +229,7 @@ impl PostListCommentCache { ) } - pub async fn fill(&mut self, ps: &Vec) { + pub async fn fill(&mut self, ps: &[Post]) { let items: Vec<(i64, i32)> = ps.iter().map(|p| self.p2pair(p)).collect(); self.rconn .zadd_multiple(&self.key, &items) @@ -337,7 +337,7 @@ impl BlockDictCache { pub async fn get_or_create( &mut self, user: &CurrentUser, - hash_list: &Vec<&String>, + hash_list: &[&String], ) -> RedisResult> { let mut block_dict = self .rconn diff --git a/src/cors.rs b/src/cors.rs index c2cefe6..bf4761f 100644 --- a/src/cors.rs +++ b/src/cors.rs @@ -3,12 +3,12 @@ use rocket::http::Header; use rocket::{Request, Response}; use std::path::PathBuf; -pub struct CORS { +pub struct Cors { pub whitelist: Vec, } #[rocket::async_trait] -impl Fairing for CORS { +impl Fairing for Cors { fn info(&self) -> Info { Info { name: "Add CORS headers to responses", @@ -17,23 +17,22 @@ impl Fairing for CORS { } async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) { - request + if let Some(origin) = request .headers() .get_one("Origin") .and_then(|origin| self.whitelist.contains(&origin.to_string()).then(|| origin)) - .and_then(|origin| { - response.set_header(Header::new("Access-Control-Allow-Origin", origin)); - response.set_header(Header::new( - "Access-Control-Allow-Methods", - "POST, GET, OPTIONS", - )); - response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); - response.set_header(Header::new( - "Access-Control-Allow-Headers", - "User-Token, Content-Type", - )); - Some(()) - }); + { + response.set_header(Header::new("Access-Control-Allow-Origin", origin)); + response.set_header(Header::new( + "Access-Control-Allow-Methods", + "POST, GET, OPTIONS", + )); + response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); + response.set_header(Header::new( + "Access-Control-Allow-Headers", + "User-Token, Content-Type", + )); + } } } diff --git a/src/db_conn.rs b/src/db_conn.rs index 1263019..b6694aa 100644 --- a/src/db_conn.rs +++ b/src/db_conn.rs @@ -1,5 +1,5 @@ -use rocket_sync_db_pools::{database, diesel}; use diesel::Connection; +use rocket_sync_db_pools::{database, diesel}; use std::env; pub type Conn = diesel::pg::PgConnection; @@ -7,11 +7,9 @@ pub type Conn = diesel::pg::PgConnection; #[database("pg_v2")] pub struct Db(Conn); - // get sync connection, only for annealing pub fn establish_connection() -> Conn { - let database_url = env::var("DATABASE_URL") - .expect("DATABASE_URL must be set"); + let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); Conn::establish(&database_url) - .expect(&format!("Error connecting to {}", database_url)) + .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) } diff --git a/src/main.rs b/src/main.rs index 195c8ce..3797081 100644 --- a/src/main.rs +++ b/src/main.rs @@ -100,7 +100,7 @@ async fn main() -> Result<(), rocket::Error> { .manage(RandomHasher::get_random_one()) .manage(rmc) .attach(Db::fairing()) - .attach(cors::CORS { + .attach(cors::Cors { whitelist: env::var("FRONTEND_WHITELIST") .unwrap_or_default() .split(',') diff --git a/src/models.rs b/src/models.rs index 685833f..8606f30 100644 --- a/src/models.rs +++ b/src/models.rs @@ -171,7 +171,7 @@ impl Post { let missing_ps = Self::_get_multi(db, missing_ids).await?; // dbg!(&missing_ps); - cacher.sets(&missing_ps.iter().collect()).await; + cacher.sets(&missing_ps.iter().collect::>()).await; for p in missing_ps.into_iter() { if let Some(op) = id2po.get_mut(&p.id) { diff --git a/src/rds_conn.rs b/src/rds_conn.rs index 3405345..f798149 100644 --- a/src/rds_conn.rs +++ b/src/rds_conn.rs @@ -1,7 +1,7 @@ use redis::aio::MultiplexedConnection; use rocket::request::{FromRequest, Outcome, Request}; -use std::ops::{Deref, DerefMut}; use std::env; +use std::ops::{Deref, DerefMut}; pub struct RdsConn(pub MultiplexedConnection); @@ -34,7 +34,6 @@ impl DerefMut for RdsConn { } } - pub async fn init_rds_client() -> MultiplexedConnection { let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set"); let client = redis::Client::open(redis_url).expect("connect to redis fail"); diff --git a/src/rds_models.rs b/src/rds_models.rs index 212c422..10d0797 100644 --- a/src/rds_models.rs +++ b/src/rds_models.rs @@ -284,10 +284,10 @@ impl PollVote { } pub async fn clear_outdate_redis_data(rconn: &RdsConn) { - BannedUsers::clear(&rconn).await.unwrap(); - CustomTitle::clear(&rconn).await.unwrap(); - AutoBlockRank::clear(&rconn).await.unwrap(); - Attention::clear_all(&rconn).await; + BannedUsers::clear(rconn).await.unwrap(); + CustomTitle::clear(rconn).await.unwrap(); + AutoBlockRank::clear(rconn).await.unwrap(); + Attention::clear_all(rconn).await; } pub(crate) use init; diff --git a/src/schema.rs b/src/schema.rs index db6da45..83a6e58 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -42,8 +42,4 @@ table! { joinable!(comments -> posts (post_id)); -allow_tables_to_appear_in_same_query!( - comments, - posts, - users, -); +allow_tables_to_appear_in_same_query!(comments, posts, users,);