diff --git a/htycommons/src/common.rs b/htycommons/src/common.rs index e010b96..684e0e8 100644 --- a/htycommons/src/common.rs +++ b/htycommons/src/common.rs @@ -115,7 +115,8 @@ pub fn parse_date_time(date_time: &String) -> anyhow::Result { } pub fn parse_bool(bool_val: &String) -> anyhow::Result { - Ok(bool_val.trim().parse().unwrap()) + bool_val.trim().parse() + .map_err(|e| anyhow::anyhow!("Failed to parse bool: {}", e)) } pub fn get_some_from_query_params( @@ -159,8 +160,8 @@ pub fn strip_result_vec(in_vec: Vec>) -> anyhow::Result String { - url.split("/").last().unwrap().to_string() +pub fn extract_filename_from_url(url: &String) -> Option { + url.split("/").last().filter(|s| !s.is_empty()).map(|s| s.to_string()) } pub fn date_to_string(date: &NaiveDateTime) -> String { @@ -168,26 +169,26 @@ pub fn date_to_string(date: &NaiveDateTime) -> String { } pub fn string_to_datetime(datetime: &Option) -> anyhow::Result> { - if datetime.is_none() { - return Ok(None); - } else { + if let Some(dt) = datetime { Ok(Some(NaiveDateTime::parse_from_str( - datetime.as_ref().unwrap().as_str(), + dt.as_str(), "%Y-%m-%d %H:%M:%S", )?)) + } else { + Ok(None) } } pub fn string_to_date(date: &Option) -> anyhow::Result> { debug!("string_to_date -> {:?}", date); - if date.is_none() { - return Ok(None); - } else { + if let Some(d) = date { Ok(Some( - NaiveDate::parse_from_str(date.as_ref().unwrap().as_str(), "%Y-%m-%d")? + NaiveDate::parse_from_str(d.as_str(), "%Y-%m-%d")? .and_time(NaiveTime::from_str("00:00:00")?), )) + } else { + Ok(None) } } diff --git a/htycommons/src/db.rs b/htycommons/src/db.rs index fb81cd2..8df69d3 100644 --- a/htycommons/src/db.rs +++ b/htycommons/src/db.rs @@ -47,7 +47,7 @@ pub fn pool(db_url: &str) -> PgPool { let max_size = env::var("POOL_SIZE") .expect("POOL_SIZE must be set") .parse::() - .unwrap(); + .unwrap_or_else(|e| panic!("Failed to parse POOL_SIZE: {}", e)); Pool::builder() .max_size(max_size) diff --git a/htycommons/src/jwt.rs b/htycommons/src/jwt.rs index fd5714b..3dfc708 100644 --- a/htycommons/src/jwt.rs +++ b/htycommons/src/jwt.rs @@ -21,9 +21,18 @@ pub fn jwt_key() -> String { } pub fn jwt_encode_token(token: HtyToken) -> Result { - let t = n_hour_later(¤t_local_datetime(), 10000).and_utc().timestamp() as usize; + let t = n_hour_later(¤t_local_datetime(), 10000) + .map_err(|e| HtyErr { + code: HtyErrCode::JwtErr, + reason: Some(format!("Failed to calculate expiration time: {}", e)), + })? + .and_utc().timestamp() as usize; let claims = HtyJwtClaims { - sub: serde_json::to_string(&token).unwrap(), + sub: serde_json::to_string(&token) + .map_err(|e| HtyErr { + code: HtyErrCode::JwtErr, + reason: Some(format!("Failed to serialize token: {}", e)), + })?, exp: t, iat: t, }; @@ -57,7 +66,11 @@ fn _jwt_decode_claims(token: &String, validation: &Validation) -> Result { //debug(format!("decoded obj -> {:?}", v).as_str()); debug!("_jwt_decode_claims -> decoded token: {:?}", v); - Ok(serde_json::from_str::(v.claims.sub.as_str()).unwrap()) + serde_json::from_str::(v.claims.sub.as_str()) + .map_err(|e| HtyErr { + code: HtyErrCode::JwtErr, + reason: Some(format!("Failed to deserialize token: {}", e)), + }) } Err(err) => Err(wrap_err(JwtErr, Box::from(err))), } diff --git a/htycommons/src/lib.rs b/htycommons/src/lib.rs index 174de71..9388c02 100644 --- a/htycommons/src/lib.rs +++ b/htycommons/src/lib.rs @@ -53,8 +53,10 @@ pub fn pass_or_panic2(res: anyhow::Result) { } } -pub fn n_hour_later(now: &NaiveDateTime, n: i64) -> NaiveDateTime { - *now + chrono::Duration::try_hours(n).unwrap() +pub fn n_hour_later(now: &NaiveDateTime, n: i64) -> anyhow::Result { + chrono::Duration::try_hours(n) + .map(|duration| *now + duration) + .ok_or_else(|| anyhow::anyhow!("Invalid number of hours: {}", n)) } pub fn remove_quote(str: &String) -> String { diff --git a/htycommons/src/logger.rs b/htycommons/src/logger.rs index cfaaf62..5b74530 100644 --- a/htycommons/src/logger.rs +++ b/htycommons/src/logger.rs @@ -64,7 +64,7 @@ pub fn logger_init() -> () { // let timer = UtcTime::new(time::format_description::well_known::Rfc3339); // https://rustcc.cn/article?id=66e2a76e-8c65-42f7-a773-66dff1a2a21e let local_time = OffsetTime::new( - UtcOffset::from_hms(8, 0, 0).unwrap(), + UtcOffset::from_hms(8, 0, 0).unwrap_or_else(|_| UtcOffset::from_hms(0, 0, 0).expect("Failed to create UTC offset")), format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"), ); diff --git a/htycommons/src/pagination.rs b/htycommons/src/pagination.rs index d6b6f39..235dded 100644 --- a/htycommons/src/pagination.rs +++ b/htycommons/src/pagination.rs @@ -11,7 +11,7 @@ pub trait Paginate: Sized { impl Paginate for T { fn paginate(self, page: Option) -> Paginated { - let offset = if page.is_some() { (page.clone().unwrap() - 1) * DEFAULT_PER_PAGE } else { -1 }; + let offset = if let Some(p) = page { (p - 1) * DEFAULT_PER_PAGE } else { -1 }; Paginated { query: self, some_per_page: Some(DEFAULT_PER_PAGE), @@ -35,8 +35,8 @@ pub struct Paginated { impl Paginated { pub fn per_page(self, some_per_page: Option) -> Self { - let per_page = if some_per_page.is_some() { some_per_page.clone().unwrap() } else { -1 }; - let offset = if some_per_page.is_some() && self.page.is_some() { (self.page.clone().unwrap() - 1) * some_per_page.clone().unwrap() } else { -1 }; + let per_page = some_per_page.unwrap_or(-1); + let offset = if let (Some(sp), Some(p)) = (some_per_page, self.page) { (p - 1) * sp } else { -1 }; Paginated { some_per_page, @@ -60,8 +60,7 @@ impl Paginated { let unwrapped_results = results?; - if some_page.is_some() && some_per_page.is_some() { - let per_page = some_per_page.unwrap(); + if let (Some(_), Some(per_page)) = (some_page, some_per_page) { let total = unwrapped_results.get(0).map(|x| x.1).unwrap_or(0); let records = unwrapped_results.into_iter().map(|x| x.0).collect(); let total_pages = (total as f64 / per_page as f64).ceil() as i64; diff --git a/htycommons/src/redis_util.rs b/htycommons/src/redis_util.rs index 46dcedf..25d4c04 100644 --- a/htycommons/src/redis_util.rs +++ b/htycommons/src/redis_util.rs @@ -17,11 +17,11 @@ pub const OPENID_INFO: &str = "OPENID_INFO_"; pub const CACHED: &str = "C_"; -pub fn get_token_expiration_days() -> usize { +pub fn get_token_expiration_days() -> anyhow::Result { env::var("EXPIRATION_DAYS") .expect("EXPIRATION_DAYS not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse EXPIRATION_DAYS: {}", e)) } pub fn get_redis_url() -> anyhow::Result { @@ -50,7 +50,7 @@ pub fn save_token_with_exp_days(token: &HtyToken, expiration_day: usize) -> anyh prefix_key.push_str(token.clone().token_id.as_str()); save_kv_to_redis_with_exp_days(&prefix_key, - &jwt_encode_token(token.clone()).unwrap(), + &jwt_encode_token(token.clone())?, expiration_day) } @@ -79,7 +79,7 @@ pub fn save_kv_to_redis(key: &String, value: &String) -> anyhow::Result<()> { let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; match Client::open(redis_url.clone()) { Ok(cli) => match cli.get_connection() { @@ -113,7 +113,7 @@ pub fn save_kv_to_redis_with_exp_secs(key: &String, value: &String, expiration_s let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; match Client::open(redis_url.clone()) { Ok(cli) => match cli.get_connection() { @@ -153,7 +153,7 @@ pub fn get_value_from_redis(key: &String) -> anyhow::Result { let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); debug!("get_value_from_redis() -> key / {:?}", &prefix_key); - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; let mut redis_conn = Client::open(redis_url.clone())?.get_connection()?; let value = redis_conn.get(prefix_key)?; debug!("get_value_from_redis() -> token : {:?}", value); @@ -164,7 +164,7 @@ pub fn get_opt_value_from_redis(key: &String) -> anyhow::Result> let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); debug!("get_value_from_redis2() -> key / {:?}", &prefix_key); - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; let mut redis_conn = Client::open(redis_url.clone())?.get_connection()?; let value = redis_conn.get(prefix_key)?; debug!("get_value_from_redis2() -> token : {:?}", value); @@ -172,7 +172,7 @@ pub fn get_opt_value_from_redis(key: &String) -> anyhow::Result> } pub fn is_key_exist_in_redis(key: &String) -> anyhow::Result { - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); @@ -187,7 +187,7 @@ pub fn is_key_exist_in_redis(key: &String) -> anyhow::Result { pub fn verify_jwt(jwt_token: &String) -> anyhow::Result<()> { dotenv().ok(); //Save token to redis - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; debug!("verify_jwt -> redis_url / {:?}", redis_url.clone()); debug!("verify_jwt -> jwt_token to verify: {:?}", jwt_token.clone()); @@ -227,7 +227,7 @@ pub fn del_from_redis(key: &String) -> anyhow::Result { let mut prefix_key = HTY_REDIS_KEY_PREFIX.to_string(); prefix_key.push_str(key); - let redis_url = get_redis_url().unwrap(); + let redis_url = get_redis_url()?; let mut redis_conn = Client::open(redis_url.clone())?.get_connection()?; diff --git a/htycommons/src/test_scaffold.rs b/htycommons/src/test_scaffold.rs index 1cec7c0..400832f 100644 --- a/htycommons/src/test_scaffold.rs +++ b/htycommons/src/test_scaffold.rs @@ -74,9 +74,9 @@ pub fn my_assert_not_none(val: &Option) -> Result<(), HtyErr> } -pub fn get_test_app_domain() -> u16 { +pub fn get_test_app_domain() -> anyhow::Result { env::var("TEST_APP_DOMAIN") .expect("TEST_APP_DOMAIN not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse TEST_APP_DOMAIN: {}", e)) } \ No newline at end of file diff --git a/htycommons/src/upyun.rs b/htycommons/src/upyun.rs index cd49498..1ee78c6 100644 --- a/htycommons/src/upyun.rs +++ b/htycommons/src/upyun.rs @@ -72,7 +72,8 @@ pub async fn upyun_delete_by_filename(in_filename: &String, sudoer: &String, hos let url = format!("{}/image/upyun_remove", get_ngx_url()); debug!("upyun_delete_by_filename -> url: {}", url); - let body = serde_json::to_string::(&upyun_filename).unwrap(); + let body = serde_json::to_string::(&upyun_filename) + .map_err(|e| anyhow::anyhow!("Failed to serialize upyun_filename: {}", e))?; debug!("upyun_delete_by_filename -> body: {}", body); diff --git a/htycommons/src/web.rs b/htycommons/src/web.rs index bde1bfd..50b71c9 100644 --- a/htycommons/src/web.rs +++ b/htycommons/src/web.rs @@ -126,10 +126,18 @@ where let resp = wrap_auth_err(&None); Err((StatusCode::UNAUTHORIZED, resp)) } else { - match jwt_decode_token(&token_result.unwrap().to_string()) { - Ok(resp) => Ok(resp), - Err(err) => { - let resp = wrap_auth_err(&Some(err.to_string())); + match token_result { + Ok(token_str) => { + match jwt_decode_token(&token_str.to_string()) { + Ok(resp) => Ok(resp), + Err(err) => { + let resp = wrap_auth_err(&Some(err.to_string())); + Err((StatusCode::UNAUTHORIZED, resp)) + } + } + } + Err(_) => { + let resp = wrap_auth_err(&None); Err((StatusCode::UNAUTHORIZED, resp)) } } @@ -267,7 +275,19 @@ pub fn wrap_auth_err(some_err_str: &Option) -> String { reason: None, }), }) - .unwrap() + .unwrap_or_else(|_| { + // 如果序列化失败,尝试序列化一个简化的响应 + serde_json::to_string(&HtyResponse:: { + r: false, + d: None, + e: Some("AuthorizationErr".to_string()), + hty_err: Some(HtyErr { + code: HtyErrCode::InternalErr, + reason: None, + }), + }) + .expect("Failed to serialize simplified HtyResponse") + }) } pub fn wrap_sudo_err(some_token: &Option) -> String { @@ -280,7 +300,19 @@ pub fn wrap_sudo_err(some_token: &Option) -> String { reason: Some("HtySudoerTokenErr".to_string()), }), }) - .unwrap() + .unwrap_or_else(|_| { + // 如果序列化失败,尝试序列化一个简化的响应 + serde_json::to_string(&HtyResponse:: { + r: false, + d: None, + e: Some("HtySudoerTokenErr".to_string()), + hty_err: Some(HtyErr { + code: HtyErrCode::AuthenticationFailed, + reason: Some("HtySudoerTokenErr".to_string()), + }), + }) + .expect("Failed to serialize simplified HtyResponse") + }) } pub fn wrap_anyhow_err( @@ -314,16 +346,18 @@ pub fn wrap_ok_resp(ok: T) -> H //------------------------------------------------ -pub async fn launch_rocket(port: u16, app: Router) { +pub async fn launch_rocket(port: u16, app: Router) -> anyhow::Result<()> { debug!("launching rocket...🚀"); let addr = SocketAddr::from(([127, 0, 0, 1], port)); // tracing::debug!("listening on {}", addr); debug!("listening on {}", addr); // https://tokio.rs/blog/2023-11-27-announcing-axum-0-7-0 - let listener = TcpListener::bind(&addr).await.unwrap(); + let listener = TcpListener::bind(&addr).await + .map_err(|e| anyhow!("Failed to bind to address: {}", e))?; axum::serve(listener, app.into_make_service()) .await - .unwrap(); + .map_err(|e| anyhow!("Failed to start server: {}", e))?; + Ok(()) } @@ -357,11 +391,11 @@ pub fn random_port() -> u16 { rand::rng().random_range(10000..20000) } -pub fn get_uc_port() -> u16 { +pub fn get_uc_port() -> anyhow::Result { env::var("UC_PORT") .expect("UC_PORT not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse UC_PORT: {}", e)) } pub fn generate_ports() { @@ -381,53 +415,52 @@ pub fn set_uc_port(port: u16) { env::set_var("UC_PORT", port.to_string()); } -pub fn get_ws_port() -> u16 { +pub fn get_ws_port() -> anyhow::Result { env::var("WS_PORT") .expect("WS_PORT not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse WS_PORT: {}", e)) } pub fn set_ws_port(port: u16) { env::set_var("WS_PORT", port.to_string()); } -pub fn get_kc_port() -> u16 { +pub fn get_kc_port() -> anyhow::Result { env::var("KC_PORT") .expect("KC_PORT not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse KC_PORT: {}", e)) } pub fn set_kc_port(port: u16) { env::set_var("KC_PORT", port.to_string()); } -pub fn skip_post_login() -> bool { +pub fn skip_post_login() -> anyhow::Result { env::var("SKIP_POST_LOGIN") .expect("SKIP_POST_LOGIN not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse SKIP_POST_LOGIN: {}", e)) } -pub fn skip_post_registration() -> bool { +pub fn skip_post_registration() -> anyhow::Result { env::var("SKIP_REGISTRATION") .expect("SKIP_REGISTRATION not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse SKIP_REGISTRATION: {}", e)) } -pub fn skip_wx_push() -> bool { +pub fn skip_wx_push() -> anyhow::Result { env::var("SKIP_WX_PUSH") .expect("SKIP_WX_PUSH not set!!!") .parse() - .unwrap() + .map_err(|e| anyhow::anyhow!("Failed to parse SKIP_WX_PUSH: {}", e)) } pub fn get_domain() -> String { env::var("DOMAIN") .expect("DOMAIN not set!!!") - .parse() - .unwrap() + .to_string() } #[derive(Debug, Serialize, Deserialize, Clone)] diff --git a/htycommons/src/wx.rs b/htycommons/src/wx.rs index ece0de8..d0b3c54 100644 --- a/htycommons/src/wx.rs +++ b/htycommons/src/wx.rs @@ -69,10 +69,11 @@ pub struct WxLogin { } pub async fn code2session(params: &WxParams) -> anyhow::Result { + let appid = params.appid.clone().ok_or_else(|| anyhow::anyhow!("appid is required"))?; + let secret = params.secret.clone().ok_or_else(|| anyhow::anyhow!("secret is required"))?; + let code = params.code.clone().ok_or_else(|| anyhow::anyhow!("code is required"))?; let url = format!("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", - params.appid.clone().unwrap(), - params.secret.clone().unwrap(), - params.code.clone().unwrap()); + appid, secret, code); debug!("code2session -> url -> {}", url); @@ -85,20 +86,25 @@ pub async fn code2session(params: &WxParams) -> anyhow::Result { Ok(ret) } -pub fn wx_decode(params: &WxParams, session_key: &str) -> String { +pub fn wx_decode(params: &WxParams, session_key: &str) -> anyhow::Result { use aes::cipher::{ block_padding::Pkcs7, generic_array::GenericArray, BlockDecryptMut, KeyIvInit, }; use cbc::Decryptor; type Aes128CbcDec = Decryptor; - let decoded_session_key = BASE64_DECODER.decode(session_key).unwrap(); - let decoded_iv = BASE64_DECODER.decode(params.iv.clone().unwrap()).unwrap(); + let decoded_session_key = BASE64_DECODER.decode(session_key) + .map_err(|e| anyhow::anyhow!("Failed to decode session_key: {}", e))?; + let iv = params.iv.clone().ok_or_else(|| anyhow::anyhow!("iv is required"))?; + let decoded_iv = BASE64_DECODER.decode(iv) + .map_err(|e| anyhow::anyhow!("Failed to decode iv: {}", e))?; let key = GenericArray::clone_from_slice(decoded_session_key.as_slice()); let iv = GenericArray::clone_from_slice(decoded_iv.as_slice()); - let decoded_encrypted_data = BASE64_DECODER.decode(params.encrypted_data.clone().unwrap()).unwrap(); + let encrypted_data = params.encrypted_data.clone().ok_or_else(|| anyhow::anyhow!("encrypted_data is required"))?; + let decoded_encrypted_data = BASE64_DECODER.decode(encrypted_data) + .map_err(|e| anyhow::anyhow!("Failed to decode encrypted_data: {}", e))?; let ct_len = decoded_encrypted_data.len(); let mut buf = vec![0u8; ct_len]; @@ -108,9 +114,11 @@ pub fn wx_decode(params: &WxParams, session_key: &str) -> String { let pt = Aes128CbcDec::new(&key, &iv) .decrypt_padded_mut::(&mut buf) - .unwrap(); + .map_err(|e| anyhow::anyhow!("Failed to decrypt data: {}", e))?; - std::str::from_utf8(&pt).unwrap().into() + std::str::from_utf8(&pt) + .map_err(|e| anyhow::anyhow!("Failed to convert to UTF-8: {}", e)) + .map(|s| s.to_string()) } diff --git a/htyuc/src/ddl.rs b/htyuc/src/ddl.rs index 95bd69c..76c19c1 100644 --- a/htyuc/src/ddl.rs +++ b/htyuc/src/ddl.rs @@ -15,20 +15,20 @@ pub fn uc_ddl() { // let conn = &mut uc_pool.get().unwrap(); - let root_app = insert_root_app(&mut uc_pool.get().unwrap()); - let root_tag = insert_root_tag(&mut uc_pool.get().unwrap()); - let root_role_id = insert_root_role(&mut uc_pool.get().unwrap()); + let root_app = insert_root_app(&mut uc_pool.get().expect("Failed to get database connection")); + let root_tag = insert_root_tag(&mut uc_pool.get().expect("Failed to get database connection")); + let root_role_id = insert_root_role(&mut uc_pool.get().expect("Failed to get database connection")); - insert_root_label(&mut uc_pool.get().unwrap(), &root_role_id.clone()); - insert_root_user(&root_app.app_id, &root_role_id.clone(), &mut uc_pool.get().unwrap()); + insert_root_label(&mut uc_pool.get().expect("Failed to get database connection"), &root_role_id.clone()); + insert_root_user(&root_app.app_id, &root_role_id.clone(), &mut uc_pool.get().expect("Failed to get database connection")); - let ts_app = insert_ts_app(&mut uc_pool.get().unwrap(), &root_tag.tag_id); - insert_ts_user(&ts_app.app_id, &mut uc_pool.get().unwrap()); + let ts_app = insert_ts_app(&mut uc_pool.get().expect("Failed to get database connection"), &root_tag.tag_id); + insert_ts_user(&ts_app.app_id, &mut uc_pool.get().expect("Failed to get database connection")); - let admin_app = insert_admin_app(&mut uc_pool.get().unwrap()); - let admin_role_id = insert_admin_role(&mut uc_pool.get().unwrap()); - insert_admin_label(&mut uc_pool.get().unwrap(), &admin_role_id.clone()); - insert_admin_user(&admin_app.app_id, &admin_role_id.clone(), &mut uc_pool.get().unwrap()); + let admin_app = insert_admin_app(&mut uc_pool.get().expect("Failed to get database connection")); + let admin_role_id = insert_admin_role(&mut uc_pool.get().expect("Failed to get database connection")); + insert_admin_label(&mut uc_pool.get().expect("Failed to get database connection"), &admin_role_id.clone()); + insert_admin_user(&admin_app.app_id, &admin_role_id.clone(), &mut uc_pool.get().expect("Failed to get database connection")); } @@ -56,7 +56,8 @@ pub fn insert_root_role(conn: &mut PgConnection) -> String { role_name: None, }; - let _root_role = HtyRole::create(&role_root, conn).unwrap(); + let _root_role = HtyRole::create(&role_root, conn) + .expect("Failed to create root role"); _root_role.hty_role_id } @@ -73,7 +74,8 @@ pub fn insert_admin_role(conn: &mut PgConnection) -> String { role_name: None, }; - let _role_admin_c = HtyRole::create(&role_admin, conn).unwrap(); + let _role_admin_c = HtyRole::create(&role_admin, conn) + .expect("Failed to create admin role"); _role_admin_c.hty_role_id } @@ -91,7 +93,8 @@ pub fn insert_tester_role(app_id: &String, conn: &mut PgConnection) -> String { role_name: None, }; - let created_role_tester = HtyRole::create(&role_tester, conn).unwrap(); + let created_role_tester = HtyRole::create(&role_tester, conn) + .expect("Failed to create tester role"); let tester_app_role = AppRole { @@ -174,17 +177,24 @@ pub fn insert_tester_label(conn: &mut PgConnection, role_id: &String) { pub fn insert_ts_app(conn: &mut PgConnection, tag_id: &String) -> HtyApp { info!("insert task server app..."); - let app_key_pair = generate_cert_key_pair().unwrap(); + let app_key_pair = generate_cert_key_pair() + .expect("Failed to generate cert key pair"); let app_id = uuid(); + let pubkey = app_key_pair.pubkey + .ok_or_else(|| anyhow::anyhow!("pubkey is missing")) + .expect("pubkey is required"); + let privkey = app_key_pair.privkey + .ok_or_else(|| anyhow::anyhow!("privkey is missing")) + .expect("privkey is required"); let ts_app = HtyApp { app_id: app_id.clone(), wx_secret: Some("".to_string()), domain: env_var("TS_DOMAIN"), app_desc: Some("task server app".to_string()), app_status: APP_STATUS_ACTIVE.to_string(), - pubkey: Some(app_key_pair.pubkey.unwrap()), - privkey: Some(app_key_pair.privkey.unwrap()), + pubkey: Some(pubkey), + privkey: Some(privkey), wx_id: None, is_wx_app: Some(false), }; @@ -245,15 +255,16 @@ pub fn insert_wx_gongzhonghao(conn: &mut PgConnection) -> HtyApp { info!("insert wx mp app..."); - let app_key_pair = generate_cert_key_pair().unwrap(); + let app_key_pair = generate_cert_key_pair() + .expect("Failed to generate cert key pair for wx mp app"); let wx_mp_app = HtyApp { app_id: uuid(), domain: env_var("WX_MP_DOMAIN"), app_desc: Some("微信公众号APP,用于记录公众号信息".to_string()), app_status: APP_STATUS_ACTIVE.to_string().clone(), - pubkey: Some(app_key_pair.pubkey.unwrap()), - privkey: Some(app_key_pair.privkey.unwrap()), + pubkey: app_key_pair.pubkey.clone(), + privkey: app_key_pair.privkey.clone(), wx_id: env_var("WX_MP_ID"), wx_secret: env_var("WX_MP_SECRET"), is_wx_app: Some(true), @@ -266,15 +277,16 @@ pub fn insert_wx_gongzhonghao(conn: &mut PgConnection) -> HtyApp { pub fn insert_root_app(conn: &mut PgConnection) -> HtyApp { info!("insert root app..."); - let app_key_pair = generate_cert_key_pair().unwrap(); + let app_key_pair = generate_cert_key_pair() + .expect("Failed to generate cert key pair for root app"); let root_app = HtyApp { app_id: uuid(), domain: Some("root".to_string()), app_desc: Some("virtual root app".to_string()), app_status: APP_STATUS_ACTIVE.to_string().clone(), - pubkey: Some(app_key_pair.pubkey.unwrap()), - privkey: Some(app_key_pair.privkey.unwrap()), + pubkey: app_key_pair.pubkey.clone(), + privkey: app_key_pair.privkey.clone(), wx_id: None, wx_secret: Some("default secret".to_string()), is_wx_app: Some(false), @@ -317,10 +329,14 @@ pub fn insert_root_user(app_id: &String, role_id: &String, conn: &mut PgConnecti }; debug!("insert root user app_id -> {}", app_id.clone()); - debug!("insert root user info -> app_id: {}, hty_id: {}", root_user_info.app_id.as_ref().unwrap().clone(), root_id.clone()); + let app_id_str = root_user_info.app_id.as_ref() + .map(|id| id.clone()) + .unwrap_or_else(|| "unknown".to_string()); + debug!("insert root user info -> app_id: {}, hty_id: {}", app_id_str, root_id.clone()); pass_or_panic2(HtyUser::create_with_info(&root_user, &Some(root_user_info), conn)); - let user_info = UserAppInfo::find_by_hty_id_and_app_id(&root_id, &app_id, conn).unwrap(); + let user_info = UserAppInfo::find_by_hty_id_and_app_id(&root_id, &app_id, conn) + .expect("Failed to find user info"); let user_info_role = UserInfoRole { the_id: uuid(), user_info_id: user_info.id.clone(), @@ -335,15 +351,16 @@ pub fn insert_root_user(app_id: &String, role_id: &String, conn: &mut PgConnecti pub fn insert_admin_app(conn: &mut PgConnection) -> HtyApp { info!("insert admin app..."); - let app_key_pair = generate_cert_key_pair().unwrap(); + let app_key_pair = generate_cert_key_pair() + .expect("Failed to generate cert key pair for admin app"); let admin_app = HtyApp { app_id: uuid(), domain: env_var("ADMIN_DOMAIN"), app_desc: Some("admin system".to_string()), app_status: APP_STATUS_ACTIVE.to_string().clone(), - pubkey: Some(app_key_pair.pubkey.unwrap()), - privkey: Some(app_key_pair.privkey.unwrap()), + pubkey: app_key_pair.pubkey.clone(), + privkey: app_key_pair.privkey.clone(), wx_id: None, wx_secret: Some("default secret".to_string()), is_wx_app: Some(false), @@ -386,7 +403,9 @@ pub fn insert_admin_user(app_id: &String, role_id: &String, conn: &mut PgConnect }; debug!("insert admin user app_id -> {}", app_id.clone()); - debug!("insert admin user app_id user info -> {}", admin_user_info.app_id.as_ref().unwrap().clone()); + if let Some(app_id_ref) = admin_user_info.app_id.as_ref() { + debug!("insert admin user app_id user info -> {}", app_id_ref.clone()); + } info!("creating admin user..."); @@ -395,7 +414,8 @@ pub fn insert_admin_user(app_id: &String, role_id: &String, conn: &mut PgConnect &Some(admin_user_info), conn, )); - let user_info = UserAppInfo::find_by_hty_id_and_app_id(&id_admin, &app_id, conn).unwrap(); + let user_info = UserAppInfo::find_by_hty_id_and_app_id(&id_admin, &app_id, conn) + .expect("Failed to find admin user info after creation"); let user_info_role = UserInfoRole { the_id: uuid(), user_info_id: user_info.id.clone(), @@ -487,12 +507,13 @@ pub fn insert_music_room_teacher(app_id: &String, role_id: Option<&String>, conn info!("creating teacher moicen for music room..."); pass_or_panic2(HtyUser::create_with_info(&teacher, &Some(teacher_app_info), conn)); - if role_id.is_some() { - let user_info = UserAppInfo::find_by_hty_id_and_app_id(&teacher.hty_id.clone(), &app_id, conn).unwrap(); + if let Some(role_id_val) = role_id { + let user_info = UserAppInfo::find_by_hty_id_and_app_id(&teacher.hty_id.clone(), &app_id, conn) + .expect("Failed to find user info"); let user_info_role = UserInfoRole { the_id: uuid(), user_info_id: user_info.id.clone(), - role_id: role_id.unwrap().clone(), + role_id: role_id_val.clone(), }; UserInfoRole::create(&user_info_role, conn).ok(); } @@ -531,7 +552,8 @@ pub fn insert_music_room_student(app_id: &String, role_id: &String, real_name: S info!("creating student {}...", real_name); pass_or_panic2(HtyUser::create_with_info(&student_user, &Some(student_user_info), conn)); - let user_info = UserAppInfo::find_by_hty_id_and_app_id(&student_user.hty_id.clone(), &app_id.clone(), conn).unwrap(); + let user_info = UserAppInfo::find_by_hty_id_and_app_id(&student_user.hty_id.clone(), &app_id.clone(), conn) + .expect("Failed to find student user info after creation"); let user_info_role = UserInfoRole { the_id: uuid(), user_info_id: user_info.id.clone(), @@ -575,7 +597,9 @@ pub fn insert_role_tester_user(app_id: &String, role_id: &String, conn: &mut PgC }; debug!("insert tester user app_id -> {}", app_id.clone()); - debug!("insert tester user app_id user info -> {}", tester_user_info.app_id.as_ref().unwrap().clone()); + if let Some(app_id_ref) = tester_user_info.app_id.as_ref() { + debug!("insert tester user app_id user info -> {}", app_id_ref.clone()); + } info!("creating tester user..."); @@ -584,7 +608,8 @@ pub fn insert_role_tester_user(app_id: &String, role_id: &String, conn: &mut PgC &Some(tester_user_info), conn, )); - let user_info = UserAppInfo::find_by_hty_id_and_app_id(&id_tester, &app_id, conn).unwrap(); + let user_info = UserAppInfo::find_by_hty_id_and_app_id(&id_tester, &app_id, conn) + .expect("Failed to find tester user info after creation"); let user_info_role = UserInfoRole { the_id: uuid(), user_info_id: user_info.id.clone(), diff --git a/htyuc/src/lib.rs b/htyuc/src/lib.rs index b528f06..feb6568 100644 --- a/htyuc/src/lib.rs +++ b/htyuc/src/lib.rs @@ -38,7 +38,7 @@ use htycommons::models::*; pub mod ddl; pub mod r_uc; mod notifications; -pub mod test_scaffold; + // pub mod wx; @@ -99,26 +99,28 @@ async fn save_cached_kv(_sudoer: HtySudoerTokenHeader, fn raw_save_cached_kv(in_kv: &ReqKV) -> anyhow::Result<()> { let c_in_kv = in_kv.clone(); + let key = c_in_kv.key.ok_or_else(|| anyhow::anyhow!("key is required"))?; + let val = c_in_kv.val.ok_or_else(|| anyhow::anyhow!("val is required"))?; let mut prefix_key = CACHED.to_string(); - prefix_key.push_str(c_in_kv.key.unwrap().clone().as_str()); + prefix_key.push_str(key.as_str()); - if in_kv.exp_unit.is_some() { - match in_kv.exp_unit.clone().unwrap() { + if let Some(exp_unit) = in_kv.exp_unit.clone() { + match exp_unit { TimeUnit::SECOND => { - save_kv_to_redis_with_exp_secs(&prefix_key, &c_in_kv.val.unwrap(), c_in_kv.exp.unwrap_or(7) as usize) // default 7 seconds. + save_kv_to_redis_with_exp_secs(&prefix_key, &val, c_in_kv.exp.unwrap_or(7) as usize) // default 7 seconds. } TimeUnit::MINUTE => { - save_kv_to_redis_with_exp_minutes(&prefix_key, &c_in_kv.val.unwrap(), c_in_kv.exp.unwrap_or(7) as usize) // default 7 minutes. + save_kv_to_redis_with_exp_minutes(&prefix_key, &val, c_in_kv.exp.unwrap_or(7) as usize) // default 7 minutes. } TimeUnit::HOUR => { - save_kv_to_redis_with_exp_hours(&prefix_key, &c_in_kv.val.unwrap(), c_in_kv.exp.unwrap_or(7) as usize) // default 7 hours. + save_kv_to_redis_with_exp_hours(&prefix_key, &val, c_in_kv.exp.unwrap_or(7) as usize) // default 7 hours. } TimeUnit::DAY => { - save_kv_to_redis_with_exp_days(&prefix_key, &c_in_kv.val.unwrap(), c_in_kv.exp.unwrap_or(7) as usize) // default 7 days. + save_kv_to_redis_with_exp_days(&prefix_key, &val, c_in_kv.exp.unwrap_or(7) as usize) // default 7 days. } } } else { - save_kv_to_redis_with_exp_days(&prefix_key, &c_in_kv.val.unwrap(), c_in_kv.exp.unwrap_or(7) as usize) // default 7 days. + save_kv_to_redis_with_exp_days(&prefix_key, &val, c_in_kv.exp.unwrap_or(7) as usize) // default 7 days. } } @@ -179,16 +181,28 @@ async fn find_hty_template_with_data_by_key_and_app_id( let id_app = get_some_from_query_params::("app_id", ¶ms); let key_template = get_some_from_query_params::("template_key", ¶ms); - if id_app.is_none() || key_template.is_none() { - return wrap_json_hty_err::>(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("id_app or key_template is none".into()), - }); - } + let id_app_val = match id_app { + Some(val) => val, + None => { + return wrap_json_hty_err::>(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("id_app is required".into()), + }); + } + }; + let key_template_val = match key_template { + Some(val) => val, + None => { + return wrap_json_hty_err::>(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("key_template is required".into()), + }); + } + }; match raw_find_hty_template_with_data_by_key_and_app_id( - &id_app.unwrap(), - &key_template.unwrap(), + &id_app_val, + &key_template_val, extract_conn(conn).deref_mut(), ) { Ok(resp) => { @@ -409,16 +423,28 @@ async fn count_unread_tongzhis_by_user_id_and_role_id( let id_user = get_some_from_query_params::("user_id", ¶ms); let id_role = get_some_from_query_params::("role_id", ¶ms); - if id_user.is_none() || id_user.is_none() { - return wrap_json_hty_err::(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("id_user or id_user or score_val is none".into()), - }); - } + let id_user_val = match id_user { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("id_user is required".into()), + }); + } + }; + let id_role_val = match id_role { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("id_role is required".into()), + }); + } + }; match raw_count_unread_tongzhis_by_user_id_and_role_id( - &id_user.clone().unwrap(), - &id_role.clone().unwrap(), + &id_user_val, + &id_role_val, extract_conn(conn).deref_mut(), ) { Ok(resp) => { @@ -455,16 +481,28 @@ async fn clear_all_unread_tongzhis_by_user_id_and_role_id( id_role, id_user ); - if id_role.is_none() || id_user.is_none() { - return wrap_json_hty_err::(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("user_id or role_id is none".into()), - }); - } + let id_user_val = match id_user { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("user_id is required".into()), + }); + } + }; + let id_role_val = match id_role { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_id is required".into()), + }); + } + }; match raw_clear_all_unread_tongzhis_by_user_id_and_role_id( - &id_user.clone().unwrap(), - &id_role.clone().unwrap(), + &id_user_val, + &id_role_val, extract_conn(conn).deref_mut(), ) { Ok(resp) => { @@ -508,17 +546,38 @@ async fn delete_all_tongzhis_by_status_and_role_id_and_user_id( debug!("delete_all_tongzhis_by_status_and_role_id_and_user_id -> tongzhi_status: {:?} / id_role: {:?} / id_user: {:?}", tongzhi_status, id_role, id_user); - if tongzhi_status.is_none() || id_role.is_none() || id_user.is_none() { - return wrap_json_hty_err::(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("status or user_id or role_id is none".into()), - }); - } + let tongzhi_status_val = match tongzhi_status { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("tongzhi_status is required".into()), + }); + } + }; + let id_role_val = match id_role { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_id is required".into()), + }); + } + }; + let id_user_val = match id_user { + Some(val) => val, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("user_id is required".into()), + }); + } + }; match raw_delete_all_tongzhis_by_status_and_role_id_and_user_id( - &id_role.clone().unwrap(), - &id_user.clone().unwrap(), - &tongzhi_status.clone().unwrap(), + &id_role_val, + &id_user_val, + &tongzhi_status_val, extract_conn(conn).deref_mut(), ) { Ok(resp) => { @@ -816,20 +875,24 @@ fn raw_bulk_update_tag_ref( req_tag_refs_by_ref_id: ReqTagRefsByRefId, db_pool: Arc, ) -> anyhow::Result { - let ref_id = req_tag_refs_by_ref_id.ref_id.clone().unwrap(); + let ref_id = req_tag_refs_by_ref_id.ref_id.clone() + .ok_or_else(|| anyhow::anyhow!("ref_id is required"))?; let cloned_req_tag_refs = req_tag_refs_by_ref_id.tag_refs.clone().unwrap_or(Vec::new()); // 将数据序列化传递给闭包 let mut params = HashMap::new(); - params.insert("ref_id".to_string(), ref_id); + params.insert("ref_id".to_string(), ref_id.clone()); params.insert("tag_refs".to_string(), serde_json::to_string(&cloned_req_tag_refs)?); let task_update = |in_params: Option>, conn: &mut PgConnection| -> anyhow::Result> { - let params = in_params.unwrap(); - let ref_id = params.get("ref_id").unwrap().clone(); - let tag_refs_json = params.get("tag_refs").unwrap(); + let params = in_params.ok_or_else(|| anyhow::anyhow!("params is required"))?; + let ref_id = params.get("ref_id") + .ok_or_else(|| anyhow::anyhow!("ref_id not found in params"))? + .clone(); + let tag_refs_json = params.get("tag_refs") + .ok_or_else(|| anyhow::anyhow!("tag_refs not found in params"))?; let cloned_req_tag_refs: Vec = serde_json::from_str(tag_refs_json)?; let _ = HtyTagRef::delete_all_by_ref_id(&ref_id, conn)?; @@ -843,11 +906,15 @@ fn raw_bulk_update_tag_ref( })); } let new_id = uuid(); + let hty_tag_id = req_tag_ref.hty_tag_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_tag_id is required"))?; + let ref_type = req_tag_ref.ref_type.clone() + .ok_or_else(|| anyhow::anyhow!("ref_type is required"))?; let db_tag_ref = HtyTagRef { the_id: new_id.clone(), - hty_tag_id: req_tag_ref.hty_tag_id.clone().unwrap(), + hty_tag_id, ref_id: ref_id.clone(), - ref_type: req_tag_ref.ref_type.clone().unwrap(), + ref_type, meta: req_tag_ref.meta.clone(), }; let _ = HtyTagRef::create(&db_tag_ref, conn)?; @@ -974,35 +1041,17 @@ async fn find_all_tongzhis_with_page( let mut the_role_id = None; let mut the_hty_id = None; - if params.get("tongzhi_status").is_some() { + if let Some(status_str) = params.get("tongzhi_status") { // READ / UNREAD - the_tongzhi_status = Some( - params - .get("tongzhi_status") - .unwrap() - .parse::() - .unwrap_or_default(), - ); + the_tongzhi_status = Some(status_str.parse::().unwrap_or_default()); } - if params.get("role_id").is_some() { - the_role_id = Some( - params - .get("role_id") - .unwrap() - .parse::() - .unwrap_or_default(), - ); + if let Some(role_id_str) = params.get("role_id") { + the_role_id = Some(role_id_str.parse::().unwrap_or_default()); } - if params.get("hty_id").is_some() { - the_hty_id = Some( - params - .get("hty_id") - .unwrap() - .parse::() - .unwrap_or_default(), - ); + if let Some(hty_id_str) = params.get("hty_id") { + the_hty_id = Some(hty_id_str.parse::().unwrap_or_default()); } match raw_find_tongzhis( @@ -1046,25 +1095,13 @@ async fn find_tongzhis( } } - if params.get("tongzhi_status").is_some() { + if let Some(status_str) = params.get("tongzhi_status") { // READ / UNREAD - the_tongzhi_status = Some( - params - .get("tongzhi_status") - .unwrap() - .parse::() - .unwrap_or_default(), - ); + the_tongzhi_status = Some(status_str.parse::().unwrap_or_default()); } - if params.get("role_id").is_some() { - the_role_id = Some( - params - .get("role_id") - .unwrap() - .parse::() - .unwrap_or_default(), - ); + if let Some(role_id_str) = params.get("role_id") { + the_role_id = Some(role_id_str.parse::().unwrap_or_default()); } match raw_find_tongzhis( @@ -1158,27 +1195,25 @@ async fn create_or_update_tags( } fn raw_create_or_update_tags(req_tag: ReqHtyTag, db_pool: Arc) -> anyhow::Result<()> { - if !req_tag.tag_id.is_none() { - let id_tag = req_tag.tag_id.clone().unwrap(); + if let Some(id_tag) = req_tag.tag_id.clone() { let mut db_tag = HtyTag::find_by_tag_id(&id_tag, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; - if req_tag.tag_name.is_some() { - db_tag.tag_name = req_tag.tag_name.clone().unwrap(); + if let Some(tag_name) = req_tag.tag_name.clone() { + db_tag.tag_name = tag_name; } db_tag.tag_desc = req_tag.tag_desc.clone(); db_tag.style = req_tag.style.clone(); let _ = HtyTag::update(&db_tag, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; return Ok(()); } - if req_tag.tag_name.is_none() { - return Err(anyhow!(HtyErr { + let tag_name = req_tag.tag_name.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, reason: Some("for create flow, tag_name can not be none".into()) - })); - } + }))?; let db_tag = HtyTag { tag_id: uuid(), - tag_name: req_tag.tag_name.clone().unwrap(), + tag_name, tag_desc: req_tag.tag_desc.clone(), style: req_tag.style.clone(), }; @@ -1205,17 +1240,21 @@ async fn create_tag_ref( } fn raw_create_tag_ref(req_tag_ref: ReqHtyTagRef, db_pool: Arc) -> anyhow::Result { - if req_tag_ref.hty_tag_id.is_none() - || req_tag_ref.ref_id.is_none() - || req_tag_ref.ref_type.is_none() - { - return Err(anyhow!(HtyErr { + let tag_id = req_tag_ref.hty_tag_id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("hty_tag_id or ref_id or ref_type is none".into()) - })); - } - let tag_id = req_tag_ref.hty_tag_id.clone().unwrap(); - let ref_id = req_tag_ref.ref_id.clone().unwrap(); + reason: Some("hty_tag_id is required".into()) + }))?; + let ref_id = req_tag_ref.ref_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("ref_id is required".into()) + }))?; + let ref_type = req_tag_ref.ref_type.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("ref_type is required".into()) + }))?; let duplicate_check = HtyTagRef::verify_exist_by_ref_id_and_tag_id( &tag_id, &ref_id, @@ -1229,9 +1268,9 @@ fn raw_create_tag_ref(req_tag_ref: ReqHtyTagRef, db_pool: Arc) -> anyho } let db_tag_ref = HtyTagRef { the_id: uuid(), - hty_tag_id: req_tag_ref.hty_tag_id.clone().unwrap(), - ref_id: req_tag_ref.ref_id.clone().unwrap(), - ref_type: req_tag_ref.ref_type.clone().unwrap(), + hty_tag_id: tag_id.clone(), + ref_id: ref_id.clone(), + ref_type: ref_type.clone(), meta: req_tag_ref.meta.clone(), }; let res = HtyTagRef::create( @@ -1263,7 +1302,8 @@ fn raw_find_all_tags(db_pool: Arc) -> anyhow::Result> { let tags = HtyTag::find_all(extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; let req_tags: Vec = tags.into_iter().map(|tag| tag.to_req()).collect(); for mut req_tag in req_tags { - let id_tag = req_tag.tag_id.clone().unwrap(); + let id_tag = req_tag.tag_id.clone() + .ok_or_else(|| anyhow::anyhow!("tag_id is required"))?; let tag_refs = HtyTagRef::find_all_by_tag_id( &id_tag, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), @@ -1449,11 +1489,15 @@ async fn raw_register_verify( let register_verify_copy = register_verify.clone(); - let in_app = HtyApp::find_by_id(®ister_verify.clone().app_id.unwrap(), + let app_id = register_verify.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let in_app = HtyApp::find_by_id(&app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; debug!("raw_register_verify -> in_app: {:?}", in_app); - let user_id = register_verify_copy.hty_id.unwrap(); - let verified = register_verify_copy.validate.unwrap(); + let user_id = register_verify_copy.hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; + let verified = register_verify_copy.validate.clone() + .ok_or_else(|| anyhow::anyhow!("validate is required"))?; let mut user_info = UserAppInfo::find_by_hty_id_and_app_id( &user_id, @@ -1523,35 +1567,37 @@ async fn raw_register( let in_unionid = register_info.clone().unionid; - debug!( - "raw_register -> in_unionid -> {:?} / is_none? {:?} / is_empty? {:?}", - &in_unionid, - &in_unionid.is_none(), - &in_unionid.clone().unwrap().trim().is_empty() - ); - if in_unionid.is_none() || in_unionid.clone().unwrap().trim().is_empty() { - let msg = format!("注册信息里面没有用户小程序UNIONID / {:?}", ®ister_info); - debug!("raw_register -> NO UNIONID -> {:?}", msg); - return Err(anyhow!(HtyErr { - code: HtyErrCode::WebErr, - reason: Some(msg), - })); - } + let unionid_str = match in_unionid.clone() { + Some(u) if !u.trim().is_empty() => u, + _ => { + let msg = format!("注册信息里面没有用户小程序UNIONID / {:?}", ®ister_info); + debug!("raw_register -> NO UNIONID -> {:?}", msg); + return Err(anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some(msg), + })); + } + }; let in_openid = register_info.clone().openid; debug!("raw_register -> in_openid -> {:?}", &in_openid,); - if in_openid.is_none() || in_openid.unwrap().trim().is_empty() { - let msg = format!("注册信息里面没有用户小程序OPENID / {:?}", ®ister_info); - debug!("raw_register -> NO OPENID -> {:?}", msg); - return Err(anyhow!(HtyErr { - code: HtyErrCode::WebErr, - reason: Some(msg), - })); - } + match in_openid.clone() { + Some(o) if !o.trim().is_empty() => { + // openid is valid, continue + } + _ => { + let msg = format!("注册信息里面没有用户小程序OPENID / {:?}", ®ister_info); + debug!("raw_register -> NO OPENID -> {:?}", msg); + return Err(anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some(msg), + })); + } + }; match HtyUser::find_by_union_id( - &in_unionid.clone().unwrap(), + &unionid_str, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(user) => { @@ -1774,7 +1820,7 @@ async fn raw_register( } fn do_post_registration(to_app_id: &String, user_id: &String) { - if skip_post_registration() { + if skip_post_registration().unwrap_or(false) { debug!("do_post_registration ::BY_PASSED::"); } else { let to_app_id_copy = to_app_id.clone(); @@ -1797,7 +1843,13 @@ fn do_post_registration(to_app_id: &String, user_id: &String) { &req_struct ); - let body = serde_json::to_string::(&req_struct).unwrap(); + let body = match serde_json::to_string::(&req_struct) { + Ok(b) => b, + Err(e) => { + error!("Failed to serialize request: {}", e); + return; + } + }; debug!( "raw_register -> update_official_account_openid -> body: {:?}", @@ -1884,13 +1936,11 @@ async fn raw_update_hty_gonggao( db_pool: Arc, ) -> anyhow::Result<()> { debug!("start raw_update_tongzhi_status_by_id"); - if req_gonggao.id.is_none() { - return Err(anyhow!(HtyErr { + let gonggao_id = req_gonggao.id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("id is none".into()) - })); - } - let gonggao_id = req_gonggao.id.clone().unwrap(); + reason: Some("id is required".into()) + }))?; let mut gonggao = HtyGongGao::find_by_id( &gonggao_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), @@ -1913,8 +1963,24 @@ async fn update_tongzhi_status_by_id( debug!("update_tongzhi_status_by_id -> starts"); debug!("update_tongzhi_status_by_id -> req_body {:?}", &req_body); - let the_tongzhi_id = req_body.0.tongzhi_id.unwrap(); - let the_tongzhi_status = req_body.0.tongzhi_status.unwrap(); + let the_tongzhi_id = match req_body.0.tongzhi_id.clone() { + Some(id) => id, + None => { + return wrap_json_hty_err::<()>(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("tongzhi_id is required".into()), + }); + } + }; + let the_tongzhi_status = match req_body.0.tongzhi_status.clone() { + Some(status) => status, + None => { + return wrap_json_hty_err::<()>(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("tongzhi_status is required".into()), + }); + } + }; match raw_update_tongzhi_status_by_id(&the_tongzhi_id, &the_tongzhi_status, db_conn, db_pool) .await @@ -1980,13 +2046,16 @@ async fn raw_update_official_account_openid( db_pool: Arc, ) -> anyhow::Result<()> { debug!("start raw_update_official_account_openid"); - let id_user = req_user.hty_id.clone().unwrap(); - let id_app = req_user.app_id.clone().unwrap(); + let id_user = req_user.hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; + let id_app = req_user.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; let to_app = HtyApp::find_by_id(&id_app, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; let in_user = HtyUser::find_by_hty_id(&id_user, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; - let id_union = in_user.union_id.clone().unwrap(); + let id_union = in_user.union_id.clone() + .ok_or_else(|| anyhow::anyhow!("union_id is required"))?; let _ = refresh_cache_and_get_wx_all_follower_openids(&to_app).await?; @@ -2057,7 +2126,8 @@ async fn raw_register_rollback( _db_conn: db::DbConn, db_pool: Arc, ) -> anyhow::Result<()> { - let hty_id = rollback_info.hty_id.unwrap(); + let hty_id = rollback_info.hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; let infos = rollback_info.infos.clone(); let task_delete = move |_in_params: Option>, @@ -2066,19 +2136,27 @@ async fn raw_register_rollback( // let _ = UserInfoRole::delete_by_id(&id3, extract_conn(conn).deref_mut()); // let _ = UserAppInfo::delete(&id2, extract_conn(conn).deref_mut()); let _ = HtyUser::delete_by_hty_id(&hty_id, conn)?; - for info in infos.clone().unwrap() { - let info_id = info.id.clone().unwrap(); - let roles = info.roles.clone().unwrap(); - for role in roles { - let role_copy = role.clone(); - let rel = UserInfoRole::find_by_role_id_and_user_info_id( - &role_copy.hty_role_id.unwrap(), - &role_copy.user_app_info_id.unwrap(), - conn, - )?; - let _ = UserInfoRole::delete_by_id(&rel.the_id, conn); + if let Some(infos_vec) = infos.clone() { + for info in infos_vec { + let info_id = info.id.clone() + .ok_or_else(|| anyhow::anyhow!("info.id is required"))?; + let roles = info.roles.clone() + .ok_or_else(|| anyhow::anyhow!("info.roles is required"))?; + for role in roles { + let role_copy = role.clone(); + let hty_role_id = role_copy.hty_role_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_role_id is required"))?; + let user_app_info_id = role_copy.user_app_info_id.clone() + .ok_or_else(|| anyhow::anyhow!("user_app_info_id is required"))?; + let rel = UserInfoRole::find_by_role_id_and_user_info_id( + &hty_role_id, + &user_app_info_id, + conn, + )?; + let _ = UserInfoRole::delete_by_id(&rel.the_id, conn); + } + let _ = UserAppInfo::delete(&info_id, conn); } - let _ = UserAppInfo::delete(&info_id, conn); } Ok(()) }; @@ -2209,8 +2287,10 @@ async fn raw_create_hty_resource( format!("raw_create_hty_resource -> token / #{:?}", token.clone()).as_str(), ); + let hty_id = token.hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; match HtyUser::find_by_hty_id( - &token.hty_id.clone().unwrap()[..], + &hty_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(user) => { @@ -2299,18 +2379,26 @@ fn raw_update_user_group( req_user_group: &ReqHtyUserGroup, db_pool: Arc, ) -> anyhow::Result<()> { - if req_user_group.app_id.is_none() - || req_user_group.group_type.is_none() - || req_user_group.group_name.is_none() - || req_user_group.id.is_none() - { - return Err(anyhow!(HtyErr { + let id_user_group = req_user_group.id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("app_id or group_type or group_name or id is none".into()), - })); - }; - - let id_user_group = req_user_group.id.clone().unwrap(); + reason: Some("id is required".into()), + }))?; + let app_id = req_user_group.app_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("app_id is required".into()), + }))?; + let group_type = req_user_group.group_type.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("group_type is required".into()), + }))?; + let group_name = req_user_group.group_name.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("group_name is required".into()), + }))?; let mut db_user_group = HtyUserGroup::find_by_id( &id_user_group, @@ -2321,9 +2409,9 @@ fn raw_update_user_group( db_user_group.users = req_user_group.users.clone(); } - db_user_group.group_type = req_user_group.group_type.clone().unwrap(); - db_user_group.app_id = req_user_group.app_id.clone().unwrap(); - db_user_group.group_name = req_user_group.group_name.clone().unwrap(); + db_user_group.group_type = group_type; + db_user_group.app_id = app_id; + db_user_group.group_name = group_name; db_user_group.group_desc = req_user_group.group_desc.clone(); db_user_group.parent_id = req_user_group.parent_id.clone(); db_user_group.owners = req_user_group.owners.clone(); @@ -2369,12 +2457,16 @@ fn raw_create_user_group( _auth: AuthorizationHeader, db_pool: Arc, ) -> anyhow::Result { - if req_user_group.group_type.is_none() || req_user_group.group_name.is_none() { - return Err(anyhow!(HtyErr { + let group_type = req_user_group.group_type.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("group_type or group_name is none".into()), - })); - }; + reason: Some("group_type is required".into()), + }))?; + let group_name = req_user_group.group_name.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("group_name is required".into()), + }))?; // let id_user = jwt_decode_token(&(*auth).clone())?.hty_id.unwrap(); let in_app = get_app_from_host( (*host).clone(), @@ -2383,11 +2475,11 @@ fn raw_create_user_group( let in_user_group = HtyUserGroup { id: uuid(), users: req_user_group.users.clone(), - group_type: req_user_group.group_type.clone().unwrap(), + group_type, created_at: Some(current_local_datetime()), created_by: req_user_group.created_by.clone(), app_id: in_app.app_id, - group_name: req_user_group.group_name.clone().unwrap(), + group_name, is_delete: false, group_desc: req_user_group.group_desc.clone(), parent_id: req_user_group.parent_id.clone(), @@ -2429,22 +2521,20 @@ fn raw_update_template_data( req_template_data: &ReqHtyTemplateData, db_pool: Arc, ) -> anyhow::Result { - if req_template_data.id.is_none() { - return Err(anyhow!(HtyErr { + let id_template_data = req_template_data.id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("id is none".into()), - })); - }; - let id_template_data = req_template_data.id.clone().unwrap(); + reason: Some("id is required".into()), + }))?; let mut db_template_data = HtyTemplateData::find_by_id( &id_template_data, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; - if req_template_data.template_id.is_some() { - db_template_data.template_id = req_template_data.template_id.clone().unwrap(); + if let Some(template_id) = req_template_data.template_id.clone() { + db_template_data.template_id = template_id; } - if req_template_data.app_id.is_some() { - db_template_data.app_id = req_template_data.app_id.clone().unwrap(); + if let Some(app_id) = req_template_data.app_id.clone() { + db_template_data.app_id = app_id; } db_template_data.template_val = req_template_data.template_val.clone(); db_template_data.template_text = req_template_data.template_text.clone(); @@ -2478,19 +2568,17 @@ fn raw_update_template( req_template: &ReqHtyTemplate, db_pool: Arc, ) -> anyhow::Result { - if req_template.id.is_none() { - return Err(anyhow!(HtyErr { + let id_template = req_template.id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("id is none".into()), - })); - }; - let id_template = req_template.id.clone().unwrap(); + reason: Some("id is required".into()), + }))?; let mut db_template = HtyTemplate::find_by_id( &id_template, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; - if req_template.template_key.is_some() { - db_template.template_key = req_template.template_key.clone().unwrap(); + if let Some(template_key) = req_template.template_key.clone() { + db_template.template_key = template_key; } db_template.template_desc = req_template.template_desc.clone(); let _ = HtyTemplate::update( @@ -2531,17 +2619,23 @@ fn raw_create_template_data( auth: AuthorizationHeader, db_pool: Arc, ) -> anyhow::Result { - if req_template_data.app_id.is_none() || req_template_data.template_id.is_none() { - return Err(anyhow!(HtyErr { + let app_id = req_template_data.app_id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("app_id or template_id is none".into()), - })); - }; - let id_user = jwt_decode_token(&(*auth).clone())?.hty_id.unwrap(); + reason: Some("app_id is required".into()), + }))?; + let template_id = req_template_data.template_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("template_id is required".into()), + }))?; + let id_user = jwt_decode_token(&(*auth).clone())? + .hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; let in_template_data = HtyTemplateData { id: uuid(), - app_id: req_template_data.app_id.clone().unwrap(), - template_id: req_template_data.template_id.clone().unwrap(), + app_id, + template_id, template_val: req_template_data.template_val.clone(), template_text: req_template_data.template_text.clone(), created_at: current_local_datetime(), @@ -2584,10 +2678,17 @@ fn raw_create_template( reason: Some("template_key is none".into()), })); }; - let id_user = jwt_decode_token(&(*auth).clone())?.hty_id.unwrap(); + let id_user = jwt_decode_token(&(*auth).clone())? + .hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; + let template_key = req_template.template_key.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("template_key is required".into()), + }))?; let in_template = HtyTemplate { id: uuid(), - template_key: req_template.template_key.clone().unwrap(), + template_key, created_at: current_local_datetime(), created_by: id_user, template_desc: req_template.template_desc.clone(), @@ -2678,7 +2779,9 @@ fn get_all_db_tags_of_the_user(auth: AuthorizationHeader, host: HtyHostHeader, c let app = HtyApp::find_by_domain(&domain, conn)?; debug!("get_all_db_tags_of_the_user -> app: {:?}", app); - let id_user = jwt_decode_token(&(*auth).clone())?.hty_id.unwrap(); + let id_user = jwt_decode_token(&(*auth).clone())? + .hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; debug!("get_all_db_tags_of_the_user -> id_user: {:?}", id_user); let user_app_info = UserAppInfo::find_by_hty_id_and_app_id(&id_user, &app.app_id, conn)?; @@ -2732,7 +2835,9 @@ fn raw_get_user_groups_of_current_user( some_is_delete: &Option, db_pool: Arc, ) -> anyhow::Result> { - let id_user = jwt_decode_token(&(*auth).clone())?.hty_id.unwrap(); + let id_user = jwt_decode_token(&(*auth).clone())? + .hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; debug!("raw_get_user_groups_of_current_user -> find_by_created_by_or_users START: {:?}", current_local_datetime()); let res = HtyUserGroup::find_by_created_by_or_users( @@ -2767,7 +2872,8 @@ async fn raw_delete_hty_resource_by_id(id_hty_resource: String, sudoer: HtySudoe debug!("raw_delete_hty_resource_by_id -> hty_resource: {:?}", hty_resource); // if hty_resource.url.is_some() { - let filename = extract_filename_from_url(&hty_resource.url); + let filename = extract_filename_from_url(&hty_resource.url) + .ok_or_else(|| anyhow::anyhow!("Failed to extract filename from URL: {}", hty_resource.url))?; debug!("raw_delete_hty_resource_by_id -> filename: {:?}", filename); let _ = upyun_delete_by_filename(&filename, &sudoer.0, &host.0).await?; // } @@ -2961,16 +3067,20 @@ fn raw_create_app_from_to( req_from_to: &ReqAppFromTo, conn: &mut PgConnection, ) -> anyhow::Result { - if req_from_to.from_app_id.is_none() || req_from_to.to_app_id.is_none() { - return Err(anyhow!(HtyErr { + let from_app_id = req_from_to.from_app_id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::WebErr, - reason: Some("from_app_id or to_app_id".into()), - })); - } + reason: Some("from_app_id is required".into()), + }))?; + let to_app_id = req_from_to.to_app_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("to_app_id is required".into()), + }))?; let in_from_to = AppFromTo { id: uuid(), - from_app_id: req_from_to.from_app_id.clone().unwrap(), - to_app_id: req_from_to.to_app_id.clone().unwrap(), + from_app_id, + to_app_id, is_enabled: true, }; let res = AppFromTo::create(&in_from_to, conn)?; @@ -3121,8 +3231,7 @@ fn verify_user_with_info( })); }; - if !info.is_none() { - let in_info = info.clone().unwrap(); + if let Some(in_info) = info.clone() { let in_app_id = match in_info.app_id { Some(app_id) => app_id, None => HtyApp::find_by_domain(&app_domain, conn)?.app_id, @@ -3198,12 +3307,12 @@ fn raw_create_or_update_user_with_info_tx( .clone(); let mut res_user_id = String::new(); let mut res_user_info_id = String::new(); - if !some_user.is_none() { - if !some_user.clone().unwrap().hty_id.is_none() { - let in_user = some_user.unwrap().to_hty_user()?; + if let Some(some_user_val) = some_user.clone() { + if some_user_val.hty_id.is_some() { + let in_user = some_user_val.to_hty_user()?; res_user_id = HtyUser::update(&in_user, conn)?.hty_id; } else { - let c_user = some_user.clone().unwrap(); + let c_user = some_user_val; let in_user = HtyUser { hty_id: uuid(), union_id: c_user.union_id, @@ -3218,12 +3327,12 @@ fn raw_create_or_update_user_with_info_tx( res_user_id = HtyUser::create(&in_user, conn)?.hty_id; } } - if !info.is_none() { - if !info.clone().unwrap().id.is_none() { - let in_info = info.clone().unwrap().to_user_app_info()?; + if let Some(info_val) = info.clone() { + if info_val.id.is_some() { + let in_info = info_val.to_user_app_info()?; res_user_info_id = UserAppInfo::update(&in_info, conn)?.id; } else { - let mut tem_hty_id = info.clone().unwrap().hty_id; + let mut tem_hty_id = info_val.hty_id.clone(); if tem_hty_id.is_none() { if res_user_id.is_empty() { return Err(anyhow!(HtyErr { @@ -3234,8 +3343,12 @@ fn raw_create_or_update_user_with_info_tx( tem_hty_id = Some(res_user_id.clone()); } - let c_info = info.clone().unwrap(); - let is_exist = UserAppInfo::verify_exist_by_app_id_and_hty_id(&tem_hty_id.clone().unwrap(), &c_info.app_id.clone().unwrap(), conn)?; + let c_info = info_val; + let hty_id_val = tem_hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required"))?; + let app_id_val = c_info.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let is_exist = UserAppInfo::verify_exist_by_app_id_and_hty_id(&hty_id_val, &app_id_val, conn)?; if is_exist { return Err(anyhow!(HtyErr { code: HtyErrCode::WebErr, @@ -3244,8 +3357,8 @@ fn raw_create_or_update_user_with_info_tx( } let in_info = UserAppInfo { - hty_id: tem_hty_id.unwrap(), - app_id: c_info.app_id, + hty_id: hty_id_val, + app_id: Some(app_id_val), openid: c_info.openid, is_registered: true, id: uuid(), @@ -3291,29 +3404,29 @@ fn verify_username( return Ok(()); } - let id_user; - if user.is_none() { - id_user = info.clone().unwrap().hty_id; + let id_user = if let Some(user_val) = user { + user_val.hty_id.clone() } else { - id_user = user.clone().unwrap().hty_id; - } + info.as_ref().and_then(|i| i.hty_id.clone()) + }; - let in_info = info.clone().unwrap(); + let in_info = info.as_ref() + .ok_or_else(|| anyhow::anyhow!("info is required"))?; let in_username = in_info.username.clone(); - if !in_username.is_none() { - if in_username.clone().unwrap() != "" { + if let Some(username) = in_username.clone() { + if !username.is_empty() { let res = UserAppInfo::verify_unique_username_by_app_id(&in_info.clone(), app_id, conn)?; if res { - if !id_user.is_none() { + if let Some(id_user_val) = id_user.clone() { // 如果和自己重名,则不是问题,此场景适用于update_user的username之时。 let my_info = UserAppInfo::find_by_username_and_app_id( - &in_username.clone().unwrap(), + &username, app_id, conn, )?; - if Some(my_info.hty_id) == id_user { + if Some(my_info.hty_id) == Some(id_user_val.clone()) { return Ok(()); } } else { @@ -3321,7 +3434,7 @@ fn verify_username( code: HtyErrCode::InternalErr, reason: Some(format!( "existing username -> {}", - &in_username.clone().unwrap() + &username )) })); } @@ -3351,7 +3464,9 @@ fn raw_update_needs_refresh_for_app( hty_app: &ReqHtyApp, conn: &mut PgConnection, ) -> anyhow::Result { - let in_app = HtyApp::find_by_id(&hty_app.app_id.clone().unwrap(), conn)?; + let app_id = hty_app.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let in_app = HtyApp::find_by_id(&app_id, conn)?; let needs_refresh = hty_app.needs_refresh.clone(); let all_infos = in_app.all_user_infos(conn)?; @@ -3391,12 +3506,11 @@ fn raw_create_or_update_apps_with_roles( mut hty_app: ReqHtyApp, conn: &mut PgConnection, ) -> anyhow::Result { - if hty_app.app_status.is_none() { - return Err(anyhow!(HtyErr { + let app_status = hty_app.app_status.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("app_status is none".into()), - })); - }; + reason: Some("app_status is required".into()), + }))?; let mut is_new_app = false; @@ -3405,12 +3519,13 @@ fn raw_create_or_update_apps_with_roles( is_new_app = true; } - let app_id = hty_app.app_id.clone().unwrap(); + let app_id = hty_app.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; let in_app = HtyApp { app_id: app_id.clone(), wx_secret: hty_app.wx_secret.clone(), domain: hty_app.domain.clone(), - app_status: hty_app.app_status.clone().unwrap(), + app_status, app_desc: hty_app.app_desc.clone(), pubkey: hty_app.pubkey.clone(), privkey: hty_app.privkey.clone(), @@ -3436,7 +3551,8 @@ fn raw_create_or_update_apps_with_roles( // 先删后增 // todo: 未来可能重构逻辑 let _ = AppRole::delete_all_by_app_id(&app_id, conn)?; - let roles = hty_app.role_ids.clone().unwrap(); + let roles = hty_app.role_ids.clone() + .ok_or_else(|| anyhow::anyhow!("role_ids is required"))?; for id_role in roles { let entry = AppRole { the_id: uuid(), @@ -3459,9 +3575,8 @@ async fn find_tongzhi_by_id( match raw_find_tongzhi_by_id(&tongzhi_id, extract_conn(conn).deref_mut()) { Ok(some_tz) => { - if some_tz.is_some() { - let req_tz = some_tz.unwrap().to_req(); - + if let Some(tz) = some_tz { + let req_tz = tz.to_req(); wrap_json_ok_resp(Some(req_tz)) } else { wrap_json_ok_resp(None) @@ -3606,35 +3721,41 @@ fn raw_create_or_update_userinfo_with_roles( ) -> anyhow::Result { let req_user_app_info = hty_user_app_info.clone(); let user_app_info = UserAppInfo::find_by_req_info(&req_user_app_info, conn)?; - if user_app_info.app_id.is_none() { - return Err(anyhow!(HtyErr { + let app_id = user_app_info.app_id.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("app id can not be none".into()), - })); - } - let app_roles: Vec = HtyApp::find_by_id(&user_app_info.app_id.clone().unwrap(), conn)? + reason: Some("app id is required".into()), + }))?; + let app_roles: Vec = HtyApp::find_by_id(&app_id, conn)? .find_linked_roles(conn)? .iter() .map(|role| role.clone().hty_role_id) .collect(); - if req_user_app_info.roles.is_some() { - let user_info_roles = req_user_app_info.roles.clone().unwrap(); - let user_info_role_ids: Vec = user_info_roles - .iter() - .map(|item| item.hty_role_id.clone().unwrap()) - .collect(); + if let Some(user_info_roles) = req_user_app_info.roles.clone() { + let mut user_info_role_ids: Vec = Vec::new(); for user_info_role in user_info_roles.clone() { - if !app_roles.contains(&user_info_role.hty_role_id.clone().unwrap()) { + let hty_role_id = user_info_role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::InternalErr, + reason: Some("hty_role_id is required".into()), + }))?; + if !app_roles.contains(&hty_role_id) { return Err(anyhow!(HtyErr { code: HtyErrCode::InternalErr, reason: Some("There exist unsupported role in the request".into()), })); } + user_info_role_ids.push(hty_role_id.clone()); } for user_info_role in user_info_roles { + let hty_role_id = user_info_role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::InternalErr, + reason: Some("hty_role_id is required".into()), + }))?; match UserInfoRole::verify_exist_by_user_info_id_and_role_id( &user_app_info.id, - &user_info_role.hty_role_id.clone().unwrap(), + &hty_role_id, conn, ) { Ok(true) => continue, @@ -3642,7 +3763,7 @@ fn raw_create_or_update_userinfo_with_roles( let entry = UserInfoRole { the_id: uuid(), user_info_id: user_app_info.id.clone(), - role_id: user_info_role.hty_role_id.clone().unwrap().clone(), + role_id: hty_role_id, }; UserInfoRole::create(&entry, conn)?; } @@ -3696,10 +3817,15 @@ fn raw_create_or_update_roles( db_pool: Arc, ) -> anyhow::Result { let role = hty_role.clone(); - if role.labels.is_some() { - for label in role.labels.clone().unwrap() { + if let Some(labels) = role.labels.clone() { + for label in labels { + let hty_label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_label_id is required".into()), + }))?; match HtyLabel::verify_exist_by_id( - &label.hty_label_id.unwrap(), + &hty_label_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -3712,10 +3838,15 @@ fn raw_create_or_update_roles( } } } - if role.actions.is_some() { - for action in role.actions.clone().unwrap() { + if let Some(actions) = role.actions.clone() { + for action in actions { + let hty_action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_action_id is required".into()), + }))?; match HtyAction::verify_exist_by_id( - &action.hty_action_id.unwrap(), + &hty_action_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -3728,8 +3859,8 @@ fn raw_create_or_update_roles( } } } - if role.app_ids.is_some() { - for app_id in role.app_ids.clone().unwrap() { + if let Some(app_ids) = role.app_ids.clone() { + for app_id in app_ids { match HtyApp::verify_exist_by_id( &app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), @@ -3764,18 +3895,28 @@ fn raw_create_or_update_roles( conn: &mut PgConnection| -> anyhow::Result { let mut res_role = role.clone(); + let role_key = role.role_key.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_key is required".into()), + }))?; + let role_status = role.role_status.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_status is required".into()), + }))?; let in_role = HtyRole { hty_role_id: uuid(), - role_key: role.role_key.clone().unwrap(), + role_key, role_desc: role.role_desc.clone(), - role_status: role.role_status.clone().unwrap(), + role_status, style: role.style.clone(), role_name: role.role_name.clone(), }; let created_role = HtyRole::create(&in_role, conn)?; res_role.hty_role_id = Some(created_role.hty_role_id.clone()); - if role.app_ids.is_some() { - for app in role.app_ids.clone().unwrap() { + if let Some(app_ids) = role.app_ids.clone() { + for app in app_ids { let in_app = AppRole { the_id: uuid(), role_id: in_role.hty_role_id.clone(), @@ -3784,22 +3925,32 @@ fn raw_create_or_update_roles( AppRole::create(&in_app, conn)?; } } - if role.labels.is_some() { - for label in role.labels.clone().unwrap() { + if let Some(labels) = role.labels.clone() { + for label in labels { + let label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_label_id is required".into()), + }))?; let in_label = RoleLabel { the_id: uuid(), role_id: in_role.hty_role_id.clone(), - label_id: label.hty_label_id.clone().unwrap(), + label_id, }; RoleLabel::create(&in_label, conn)?; } } - if role.actions.is_some() { - for action in role.actions.clone().unwrap() { + if let Some(actions) = role.actions.clone() { + for action in actions { + let action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_action_id is required".into()), + }))?; let in_action = RoleAction { the_id: uuid(), role_id: in_role.hty_role_id.clone(), - action_id: action.hty_action_id.clone().unwrap(), + action_id, }; RoleAction::create(&in_action, conn)?; } @@ -3820,29 +3971,39 @@ fn raw_create_or_update_roles( } // role_id is some, then update existing role - if role.hty_role_id.is_some() { + if let Some(hty_role_id) = role.hty_role_id.clone() { let task_update_role = move |_in_params: Option>, conn: &mut PgConnection| -> anyhow::Result { - RoleLabel::delete_by_role_id(&role.hty_role_id.clone().unwrap(), conn)?; - AppRole::delete_by_role_id(&role.hty_role_id.clone().unwrap(), conn)?; - RoleAction::delete_by_role_id(&role.hty_role_id.clone().unwrap(), conn)?; - match HtyRole::verify_exist_by_id(&role.hty_role_id.clone().unwrap(), conn) { + RoleLabel::delete_by_role_id(&hty_role_id, conn)?; + AppRole::delete_by_role_id(&hty_role_id, conn)?; + RoleAction::delete_by_role_id(&hty_role_id, conn)?; + match HtyRole::verify_exist_by_id(&hty_role_id, conn) { Ok(true) => { + let role_key = role.role_key.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_key is required".into()), + }))?; + let role_status = role.role_status.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("role_status is required".into()), + }))?; let update_role = HtyRole { - hty_role_id: role.hty_role_id.clone().unwrap(), - role_key: role.role_key.clone().unwrap(), + hty_role_id: hty_role_id.clone(), + role_key, role_desc: role.clone().role_desc, - role_status: role.role_status.clone().unwrap(), + role_status, style: role.style.clone(), role_name: role.role_name.clone(), }; HtyRole::update(&update_role, conn)?; - if role.app_ids.is_some() { - for app_id in role.app_ids.clone().unwrap() { + if let Some(app_ids) = role.app_ids.clone() { + for app_id in app_ids { match AppRole::verify_exist_by_app_id_and_role_id( &app_id.clone(), - &role.hty_role_id.clone().unwrap(), + &hty_role_id, conn, ) { Ok(true) => continue, @@ -3850,7 +4011,7 @@ fn raw_create_or_update_roles( let in_app_role = AppRole { the_id: uuid(), app_id: app_id.clone(), - role_id: role.hty_role_id.clone().unwrap(), + role_id: hty_role_id.clone(), }; AppRole::create(&in_app_role, conn)?; } @@ -3863,19 +4024,24 @@ fn raw_create_or_update_roles( } } } - if role.labels.is_some() { - for label in role.labels.clone().unwrap() { + if let Some(labels) = role.labels.clone() { + for label in labels { + let label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_label_id is required".into()), + }))?; match RoleLabel::verify_exist_by_role_id_and_label_id( - &role.hty_role_id.clone().unwrap(), - &label.hty_label_id.clone().unwrap(), + &hty_role_id, + &label_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_role_label = RoleLabel { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), - label_id: label.hty_label_id.clone().unwrap(), + role_id: hty_role_id.clone(), + label_id, }; RoleLabel::create(&in_role_label, conn)?; } @@ -3888,19 +4054,24 @@ fn raw_create_or_update_roles( } } } - if role.actions.is_some() { - for action in role.actions.clone().unwrap() { + if let Some(actions) = role.actions.clone() { + for action in actions { + let action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_action_id is required".into()), + }))?; match RoleAction::verify_exist_by_role_id_and_action_id( - &role.hty_role_id.clone().unwrap(), - &action.hty_action_id.clone().unwrap(), + &hty_role_id, + &action_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_role_action = RoleAction { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), - action_id: action.hty_action_id.clone().unwrap(), + role_id: hty_role_id.clone(), + action_id, }; RoleAction::create(&in_role_action, conn)?; } @@ -3968,10 +4139,15 @@ fn raw_create_or_update_actions( db_pool: Arc, ) -> anyhow::Result { let action = hty_action.clone(); - if action.labels.is_some() { - for label in action.labels.clone().unwrap() { + if let Some(labels) = action.labels.clone() { + for label in labels { + let hty_label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_label_id is required".into()), + }))?; match HtyLabel::verify_exist_by_id( - &label.hty_label_id.unwrap(), + &hty_label_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -3984,10 +4160,15 @@ fn raw_create_or_update_actions( } } } - if action.roles.is_some() { - for role in action.roles.clone().unwrap() { + if let Some(roles) = action.roles.clone() { + for role in roles { + let hty_role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_role_id is required".into()), + }))?; match HtyRole::verify_exist_by_id( - &role.hty_role_id.unwrap(), + &hty_role_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -4000,18 +4181,16 @@ fn raw_create_or_update_actions( } } } - if action.action_name.is_none() { - return Err(anyhow!(HtyErr { + let action_name = action.action_name.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("action name can not be none".into()), - })); - } - if action.action_status.is_none() { - return Err(anyhow!(HtyErr { + reason: Some("action_name is required".into()), + }))?; + let action_status = action.action_status.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("action status can not be none".into()), - })); - } + reason: Some("action_status is required".into()), + }))?; let params = HashMap::new(); // action_id is none, then create new action @@ -4022,30 +4201,40 @@ fn raw_create_or_update_actions( let mut res_action = action.clone(); let in_action = HtyAction { hty_action_id: uuid(), - action_name: action.action_name.clone().unwrap(), + action_name: action_name.clone(), action_desc: action.action_desc.clone(), - action_status: action.action_status.clone().unwrap(), + action_status: action_status.clone(), }; let created_action = HtyAction::create(&in_action, conn)?; res_action.hty_action_id = Some(created_action.hty_action_id.clone()); - if action.labels.is_some() { - for label in action.labels.clone().unwrap() { + if let Some(labels) = action.labels.clone() { + for label in labels { + let label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_label_id is required".into()), + }))?; let in_label = ActionLabel { the_id: uuid(), action_id: created_action.hty_action_id.clone(), - label_id: label.hty_label_id.clone().unwrap(), + label_id, }; ActionLabel::create(&in_label, conn)?; } } - if action.roles.is_some() { - for role in action.roles.clone().unwrap() { - let in_action = RoleAction { + if let Some(roles) = action.roles.clone() { + for role in roles { + let role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_role_id is required".into()), + }))?; + let in_role_action = RoleAction { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), - action_id: in_action.hty_action_id.clone(), + role_id, + action_id: created_action.hty_action_id.clone(), }; - RoleAction::create(&in_action, conn)?; + RoleAction::create(&in_role_action, conn)?; } } return Ok(res_action.clone()); @@ -4063,35 +4252,40 @@ fn raw_create_or_update_actions( }; } - // action_id is some, then update existing role - if action.hty_action_id.is_some() { + // action_id is some, then update existing action + if let Some(hty_action_id) = action.hty_action_id.clone() { let task_update_action = move |_in_params: Option>, conn: &mut PgConnection| -> anyhow::Result { - RoleAction::delete_by_action_id(&action.hty_action_id.clone().unwrap(), conn)?; - ActionLabel::delete_by_action_id(&action.hty_action_id.clone().unwrap(), conn)?; - match HtyAction::verify_exist_by_id(&action.hty_action_id.clone().unwrap(), conn) { + RoleAction::delete_by_action_id(&hty_action_id, conn)?; + ActionLabel::delete_by_action_id(&hty_action_id, conn)?; + match HtyAction::verify_exist_by_id(&hty_action_id, conn) { Ok(true) => { let update_action = HtyAction { - hty_action_id: action.hty_action_id.clone().unwrap(), - action_name: action.action_name.clone().unwrap(), + hty_action_id: hty_action_id.clone(), + action_name: action_name.clone(), action_desc: action.clone().action_desc, - action_status: action.action_status.clone().unwrap(), + action_status: action_status.clone(), }; HtyAction::update(&update_action, conn)?; - if action.labels.is_some() { - for label in action.labels.clone().unwrap() { + if let Some(labels) = action.labels.clone() { + for label in labels { + let label_id = label.hty_label_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_label_id is required".into()), + }))?; match ActionLabel::verify_exist_by_action_id_and_label_id( - &action.hty_action_id.clone().unwrap(), - &label.hty_label_id.clone().unwrap(), + &hty_action_id, + &label_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_action_label = ActionLabel { the_id: uuid(), - action_id: action.hty_action_id.clone().unwrap(), - label_id: label.hty_label_id.clone().unwrap(), + action_id: hty_action_id.clone(), + label_id, }; ActionLabel::create(&in_action_label, conn)?; } @@ -4104,19 +4298,24 @@ fn raw_create_or_update_actions( } } } - if action.roles.is_some() { - for role in action.roles.clone().unwrap() { + if let Some(roles) = action.roles.clone() { + for role in roles { + let role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_role_id is required".into()), + }))?; match RoleAction::verify_exist_by_role_id_and_action_id( - &role.hty_role_id.clone().unwrap(), - &action.hty_action_id.clone().unwrap(), + &role_id, + &hty_action_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_role_action = RoleAction { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), - action_id: action.hty_action_id.clone().unwrap(), + role_id, + action_id: hty_action_id.clone(), }; RoleAction::create(&in_role_action, conn)?; } @@ -4178,10 +4377,15 @@ fn raw_create_or_update_labels( db_pool: Arc, ) -> anyhow::Result { let label = hty_label.clone(); - if label.roles.is_some() { - for role in label.roles.clone().unwrap() { + if let Some(roles) = label.roles.clone() { + for role in roles { + let hty_role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_role_id is required".into()), + }))?; match HtyRole::verify_exist_by_id( - &role.hty_role_id.clone().unwrap(), + &hty_role_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -4194,10 +4398,15 @@ fn raw_create_or_update_labels( } } } - if label.actions.is_some() { - for action in label.actions.clone().unwrap() { + if let Some(actions) = label.actions.clone() { + for action in actions { + let hty_action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::NullErr, + reason: Some("hty_action_id is required".into()), + }))?; match HtyAction::verify_exist_by_id( - &action.hty_action_id.clone().unwrap(), + &hty_action_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(true) => continue, @@ -4210,18 +4419,16 @@ fn raw_create_or_update_labels( } } } - if label.label_name.is_none() { - return Err(anyhow!(HtyErr { + let label_name = label.label_name.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("label name can not be none".into()), - })); - } - if label.label_status.is_none() { - return Err(anyhow!(HtyErr { + reason: Some("label_name is required".into()), + }))?; + let label_status = label.label_status.clone() + .ok_or_else(|| anyhow!(HtyErr { code: HtyErrCode::NullErr, - reason: Some("label status can not be none".into()), - })); - } + reason: Some("label_status is required".into()), + }))?; let params = HashMap::new(); // label_id is none, then create new label @@ -4232,28 +4439,38 @@ fn raw_create_or_update_labels( let mut res_label = label.clone(); let in_label = HtyLabel { hty_label_id: uuid(), - label_name: label.label_name.clone().unwrap(), + label_name: label_name.clone(), label_desc: label.label_desc.clone(), - label_status: label.label_status.clone().unwrap(), + label_status: label_status.clone(), style: label.style.clone(), }; let created_label = HtyLabel::create(&in_label, conn)?; res_label.hty_label_id = Some(created_label.hty_label_id.clone()); - if label.actions.is_some() { - for action in label.actions.clone().unwrap() { + if let Some(actions) = label.actions.clone() { + for action in actions { + let action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_action_id is required".into()), + }))?; let in_action_label = ActionLabel { the_id: uuid(), - action_id: action.hty_action_id.clone().unwrap(), + action_id, label_id: created_label.hty_label_id.clone(), }; ActionLabel::create(&in_action_label, conn)?; } } - if label.roles.is_some() { - for role in label.roles.clone().unwrap() { + if let Some(roles) = label.roles.clone() { + for role in roles { + let role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_role_id is required".into()), + }))?; let in_role_label = RoleLabel { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), + role_id, label_id: created_label.hty_label_id.clone(), }; RoleLabel::create(&in_role_label, conn)?; @@ -4279,35 +4496,40 @@ fn raw_create_or_update_labels( } // label_id is some, then update existing label - if label.hty_label_id.is_some() { + if let Some(hty_label_id) = label.hty_label_id.clone() { let task_update_label = move |_in_params: Option>, conn: &mut PgConnection| -> anyhow::Result { - RoleLabel::delete_by_label_id(&label.hty_label_id.clone().unwrap(), conn)?; - ActionLabel::delete_by_label_id(&label.hty_label_id.clone().unwrap(), conn)?; - match HtyLabel::verify_exist_by_id(&label.hty_label_id.clone().unwrap(), conn) { + RoleLabel::delete_by_label_id(&hty_label_id, conn)?; + ActionLabel::delete_by_label_id(&hty_label_id, conn)?; + match HtyLabel::verify_exist_by_id(&hty_label_id, conn) { Ok(true) => { let update_label = HtyLabel { - hty_label_id: label.hty_label_id.clone().unwrap(), - label_name: label.label_name.clone().unwrap(), + hty_label_id: hty_label_id.clone(), + label_name: label_name.clone(), label_desc: label.clone().label_desc, - label_status: label.label_status.clone().unwrap(), + label_status: label_status.clone(), style: label.style.clone(), }; HtyLabel::update(&update_label, conn)?; - if label.actions.is_some() { - for action in label.actions.clone().unwrap() { + if let Some(actions) = label.actions.clone() { + for action in actions { + let action_id = action.hty_action_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_action_id is required".into()), + }))?; match ActionLabel::verify_exist_by_action_id_and_label_id( - &action.hty_action_id.clone().unwrap(), - &label.hty_label_id.clone().unwrap(), + &action_id, + &hty_label_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_action_label = ActionLabel { the_id: uuid(), - action_id: action.hty_action_id.clone().unwrap(), - label_id: label.hty_label_id.clone().unwrap(), + action_id, + label_id: hty_label_id.clone(), }; ActionLabel::create(&in_action_label, conn)?; } @@ -4320,19 +4542,24 @@ fn raw_create_or_update_labels( } } } - if label.roles.is_some() { - for role in label.roles.clone().unwrap() { + if let Some(roles) = label.roles.clone() { + for role in roles { + let role_id = role.hty_role_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_role_id is required".into()), + }))?; match RoleLabel::verify_exist_by_role_id_and_label_id( - &role.hty_role_id.clone().unwrap(), - &label.hty_label_id.clone().unwrap(), + &role_id, + &hty_label_id, conn, ) { Ok(true) => continue, Ok(false) => { let in_role_label = RoleLabel { the_id: uuid(), - role_id: role.hty_role_id.clone().unwrap(), - label_id: label.hty_label_id.clone().unwrap(), + role_id, + label_id: hty_label_id.clone(), }; RoleLabel::create(&in_role_label, conn)?; } @@ -4446,10 +4673,15 @@ pub async fn find_all_valid_teachers( Ok(in_users) => { let mut resp = Vec::new(); for in_user in in_users { - if in_user.enabled.is_some() { - let is_enabled = in_user.enabled.clone().unwrap(); - if is_enabled && in_user.infos.clone().unwrap().get(0).unwrap().is_registered { - resp.push(in_user.clone()); + if let Some(is_enabled) = in_user.enabled.clone() { + if is_enabled { + if let Some(infos) = in_user.infos.clone() { + if let Some(first_info) = infos.get(0) { + if first_info.is_registered { + resp.push(in_user.clone()); + } + } + } } } } @@ -4612,17 +4844,18 @@ fn raw_find_users_with_info_by_role( let user_infos = role.find_linked_user_app_info(conn)?; let out_user_infos: Vec = user_infos .into_iter() - .filter(|item| item.clone().app_id.unwrap() == app_id.app_id) + .filter(|item| item.app_id.as_ref().map(|id| id == &app_id.app_id).unwrap_or(false)) .collect(); let out_req_user_infos: Vec = out_user_infos.iter().map(|item| item.to_req()).collect(); let res: Vec = out_req_user_infos .iter() - .map(|item| { - let user = HtyUser::find_by_hty_id(&item.clone().hty_id.unwrap(), conn).unwrap(); + .filter_map(|item| { + let hty_id = item.hty_id.clone()?; + let user = HtyUser::find_by_hty_id(&hty_id, conn).ok()?; let mut infos = Vec::new(); infos.push(item.clone()); - let out = ReqHtyUserWithInfos { + Some(ReqHtyUserWithInfos { hty_id: Some(user.hty_id.clone()), union_id: user.union_id.clone(), enabled: Some(user.enabled), @@ -4633,8 +4866,7 @@ fn raw_find_users_with_info_by_role( infos: Some(infos), info_roles: None, settings: user.settings.clone(), - }; - out + }) }) .collect(); Ok(res) @@ -4944,15 +5176,18 @@ async fn raw_find_user_with_info_by_token( debug(format!("raw_find_user_with_info_by_token -> app_id: {:?}", in_app).as_str()); + let hty_id = token.hty_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_id is required in token"))?; + let in_user = HtyUser::find_by_hty_id( - &token.hty_id.clone().unwrap()[..], + &hty_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; debug(format!("raw_find_user_with_info_by_token -> user: {:?}", in_user).as_str()); let info = UserAppInfo::find_by_hty_id_and_app_id( - &token.hty_id.clone().unwrap(), + &hty_id, &in_app.app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; @@ -4977,8 +5212,10 @@ async fn raw_find_user_with_info_by_token( role_name: in_role.role_name.clone(), }; + let hty_role_id = out_role.hty_role_id.clone() + .ok_or_else(|| anyhow::anyhow!("hty_role_id is required"))?; let labels = HtyLabel::find_all_by_role_id( - &out_role.hty_role_id.clone().unwrap(), + &hty_role_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; out_role.labels = Some(HtyLabel::to_req_labels(&labels)); @@ -5014,12 +5251,16 @@ async fn raw_find_user_with_info_by_token( // }); task::spawn(async move { - let _ = post_login( - &in_user, - &in_app, - extract_conn(fetch_db_conn(&db_pool).unwrap()).deref_mut(), - ) - .await; // todo: unwrap should be fixed. + if let Ok(conn) = fetch_db_conn(&db_pool) { + let _ = post_login( + &in_user, + &in_app, + extract_conn(conn).deref_mut(), + ) + .await; + } else { + error!("Failed to get db connection in post_login task"); + } }); Ok(req_hty_user_with_infos) @@ -5049,7 +5290,9 @@ fn raw_sudo2(auth: AuthorizationHeader, host: HtyHostHeader, to_user_id: String, let user_tags = get_all_db_tags_of_the_user(auth, host, conn)?; debug!("raw_sudo2 -> user_tags: {:?}", user_tags); - let id_current_user = jwt_decode_token(&(*the_auth).clone())?.hty_id.unwrap(); + let id_current_user = jwt_decode_token(&(*the_auth).clone())? + .hty_id + .ok_or_else(|| anyhow::anyhow!("hty_id is required in token"))?; let user_app_info = UserAppInfo::find_by_id(&to_user_id, conn)?; let id_to_user = user_app_info.hty_id.clone(); @@ -5063,7 +5306,7 @@ fn raw_sudo2(auth: AuthorizationHeader, host: HtyHostHeader, to_user_id: String, roles: user_app_info.req_roles_by_id(conn)?, tags: None, }; - save_token_with_exp_days(&resp_token, get_token_expiration_days())?; + save_token_with_exp_days(&resp_token, get_token_expiration_days()?)?; Ok(jwt_encode_token(resp_token)?) } else { return Err(anyhow!(HtyErr { @@ -5118,7 +5361,7 @@ fn raw_sudo(auth: AuthorizationHeader, conn: &mut PgConnection) -> anyhow::Resul }; //Save sudoer token - save_token_with_exp_days(&resp_token, get_token_expiration_days())?; + save_token_with_exp_days(&resp_token, get_token_expiration_days()?)?; Ok(jwt_encode_token(resp_token)?) } @@ -5180,7 +5423,8 @@ fn raw_login_with_password( } let info = UserAppInfo::find_by_username_and_app_id( - &req_login.username.clone().unwrap(), + &req_login.username.clone() + .ok_or_else(|| anyhow::anyhow!("username is required"))?, &app.app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), )?; @@ -5195,7 +5439,7 @@ fn raw_login_with_password( }; return if info.password == req_login.password { - save_token_with_exp_days(&resp_token, get_token_expiration_days())?; + save_token_with_exp_days(&resp_token, get_token_expiration_days()?)?; Ok(jwt_encode_token(resp_token)?) } else { @@ -5210,7 +5454,16 @@ pub async fn wx_qr_login(State(db_pool): State>, host: HtyHostHeade debug!("wx_qr_login -> starts"); let app_domain = (*host).clone(); - let code = req_code.code.unwrap(); + let code = match req_code.code { + Some(c) => c, + None => { + error!("wx_qr_login -> code is required"); + return (StatusCode::BAD_REQUEST, wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("code is required".into()), + })); + } + }; debug!("wx_qr_login -> app_domain {:?} / code {:?}", &app_domain, &code); @@ -5230,11 +5483,14 @@ async fn raw_wx_qr_login(code: String, app_domain: String, db_pool: Arc debug!("raw_wx_qr_login -> domain: {:?} / code: {:?}", &app_domain, &code); let app = HtyApp::find_by_domain(&app_domain, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; - let wx_secret = app.wx_secret.clone().unwrap(); + let wx_secret = app.wx_secret.clone() + .ok_or_else(|| anyhow::anyhow!("wx_secret is required"))?; + let wx_id = app.wx_id.clone() + .ok_or_else(|| anyhow::anyhow!("wx_id is required"))?; debug!("raw_wx_qr_login -> domain: {:?} / app: {:?} / secret: {:?} / code: {:?}", &app_domain, &app, &wx_secret, &code); - let union_id = get_union_id_by_auth_code(app.wx_id.clone().unwrap(), wx_secret, code).await?; + let union_id = get_union_id_by_auth_code(wx_id, wx_secret, code).await?; debug!("raw_wx_qr_login -> union_id: {:?}", &union_id); @@ -5288,7 +5544,7 @@ async fn raw_wx_qr_login(code: String, app_domain: String, db_pool: Arc debug!("raw_wx_qr_login -> resp_token: {:?}", &resp_token); - save_token_with_exp_days(&resp_token, get_token_expiration_days())?; + save_token_with_exp_days(&resp_token, get_token_expiration_days()?)?; Ok(jwt_encode_token(resp_token)?) } @@ -5299,14 +5555,26 @@ async fn verify_user_enabled_and_registered_in_app(_sudoer: HtySudoerTokenHeader let in_app_domain = get_some_from_query_params::("app_domain", ¶ms); let in_hty_id = get_some_from_query_params::("hty_id", ¶ms); - if in_app_domain.is_none() || in_hty_id.is_none() { - return wrap_json_hty_err::(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("app_domain or hty_id is none".into()), - }); - } + let app_domain = match in_app_domain { + Some(d) => d, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("app_domain is required".into()), + }); + } + }; + let hty_id = match in_hty_id { + Some(id) => id, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_id is required".into()), + }); + } + }; - match raw_verify_user_enabled_and_registered_in_app(in_app_domain.unwrap(), in_hty_id.unwrap(), db_pool).await { + match raw_verify_user_enabled_and_registered_in_app(app_domain, hty_id, db_pool).await { Ok(result) => { debug!("verify_user_enabled_and_registered_in_app -> success: {:?}", result); wrap_json_ok_resp(result) @@ -5424,8 +5692,8 @@ fn raw_login2_with_unionid_tx( } }; - if r2.is_err() { - return Err(anyhow!(r2.err().unwrap())); + if let Err(e) = r2 { + return Err(anyhow!(e)); } let user_exist_r = match HtyUser::verify_exist_by_union_id(&union_id, conn) { @@ -5510,16 +5778,20 @@ fn raw_login2_with_unionid_tx( }, }; - save_token_with_exp_days(&token, get_token_expiration_days())?; + save_token_with_exp_days(&token, get_token_expiration_days()?)?; debug!("entering post_login()"); // 注册流程完成 let _ = del_from_redis(&in_processing_union_id); debug!("raw_login2_with_unionid() -> return response: {:?}", &token); + + let app = from_app.clone() + .ok_or_else(|| anyhow::anyhow!("from_app is required"))?; + Ok(( jwt_encode_token(token)?, login_user, - from_app.clone().unwrap(), + app, )) } } @@ -5536,12 +5808,16 @@ fn raw_login2_with_unionid_tx( // 补一下老用户或者后关注某一个公众号(`to_app`)没有相关`user_info()`的问题。 // 新用户且已经关注公众号(to_app)的,在`register()`里面就已经创建好了`user_app_info`. task::spawn(async move { - let _ = post_login( - &user, - &app, - extract_conn(fetch_db_conn(&db_pool).unwrap()).deref_mut(), - ) - .await; // todo: deal with error instead of `unwrap` + if let Ok(conn) = fetch_db_conn(&db_pool) { + let _ = post_login( + &user, + &app, + extract_conn(conn).deref_mut(), + ) + .await; + } else { + error!("Failed to get db connection in post_login task"); + } }); Ok(token) @@ -5562,7 +5838,7 @@ pub async fn post_login( from_app: &HtyApp, conn: &mut PgConnection, ) -> anyhow::Result<()> { - if skip_post_login() { + if skip_post_login().unwrap_or(false) { debug!("post_login() ::BYPASSED::"); } else { debug!("post_login() starts"); @@ -5674,7 +5950,8 @@ async fn call_refresh_openid( debug!("call_refresh_openid -> req_user: {:?}", &req_user); let client = reqwest::Client::new(); - let body = serde_json::to_string::(&req_user).unwrap(); + let body = serde_json::to_string::(&req_user) + .map_err(|e| anyhow::anyhow!("Failed to serialize request: {}", e))?; debug!("call_refresh_openid -> body: {:?}", &body); @@ -5692,7 +5969,7 @@ async fn call_refresh_openid( debug!("call_refresh_openid -> resp: {:?}", &resp); let resp_openid: HtyResponse = resp.json().await?; - Ok(resp_openid.d.unwrap()) + resp_openid.d.ok_or_else(|| anyhow::anyhow!("Response data is missing")) } // must move in conn here because of async @@ -5701,17 +5978,28 @@ pub async fn refresh_openid( State(db_pool): State>, Json(req_user): Json, ) -> Json> { - let id_user = req_user.hty_id.unwrap(); - let id_user_app_info = req_user + let id_user = match req_user.hty_id.clone() { + Some(id) => id, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("hty_id is required".into()), + }); + } + }; + let id_user_app_info = match req_user .infos .clone() - .unwrap() - .get(0) - .clone() - .unwrap() - .id - .clone() - .unwrap(); + .and_then(|infos| infos.get(0).cloned()) + .and_then(|info| info.id.clone()) { + Some(id) => id, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("user_app_info id is required".into()), + }); + } + }; match raw_refresh_openid(&id_user, &id_user_app_info, db_conn, db_pool).await { Ok(ok) => wrap_json_ok_resp(ok), @@ -5736,14 +6024,15 @@ async fn raw_refresh_openid( has_openid, !has_openid ); - let id_app = user_app_info.app_id.clone().unwrap(); - let union_id = user.union_id.clone().unwrap(); + let id_app = user_app_info.app_id.clone() + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let union_id = user.union_id.clone() + .ok_or_else(|| anyhow::anyhow!("union_id is required"))?; let mut out_openid = "".to_string(); let the_app = HtyApp::find_by_id(&id_app, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; - if the_app.wx_id.is_none() || the_app.wx_id.clone().unwrap().is_empty() { - debug!("refresh_openid() -> NO WX_ID, :::BYPASS:::"); + if the_app.wx_id.clone().filter(|id| !id.is_empty()).is_none() { return Err(anyhow!(HtyErr { code: HtyErrCode::NullErr, reason: Some("refresh_openid() -> NO WX_ID, :::BYPASS:::".to_string()), @@ -5751,11 +6040,9 @@ async fn raw_refresh_openid( } if has_openid { - out_openid = user_app_info.openid.clone().unwrap(); + out_openid = user_app_info.openid.clone() + .ok_or_else(|| anyhow::anyhow!("openid is required"))?; } else { - let the_app = - HtyApp::find_by_id(&id_app, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; - debug!("refresh_openid() openid -> {:?}", the_app); let _ = refresh_cache_and_get_wx_all_follower_openids(&the_app).await?; @@ -5805,7 +6092,15 @@ pub async fn upyun_token(_sudoer: HtySudoerTokenHeader, data: String) -> Json) -> Json> { - let data = payload.payload.unwrap(); + let data = match payload.payload { + Some(d) => d, + None => { + return wrap_json_hty_err::(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("payload is required".into()), + }); + } + }; let operator = get_upyun_operator().to_owned(); let pwd = get_upyun_password().to_owned(); let token = generate_upyun_token(&data, &operator, &pwd); @@ -5842,7 +6137,7 @@ async fn raw_wx_login( // Result; let params = WxParams { code: Some(login.code.clone()), - appid: Some(in_app.wx_id.unwrap().clone()), + appid: in_app.wx_id.clone(), secret: in_app.wx_secret.clone(), encrypted_data: None, iv: None, @@ -6009,10 +6304,14 @@ fn raw_login_with_cert( let app_domain = (*hty_host).clone(); let app = HtyApp::find_by_domain(&app_domain, conn)?; let req_cert = in_req_cert.clone(); + let pubkey = app.pubkey.clone() + .ok_or_else(|| anyhow::anyhow!("pubkey is required"))?; + let encrypted_data = req_cert.encrypted_data.clone() + .ok_or_else(|| anyhow::anyhow!("encrypted_data is required"))?; match verify( - app.clone().pubkey.unwrap(), - req_cert.encrypted_data.clone().unwrap(), - app.clone().pubkey.unwrap(), + pubkey.clone(), + encrypted_data, + pubkey, ) { Ok(_result) => { let resp_token = HtyToken { @@ -6025,7 +6324,7 @@ fn raw_login_with_cert( tags: None, }; - save_token_with_exp_days(&resp_token, get_token_expiration_days())?; + save_token_with_exp_days(&resp_token, get_token_expiration_days()?)?; Ok(jwt_encode_token(resp_token)?) } Err(error) => Err(error), @@ -6089,7 +6388,9 @@ fn raw_get_encrypt_id_with_pubkey( })); } - match HtyApp::get_encrypt_app_id(&req_pubkey.pubkey.clone().unwrap(), conn) { + let pubkey = req_pubkey.pubkey.clone() + .ok_or_else(|| anyhow::anyhow!("pubkey is required"))?; + match HtyApp::get_encrypt_app_id(&pubkey, conn) { Ok(encrypt_app_id) => Ok(encrypt_app_id), Err(_e) => Err(anyhow!(HtyErr { code: HtyErrCode::CommonError, @@ -6187,16 +6488,19 @@ pub async fn raw_wx_identify2( ) -> anyhow::Result>> { let app = HtyApp::find_by_domain(&domain, extract_conn(fetch_db_conn(&db_pool)?).deref_mut()); - if app.is_err() { - return Ok(wrap_json_hty_err(HtyErr { - code: HtyErrCode::DbErr, - reason: Some(app.err().unwrap().to_string()), - })); - } + let app = match app { + Ok(a) => a, + Err(e) => { + return Ok(wrap_json_hty_err(HtyErr { + code: HtyErrCode::DbErr, + reason: Some(e.to_string()), + })); + } + }; match htyuc_models::wx::identify2( &wx_id, - &app.unwrap().app_id, + &app.app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut(), ) { Ok(token) => { @@ -6273,9 +6577,12 @@ fn raw_unlink_users(req_user_rel: ReqHtyUserRels, conn: &mut PgConnection) -> an reason: Some("to_user_id or from_user_id or rel_type can not be none".into()) })); } - let id_from = req_user_rel.from_user_id.unwrap(); - let id_to = req_user_rel.to_user_id.unwrap(); - let type_rel = req_user_rel.rel_type.unwrap(); + let id_from = req_user_rel.from_user_id.clone() + .ok_or_else(|| anyhow::anyhow!("from_user_id is required"))?; + let id_to = req_user_rel.to_user_id.clone() + .ok_or_else(|| anyhow::anyhow!("to_user_id is required"))?; + let type_rel = req_user_rel.rel_type.clone() + .ok_or_else(|| anyhow::anyhow!("rel_type is required"))?; let db_item = HtyUserRels::find_by_all_col(&id_from, &id_to, &type_rel, conn)?; let res = HtyUserRels::delete_by_id(&db_item.id, conn); @@ -6301,17 +6608,26 @@ async fn link_users(conn: db::DbConn, Json(req_user_rel): Json) } fn raw_link_users(req_user_rel: ReqHtyUserRels, conn: &mut PgConnection) -> anyhow::Result<()> { - if req_user_rel.to_user_id.is_none() || req_user_rel.from_user_id.is_none() || req_user_rel.rel_type.is_none() { - return Err(anyhow!(HtyErr { - code: HtyErrCode::WebErr, - reason: Some("to_user_id or from_user_id or rel_type can not be none".into()) - })); - } + let from_user_id = req_user_rel.from_user_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("from_user_id is required".into()) + }))?; + let to_user_id = req_user_rel.to_user_id.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("to_user_id is required".into()) + }))?; + let rel_type = req_user_rel.rel_type.clone() + .ok_or_else(|| anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some("rel_type is required".into()) + }))?; let in_item = HtyUserRels { id: uuid(), - from_user_id: req_user_rel.from_user_id.unwrap(), - to_user_id: req_user_rel.to_user_id.unwrap(), - rel_type: req_user_rel.rel_type.unwrap(), + from_user_id, + to_user_id, + rel_type, }; let _ = HtyUserRels::create(&in_item, conn)?; Ok(()) @@ -6395,12 +6711,11 @@ fn raw_find_group_users_by_group_id( if group.users.is_none() { return Ok(empty); } - let users = group.users.clone().unwrap().vals; - if users.is_none() { - return Ok(empty); + if let Some(users_val) = group.users.clone().and_then(|u| u.vals) { + Ok(users_val) + } else { + Ok(empty) } - let res = users.unwrap(); - Ok(res) } async fn find_user_groups_by_user_id( @@ -6435,8 +6750,8 @@ fn raw_find_user_groups_by_user_id( let some_groups = HtyUserGroup::find_by_app_id_or_users(&id, &app.app_id, conn)?; - if some_groups.is_some() { - let res = some_groups.unwrap().into_iter().map(|group| group.to_req()).collect(); + if let Some(groups) = some_groups { + let res = groups.into_iter().map(|group| group.to_req()).collect(); Ok(Some(res)) } else { Ok(None) diff --git a/htyuc/src/main.rs b/htyuc/src/main.rs index 6ebd278..1306cc2 100644 --- a/htyuc/src/main.rs +++ b/htyuc/src/main.rs @@ -24,7 +24,8 @@ async fn main() { logger_init(); - launch_rocket(get_uc_port(), uc_rocket(&get_uc_db_url())).await; + let port = get_uc_port().expect("Failed to get UC_PORT"); + launch_rocket(port, uc_rocket(&get_uc_db_url())).await.expect("Failed to launch rocket"); // this is reachable only after `Shutdown::notify()` or `Ctrl+C`. println!("Rocket: deorbit."); diff --git a/htyuc/src/notifications.rs b/htyuc/src/notifications.rs index 934c0b2..c0dc8d5 100644 --- a/htyuc/src/notifications.rs +++ b/htyuc/src/notifications.rs @@ -37,15 +37,17 @@ fn build_wx_push_message_for_teacher_register( let from_app_admin_user_infos: Vec = admin_users .into_iter() - .filter(|the_info| the_info.app_id.clone().unwrap() == from_app.app_id) + .filter(|the_info| the_info.app_id.as_ref().map(|id| id == &from_app.app_id).unwrap_or(false)) .collect(); debug!("from_app_admin_users -> {:?}", &from_app_admin_user_infos); // let template_id = String::from(env::var("WX_MSG_TEACHER_REGISTER")?.to_string()); + let wx_id = from_app.clone().wx_id + .ok_or_else(|| anyhow::anyhow!("wx_id is required for from_app"))?; let wx_mini_program = ReqWxMiniProgram { - appid: from_app.clone().wx_id.unwrap(), + appid: wx_id, pagepath: "index".to_string(), }; @@ -60,7 +62,10 @@ fn build_wx_push_message_for_teacher_register( debug!("build_wx_push_message_for_teacher_register -> {:?} / {:?}", &in_template, &in_template_data); - let mut wx_message_data = in_template_data.template_text.clone().unwrap().clone().val.unwrap(); + let mut wx_message_data = in_template_data.template_text.clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; let val_keyword1 = wx_message_data.keyword1.value; let val_keyword2 = wx_message_data.keyword2.value; @@ -84,17 +89,20 @@ fn build_wx_push_message_for_teacher_register( // let mut tongzhi_array = vec![]; for admin_user_info in from_app_admin_user_infos { - let admin_user_openid = admin_user_info.openid.clone().unwrap(); + let admin_user_openid = admin_user_info.openid.clone() + .ok_or_else(|| anyhow::anyhow!("admin_user openid is required"))?; let admin_user = UserAppInfo::find_hty_user_by_openid(&admin_user_openid, conn)?; let admin_user_toapp_info = UserAppInfo::find_by_hty_id_and_app_id(&admin_user.hty_id, &to_app.app_id, conn)?; + let template_id = in_template_data.template_val.clone() + .ok_or_else(|| anyhow::anyhow!("template_val is required"))?; let push_message = ReqWxPushMessage { touser: admin_user_toapp_info.openid.clone(), // touser_hty_id: Some(admin_user.clone().hty_id), - template_id: in_template_data.template_val.clone().unwrap(), + template_id, url: Some(get_music_room_mini_url()), // todo: use PARAM to load domain miniprogram: Some(wx_mini_program.clone()), data: wx_message_data.clone(), @@ -127,8 +135,10 @@ fn build_wx_push_message_for_student_register( debug!("build_wx_push_message_for_student_register -> user_teacher -> {:?}", user_teacher); + let wx_id = from_app.clone().wx_id + .ok_or_else(|| anyhow::anyhow!("wx_id is required for from_app"))?; let wx_mini_program = ReqWxMiniProgram { - appid: from_app.clone().wx_id.unwrap(), + appid: wx_id, pagepath: "index".to_string(), }; @@ -143,7 +153,10 @@ fn build_wx_push_message_for_student_register( debug!("build_wx_push_message_for_student_register -> _in_template -> {:?}", _in_template); debug!("build_wx_push_message_for_student_register -> in_template_data -> {:?}", in_template_data); - let mut wx_message_data = in_template_data.template_text.clone().unwrap().clone().val.unwrap(); + let mut wx_message_data = in_template_data.template_text.clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; debug!("build_wx_push_message_for_student_register -> BEFORE wx_message_data -> {:?}", wx_message_data); @@ -162,9 +175,11 @@ fn build_wx_push_message_for_student_register( debug!("build_wx_push_message_for_student_register -> AFTER wx_message_data -> {:?}", wx_message_data); + let template_id = in_template_data.template_val.clone() + .ok_or_else(|| anyhow::anyhow!("template_val is required"))?; Ok(ReqWxPushMessage { touser: user_teacher.openid.clone(), - template_id: in_template_data.template_val.clone().unwrap(), + template_id, url: Some(get_music_room_mini_url()), miniprogram: Some(wx_mini_program.clone()), data: wx_message_data.clone(), @@ -181,8 +196,10 @@ fn build_wx_push_message_for_student_register_success( ) -> anyhow::Result> { let user_student = UserAppInfo::find_by_hty_id_and_app_id(id_student, &to_app.app_id, conn)?; + let wx_id = from_app.clone().wx_id + .ok_or_else(|| anyhow::anyhow!("wx_id is required for from_app"))?; let wx_mini_program = ReqWxMiniProgram { - appid: from_app.clone().wx_id.unwrap(), + appid: wx_id, pagepath: "index".to_string(), }; @@ -193,7 +210,10 @@ fn build_wx_push_message_for_student_register_success( &to_app.app_id.clone(), conn)?; - let mut wx_message_data = in_template_data.template_text.clone().unwrap().clone().val.unwrap(); + let mut wx_message_data = in_template_data.template_text.clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; let val_keyword1 = wx_message_data.keyword1.value; let val_keyword2 = wx_message_data.keyword2.value; @@ -208,9 +228,11 @@ fn build_wx_push_message_for_student_register_success( .replace("DAY", current_datetime.day().to_string().as_str()) }; + let template_id = in_template_data.template_val.clone() + .ok_or_else(|| anyhow::anyhow!("template_val is required"))?; Ok(ReqWxPushMessage { touser: user_student.openid.clone(), - template_id: in_template_data.template_val.clone().unwrap(), + template_id, url: Some(get_music_room_mini_url()), miniprogram: Some(wx_mini_program.clone()), data: wx_message_data.clone(), @@ -231,8 +253,10 @@ fn build_wx_push_message_for_teacher_register_success( // let template_id = String::from(env::var("WX_MSG_TEACHER_REGISTER_SUCCESS")?.to_string()); + let wx_id = from_app.clone().wx_id + .ok_or_else(|| anyhow::anyhow!("wx_id is required for from_app"))?; let wx_mini_program = ReqWxMiniProgram { - appid: from_app.clone().wx_id.unwrap(), + appid: wx_id, pagepath: "index".to_string(), }; @@ -245,7 +269,10 @@ fn build_wx_push_message_for_teacher_register_success( debug!("build_wx_push_message_for_teacher_register_success -> {:?} / {:?}", &in_template, &in_template_data); - let mut wx_message_data = in_template_data.template_text.clone().unwrap().clone().val.unwrap(); + let mut wx_message_data = in_template_data.template_text.clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; let val_keyword1 = wx_message_data.keyword1.value; let val_keyword2 = wx_message_data.keyword2.value; @@ -258,9 +285,11 @@ fn build_wx_push_message_for_teacher_register_success( }; + let template_id = in_template_data.template_val.clone() + .ok_or_else(|| anyhow::anyhow!("template_val is required"))?; let resp = ReqWxPushMessage { touser: teacher_toapp_info.openid, - template_id: in_template_data.template_val.clone().unwrap(), + template_id, url: Some(get_music_room_mini_url()), miniprogram: Some(wx_mini_program.clone()), data: wx_message_data.clone(), @@ -287,8 +316,10 @@ fn build_wx_push_message_for_reject_register( // let template_id = String::from(env::var("WX_MSG_REJECT_REGISTER")?.to_string()); + let wx_id = from_app.clone().wx_id + .ok_or_else(|| anyhow::anyhow!("wx_id is required for from_app"))?; let wx_mini_program = ReqWxMiniProgram { - appid: from_app.clone().wx_id.unwrap(), + appid: wx_id, pagepath: "index".to_string(), }; @@ -303,7 +334,10 @@ fn build_wx_push_message_for_reject_register( debug!("build_wx_push_message_for_reject_register -> {:?} / {:?}", &in_template, &in_template_data); - let mut wx_message_data = in_template_data.template_text.clone().unwrap().clone().val.unwrap(); + let mut wx_message_data = in_template_data.template_text.clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; debug!("build_wx_push_message_for_reject_register BEFORE -> msg: {:?}", &wx_message_data); // keyword1目前是模版里面写死的. let val_keyword2 = wx_message_data.keyword2.value; @@ -324,9 +358,11 @@ fn build_wx_push_message_for_reject_register( debug!("build_wx_push_message_for_reject_register AFTER -> msg: {:?}", &wx_message_data); + let template_id = in_template_data.template_val.clone() + .ok_or_else(|| anyhow::anyhow!("template_val is required"))?; Ok(ReqWxPushMessage { touser: user.openid.clone(), - template_id: in_template_data.template_val.clone().unwrap(), + template_id, url: Some(get_music_room_mini_url()), miniprogram: Some(wx_mini_program.clone()), data: wx_message_data.clone(), @@ -365,8 +401,8 @@ pub async fn raw_notify( let id_role_student = role_student.hty_role_id.clone(); let id_role_admin = role_admin.hty_role_id.clone(); - let from_app = if push_info.from_app_id.is_some() { - HtyApp::find_by_id(&push_info.clone().from_app_id.unwrap(), extract_conn(fetch_db_conn(&db_pool)?).deref_mut())? + let from_app = if let Some(from_app_id) = push_info.from_app_id.clone() { + HtyApp::find_by_id(&from_app_id, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())? } else { crate::get_app_from_host((*host).clone(), extract_conn(fetch_db_conn(&db_pool)?).deref_mut())? }; @@ -397,7 +433,9 @@ pub async fn raw_notify( for message in push_messages.clone() { // let first_value = push_message.data.first.value.clone(); - let send_to = HtyUser::find_by_openid(&message.touser.clone().unwrap(), extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; + let touser = message.touser.clone() + .ok_or_else(|| anyhow::anyhow!("touser is required in message"))?; + let send_to = HtyUser::find_by_openid(&touser, extract_conn(fetch_db_conn(&db_pool)?).deref_mut())?; let tongzhi = build_hty_tongzhi( &String::from("teacher_register"), diff --git a/htyuc/src/r_uc.rs b/htyuc/src/r_uc.rs index 2d98ea8..d1b336b 100644 --- a/htyuc/src/r_uc.rs +++ b/htyuc/src/r_uc.rs @@ -7,6 +7,7 @@ use crate::uc_rocket; pub async fn main() { dotenv().ok(); - let rocket = launch_rocket(get_uc_port(), uc_rocket(&get_uc_db_url())); - rocket.await; + let port = get_uc_port().expect("Failed to get UC_PORT"); + let rocket = launch_rocket(port, uc_rocket(&get_uc_db_url())); + rocket.await.expect("Failed to launch rocket"); } diff --git a/htyuc/src/test_scaffold.rs b/htyuc/src/test_scaffold.rs deleted file mode 100644 index ec741f2..0000000 --- a/htyuc/src/test_scaffold.rs +++ /dev/null @@ -1,460 +0,0 @@ -// use htycommons::db::get_uc_db_url; -// use htycommons::logger::logger_init; -// use htycommons::common::{APP_STATUS_ACTIVE, current_local_datetime}; -// use htycommons::{db, pass_or_panic, uuid}; -// use htycommons::cert::{generate_cert_key_pair}; -// use std::collections::HashMap; -// // use std::ops::DerefMut; -// use std::sync::Once; -// use diesel::PgConnection; -// use htycommons::jwt::jwt_encode_token; -// use htycommons::test_scaffold::TestScaffold; -// use htycommons::web::{HtyToken, ReqHtyLabel, ReqHtyRole}; -// use crate::{ActionLabel, AppFromTo, AppRole, HtyAction, HtyApp, HtyGongGao, HtyLabel, HtyResource, HtyRole, HtyTemplate, HtyTemplateData, HtyTongzhi, HtyUser, HtyUserGroup, RoleAction, RoleLabel, UserAppInfo, UserInfoRole}; -// use crate::ddl::uc_ddl; -// use crate::models::{HtyTag, HtyTagRef}; -// -// static INIT: Once = Once::new(); -// -// pub fn test_init() { -// INIT.call_once(|| { -// logger_init(); -// () -// }); -// } -// -// pub fn mocked_user(uuid: &str) -> HtyUser { -// HtyUser { -// hty_id: uuid.to_string(), -// union_id: None, -// enabled: false, -// created_at: None, -// real_name: None, -// sex: None, -// mobile: None, -// } -// } -// -// pub fn mocked_user_with_unionid(uuid: &str) -> HtyUser { -// HtyUser { -// hty_id: uuid.to_string(), -// union_id: Some("test_union".to_string()), -// enabled: false, -// created_at: None, -// real_name: None, -// sex: None, -// mobile: None, -// } -// } -// -// pub fn mocked_app(app_id: &str, secret: &str, domain: &str) -> HtyApp { -// let key_pair = generate_cert_key_pair().unwrap(); -// let priv_key = key_pair.privkey; -// let pub_key = key_pair.pubkey; -// -// HtyApp { -// app_id: app_id.to_string(), -// wx_secret: Some(secret.to_string()), -// domain: Some(domain.to_string()), -// app_status: APP_STATUS_ACTIVE.to_string(), -// app_desc: None, -// pubkey: pub_key, -// privkey: priv_key, -// wx_id: None, -// is_wx_app: Some(false), -// } -// } -// -// pub fn mocked_info( -// openid: &str, -// hty_id: &str, -// app_id: &str, -// username: &str, -// password: &str, -// is_registered: bool, -// ) -> UserAppInfo { -// UserAppInfo { -// openid: Some(openid.to_string()), -// hty_id: hty_id.to_string(), -// app_id: Some(app_id.to_string()), -// is_registered, -// id: uuid(), -// username: Some(username.to_string()), -// password: Some(password.to_string()), -// meta: None, -// created_at: None, -// teacher_info: None, -// student_info: None, -// reject_reason: None, -// needs_refresh: None, -// avatar_url: None, -// } -// } -// -// pub fn mocked_info_role(id: &str, user_info_id: &str, role_id: &str) -> UserInfoRole { -// UserInfoRole { -// the_id: id.to_string(), -// user_info_id: user_info_id.to_string(), -// role_id: role_id.to_string(), -// } -// } -// -// pub fn mocked_hty_role(role_id: &str, role_name: &str, role_desc: &str) -> HtyRole { -// HtyRole { -// hty_role_id: role_id.to_string(), -// role_key: role_name.to_string(), -// role_desc: Some(role_desc.to_string()), -// role_status: APP_STATUS_ACTIVE.to_string(), -// style: None, -// role_name: None, -// } -// } -// -// pub fn mocked_hty_label(label_id: &str, label_name: &str, label_desc: &str) -> HtyLabel { -// HtyLabel { -// hty_label_id: label_id.to_string(), -// label_name: label_name.to_string(), -// label_desc: Some(label_desc.to_string()), -// label_status: APP_STATUS_ACTIVE.to_string(), -// style: None, -// } -// } -// -// pub fn mocked_hty_action(action_id: &str, action_name: &str, action_desc: &str) -> HtyAction { -// HtyAction { -// hty_action_id: action_id.to_string(), -// action_name: action_name.to_string(), -// action_desc: Some(action_desc.to_string()), -// action_status: APP_STATUS_ACTIVE.to_string(), -// } -// } -// -// pub fn mocked_role_label(the_id: &str, role_id: &str, label_id: &str) -> RoleLabel { -// RoleLabel { -// the_id: the_id.to_string(), -// role_id: role_id.to_string(), -// label_id: label_id.to_string(), -// } -// } -// -// pub fn mocked_role_action(the_id: &str, role_id: &str, action_id: &str) -> RoleAction { -// RoleAction { -// the_id: the_id.to_string(), -// role_id: role_id.to_string(), -// action_id: action_id.to_string(), -// } -// } -// -// pub fn mocked_action_label(the_id: &str, action_id: &str, label_id: &str) -> ActionLabel { -// ActionLabel { -// the_id: the_id.to_string(), -// action_id: action_id.to_string(), -// label_id: label_id.to_string(), -// } -// } -// -// pub fn mocked_app_role(the_id: &str, app_id: &str, role_id: &str) -> AppRole { -// AppRole { -// the_id: the_id.to_string(), -// app_id: app_id.to_string(), -// role_id: role_id.to_string(), -// } -// } -// -// pub fn get_mocked_root_token() -> anyhow::Result { -// let label_root = ReqHtyLabel { -// hty_label_id: None, -// label_name: Some("SYS_ROOT".to_string()), -// label_desc: None, -// label_status: None, -// roles: None, -// actions: None, -// style: None, -// }; -// -// let role_root = ReqHtyRole { -// hty_role_id: None, -// user_app_info_id: None, -// app_ids: None, -// role_key: None, -// role_desc: None, -// role_status: None, -// labels: Some(vec![label_root]), -// actions: None, -// style: None, -// role_name: None, -// }; -// -// let token = HtyToken { -// token_id: uuid(), -// hty_id: Some(uuid()), -// app_id: None, -// ts: current_local_datetime(), -// roles: Some(vec![role_root]), -// tags: None, -// }; -// -// Ok(jwt_encode_token(token)?) -// } -// -// pub struct HtyucTestScaffold {} -// -// impl TestScaffold for HtyucTestScaffold { -// fn before_test(self: &Self) -> anyhow::Result> { -// dotenv::dotenv().ok(); -// let uc_pool = db::pool(&get_uc_db_url()); -// // let conn = *&uc_pool.get().unwrap().deref_mut(); -// test_init(); -// delete_all_uc(&mut uc_pool.get().unwrap()); -// uc_ddl(); -// -// let hty_id1 = uuid(); -// -// let new_user1 = mocked_user(hty_id1.as_str()); -// -// let _created_user1 = HtyUser::create(&new_user1, &mut uc_pool.get().unwrap()); -// -// // ---- -// let hty_id2 = uuid(); -// let new_user2 = mocked_user(hty_id2.as_str()); -// -// let _created_user2 = HtyUser::create(&new_user2, &mut uc_pool.get().unwrap()); -// -// -// // ---- -// let hty_id3 = uuid(); -// let new_user3 = mocked_user_with_unionid(hty_id3.as_str()); -// let _created_user3 = HtyUser::create(&new_user3, &mut uc_pool.get().unwrap()); -// -// let app_id = "test_app_id"; -// -// let new_app = mocked_app(app_id, "test_secret", "mocked_app"); -// -// let _created_app = HtyApp::create(&new_app, &mut uc_pool.get().unwrap()); -// -// // --- -// -// let new_info1 = mocked_info( -// "test_openid1", -// hty_id1.as_str(), -// app_id, -// "test_user1", -// "", -// false, -// ); -// -// let created_info1 = UserAppInfo::create(&new_info1.clone(), &mut uc_pool.get().unwrap())?; -// -// let hty_role1 = mocked_hty_role(uuid().as_str(), "test_read_role", ""); -// let created_hty_role1 = HtyRole::create(&hty_role1, &mut uc_pool.get().unwrap())?; -// -// let app_role = mocked_app_role( -// uuid().as_str(), -// app_id.clone(), -// hty_role1.clone().hty_role_id.as_str(), -// ); -// -// AppRole::create(&app_role, &mut uc_pool.get().unwrap())?; -// -// let hty_action1 = mocked_hty_action(uuid().as_str(), "test_read_action", ""); -// let _created_hty_action1 = HtyAction::create(&hty_action1, &mut uc_pool.get().unwrap()); -// -// let hty_label1 = mocked_hty_label(uuid().as_str(), "test_read_label", ""); -// let _created_hty_label1 = HtyLabel::create(&hty_label1, &mut uc_pool.get().unwrap()); -// -// let hty_role2 = mocked_hty_role(uuid().as_str(), "test_write_role", ""); -// let created_hty_role2 = HtyRole::create(&hty_role2, &mut uc_pool.get().unwrap())?; -// -// let app_role2 = mocked_app_role( -// uuid().as_str(), -// app_id.clone(), -// hty_role2.clone().hty_role_id.as_str(), -// ); -// -// AppRole::create(&app_role2, &mut uc_pool.get().unwrap())?; -// -// let hty_action2 = mocked_hty_action(uuid().as_str(), "test_write_action", ""); -// let _created_hty_action2 = HtyAction::create(&hty_action2, &mut uc_pool.get().unwrap()); -// -// let hty_label2 = mocked_hty_label(uuid().as_str(), "test_write_label", ""); -// let _created_hty_label2 = HtyLabel::create(&hty_label2, &mut uc_pool.get().unwrap()); -// -// let hty_role3 = mocked_hty_role(uuid().as_str(), "test_execute_role", ""); -// let created_hty_role3 = HtyRole::create(&hty_role3, &mut uc_pool.get().unwrap())?; -// -// let hty_action3 = mocked_hty_action(uuid().as_str(), "test_execute_action", ""); -// let _created_hty_action3 = HtyAction::create(&hty_action3, &mut uc_pool.get().unwrap()); -// -// let hty_label3 = mocked_hty_label(uuid().as_str(), "test_execute_label", ""); -// let _created_hty_label3 = HtyLabel::create(&hty_label3, &mut uc_pool.get().unwrap()); -// -// let user1_info_role1 = mocked_info_role( -// uuid().as_str(), -// created_info1.clone().id.clone().as_str(), -// created_hty_role1.clone().hty_role_id.clone().as_str(), -// ); -// let _c_user1_info_role1 = UserInfoRole::create(&user1_info_role1, &mut uc_pool.get().unwrap()); -// -// let user1_info_role2 = mocked_info_role( -// uuid().as_str(), -// created_info1.clone().id.clone().as_str(), -// created_hty_role2.clone().hty_role_id.clone().as_str(), -// ); -// let _c_user1_info_role2 = UserInfoRole::create(&user1_info_role2, &mut uc_pool.get().unwrap()); -// -// let user1_info_role3 = mocked_info_role( -// uuid().as_str(), -// created_info1.clone().id.clone().as_str(), -// created_hty_role3.clone().hty_role_id.clone().as_str(), -// ); -// let _c_user1_info_role3 = UserInfoRole::create(&user1_info_role3, &mut uc_pool.get().unwrap()); -// -// let role1_action1 = mocked_role_action( -// uuid().as_str(), -// hty_role1.clone().hty_role_id.as_str(), -// hty_action1.clone().hty_action_id.as_str(), -// ); -// let _c_role1_action1 = RoleAction::create(&role1_action1, &mut uc_pool.get().unwrap()); -// -// let role1_label1 = mocked_role_label( -// uuid().as_str(), -// hty_role1.clone().hty_role_id.as_str(), -// hty_label1.clone().hty_label_id.as_str(), -// ); -// let _c_role1_action = RoleLabel::create(&role1_label1, &mut uc_pool.get().unwrap()); -// -// let role2_action2 = mocked_role_action( -// uuid().as_str(), -// hty_role2.clone().hty_role_id.as_str(), -// hty_action2.clone().hty_action_id.as_str(), -// ); -// let _c_role2_action2 = RoleAction::create(&role2_action2, &mut uc_pool.get().unwrap()); -// -// let action1_label1 = mocked_action_label( -// uuid().as_str(), -// hty_action1.clone().hty_action_id.as_str(), -// hty_label1.clone().hty_label_id.as_str(), -// ); -// let _c_action1_label1 = ActionLabel::create(&action1_label1, &mut uc_pool.get().unwrap()); -// -// // ---- -// // -// let new_info2 = mocked_info( -// "test_openid2", -// hty_id2.as_str(), -// app_id, -// "test_user2", -// "", -// false, -// ); -// let created_info2 = UserAppInfo::create(&new_info2, &mut uc_pool.get().unwrap())?; -// -// let user2_info_role3 = mocked_info_role( -// uuid().as_str(), -// created_info2.clone().id.clone().as_str(), -// created_hty_role3.clone().hty_role_id.clone().as_str(), -// ); -// let _c_user1_info_role3 = UserInfoRole::create(&user2_info_role3, &mut uc_pool.get().unwrap()); -// -// let new_info3 = mocked_info( -// "test_openid3", -// hty_id3.as_str(), -// app_id, -// "test_user3", -// "testpass", -// false, -// ); -// let created_info3 = UserAppInfo::create(&new_info3, &mut uc_pool.get().unwrap())?; -// -// let mut params = HashMap::new(); -// params.insert("hty_id1".to_string(), hty_id1); -// params.insert("created_info1".to_string(), created_info1.clone().id); -// params.insert("hty_id2".to_string(), hty_id2); -// params.insert("created_info2".to_string(), created_info2.clone().id); -// params.insert("hty_id3".to_string(), hty_id3); -// params.insert("created_info3".to_string(), created_info3.clone().id); -// params.insert("app_id".to_string(), app_id.to_string()); -// params.insert("hty_role1_id".to_string(), hty_role1.clone().hty_role_id); -// params.insert("hty_role2_id".to_string(), hty_role2.clone().hty_role_id); -// params.insert("hty_role3_id".to_string(), hty_role3.clone().hty_role_id); -// params.insert( -// "hty_action1_id".to_string(), -// hty_action1.clone().hty_action_id, -// ); -// params.insert( -// "hty_action2_id".to_string(), -// hty_action2.clone().hty_action_id, -// ); -// params.insert( -// "hty_action3_id".to_string(), -// hty_action3.clone().hty_action_id, -// ); -// params.insert("hty_label1_id".to_string(), hty_label1.clone().hty_label_id); -// params.insert("hty_label2_id".to_string(), hty_label2.clone().hty_label_id); -// params.insert("hty_label3_id".to_string(), hty_label3.clone().hty_label_id); -// -// let token = get_mocked_root_token()?; -// params.insert("root_token".to_string(), token); -// -// Ok(params) -// } -// -// fn after_test(self: &Self) { -// // let _ = dotenv::dotenv(); -// // let uc_pool = db::pool(&get_uc_db_url()); -// // match uc_pool.get() { -// // Ok(conn) => { -// // delete_all_uc(conn); -// // } -// // Err(e) => { -// // panic!("[AFTER TEST ERROR] -> {:?}", e) -// // } -// // } -// } -// } -// -// pub fn delete_all_uc(conn: &mut PgConnection) { -// // this should be deleted firstly -// pass_or_panic(HtyUserGroup::delete_all(conn)); -// -// pass_or_panic(HtyResource::delete_all(conn)); -// -// pass_or_panic(HtyTongzhi::delete_all(conn)); -// -// pass_or_panic(ActionLabel::delete_all(conn)); -// -// pass_or_panic(AppRole::delete_all(conn)); -// -// pass_or_panic(RoleAction::delete_all(conn)); -// -// pass_or_panic(RoleLabel::delete_all(conn)); -// -// pass_or_panic(HtyAction::delete_all(conn)); -// -// pass_or_panic(HtyLabel::delete_all(conn)); -// -// pass_or_panic(HtyTagRef::delete_all(conn)); -// -// pass_or_panic(HtyTag::delete_all(conn)); -// -// pass_or_panic(UserInfoRole::delete_all(conn)); -// -// pass_or_panic(HtyRole::delete_all(conn)); -// -// // delete all left infos -// pass_or_panic(UserAppInfo::delete_all(conn)); -// -// // delete all left users -// pass_or_panic(HtyUser::delete_all(conn)); -// -// pass_or_panic(AppFromTo::delete_all(conn)); -// -// pass_or_panic(HtyGongGao::delete_all(conn)); -// -// pass_or_panic(HtyTemplateData::::delete_all(conn)); -// -// pass_or_panic(HtyTemplate::delete_all(conn)); -// -// // delete all apps -// pass_or_panic(HtyApp::delete_all(conn)); -// } diff --git a/htyuc_models/src/models.rs b/htyuc_models/src/models.rs index d5b36c1..7c6de40 100644 --- a/htyuc_models/src/models.rs +++ b/htyuc_models/src/models.rs @@ -127,8 +127,7 @@ impl HtyUser { let mut q = hty_users::table.into_boxed(); q = q.order(created_at.desc()); - if keyword.is_some() { - let keyword_copy = keyword.clone().unwrap(); + if let Some(keyword_copy) = keyword.clone() { q = q.filter( real_name .ilike(format!("%{}%", keyword_copy.clone())) @@ -375,7 +374,11 @@ impl HtyUser { let task = move |in_params: Option)>>, conn: &mut PgConnection| -> anyhow::Result { - let (in_user, in_info) = in_params.unwrap().get("params").unwrap().clone(); + let params_map = in_params + .ok_or_else(|| anyhow::anyhow!("in_params is required"))?; + let (in_user, in_info) = params_map.get("params") + .ok_or_else(|| anyhow::anyhow!("params key is required"))? + .clone(); match HtyUser::create_with_info(&in_user, &in_info, conn) { Ok(hty_id) => Ok(hty_id), Err(e) => Err(anyhow!(HtyErr { @@ -472,10 +475,12 @@ impl HtyUser { let in_user: HtyUser; - if !user.is_none() { - in_user = user.clone().unwrap(); + if let Some(user_val) = user.clone() { + in_user = user_val; } else { - match HtyUser::find_by_hty_id(info.clone().unwrap().hty_id.as_str(), conn) { + let info_val = info.clone() + .ok_or_else(|| anyhow::anyhow!("info is required when user is None"))?; + match HtyUser::find_by_hty_id(info_val.hty_id.as_str(), conn) { Ok(u) => { in_user = u; } @@ -669,13 +674,13 @@ impl ReqHtyTemplateData { } let to_db: HtyTemplateData = HtyTemplateData { - id: self.id.clone().unwrap(), - app_id: self.app_id.clone().unwrap(), - template_id: self.template_id.clone().unwrap(), + id: self.id.clone().expect("id should not be None after check"), + app_id: self.app_id.clone().expect("app_id should not be None after check"), + template_id: self.template_id.clone().expect("template_id should not be None after check"), template_val: self.template_val.clone(), template_text: self.template_text.clone(), - created_at: self.created_at.clone().unwrap(), - created_by: self.created_by.clone().unwrap(), + created_at: self.created_at.clone().expect("created_at should not be None after check"), + created_by: self.created_by.clone().expect("created_by should not be None after check"), }; Ok(to_db) @@ -1113,7 +1118,7 @@ impl UserAppInfo { } match user_app_info::table - .filter(user_app_info::id.eq(req_info.id.clone().unwrap())) + .filter(user_app_info::id.eq(req_info.id.clone().expect("id should not be None after check"))) .first::(conn) { Ok(info) => Ok(info), @@ -1380,10 +1385,10 @@ impl UserAppInfo { Some(ReqHtyRole { hty_role_id: Some(role.clone().hty_role_id), user_app_info_id: Some(self.clone().id), - app_ids: if self.app_id.is_none() { - None + app_ids: if let Some(app_id) = self.app_id.clone() { + Some(vec![app_id]) } else { - Some(vec![self.app_id.clone().unwrap()]) + None }, role_key: Some(role.clone().role_key), role_desc: role.clone().role_desc, @@ -1417,13 +1422,13 @@ pub struct ReqHtyTongzhi { impl ReqHtyTongzhi { pub fn to_db_struct(&self) -> HtyTongzhi { HtyTongzhi { - tongzhi_id: self.tongzhi_id.clone().unwrap(), - app_id: self.app_id.clone().unwrap(), - tongzhi_type: self.tongzhi_type.clone().unwrap(), - tongzhi_status: self.tongzhi_status.clone().unwrap(), + tongzhi_id: self.tongzhi_id.clone().expect("tongzhi_id is required"), + app_id: self.app_id.clone().expect("app_id is required"), + tongzhi_type: self.tongzhi_type.clone().expect("tongzhi_type is required"), + tongzhi_status: self.tongzhi_status.clone().expect("tongzhi_status is required"), send_from: self.send_from.clone(), - send_to: self.send_to.clone().unwrap(), - created_at: self.created_at.clone().unwrap(), + send_to: self.send_to.clone().expect("send_to is required"), + created_at: self.created_at.clone().expect("created_at is required"), content: self.content.clone(), meta: self.meta.clone(), role_id: self.role_id.clone(), // 一个用户可能有多种角色,每种角色接受各自的通知.(例如:作为学生接收学生通知;作为老师接收老师通知.) @@ -1484,11 +1489,11 @@ impl ReqUserAppInfo { } Ok(UserAppInfo { - hty_id: self.hty_id.clone().unwrap(), + hty_id: self.hty_id.clone().expect("hty_id should not be None after check"), app_id: self.app_id.clone(), openid: self.openid.clone(), is_registered: self.is_registered, - id: self.id.clone().unwrap(), + id: self.id.clone().expect("id should not be None after check"), username: self.username.clone(), password: self.password.clone(), meta: self.meta.clone(), @@ -1553,11 +1558,13 @@ impl HtyApp { .first::(conn) { Ok(app) => { + let pubkey = app.pubkey.clone() + .ok_or_else(|| anyhow::anyhow!("pubkey is not set for app"))?; debug!( "find_pubkey_by_id -> find pubkey : {}", - app.pubkey.clone().unwrap() + pubkey ); - Ok(app.pubkey.unwrap()) + Ok(pubkey) } Err(e) => { error!("find_pubkey_by_id -> err -> {:?}", e); @@ -1576,7 +1583,9 @@ impl HtyApp { .first::(conn) { Ok(app) => { - match encrypt_text_with_private_key(app.privkey.unwrap(), app.app_id.clone()) { + let privkey = app.privkey + .ok_or_else(|| anyhow::anyhow!("privkey is not set for app"))?; + match encrypt_text_with_private_key(privkey, app.app_id.clone()) { Ok(encrypt_app_id) => { debug!( "get_encrypt_app_id -> encrypt app id : {}", @@ -1856,12 +1865,12 @@ impl HtyResource { Ok(Self { filename: req.filename, - app_id: req_app_id.unwrap(), - hty_resource_id: req_hty_resource_id.unwrap(), + app_id: req_app_id?, + hty_resource_id: req_hty_resource_id?, created_at: Some(req_created_at), - url: req_url.unwrap(), + url: req_url?, res_type: req.res_type, - created_by: Some(req_created_by.unwrap()), + created_by: Some(req_created_by?), tasks: req.tasks.clone(), compress_processed: req.compress_processed.clone(), updated_at: req.updated_at.clone(), @@ -1935,10 +1944,10 @@ impl HtyResource { Self { filename: req.filename, - app_id: req_app_id.unwrap(), + app_id: req_app_id?, hty_resource_id: uuid(), created_at: Some(current_local_datetime()), - url: req_url.unwrap(), + url: req_url?, res_type: 1, created_by: None, } @@ -3538,30 +3547,31 @@ impl HtyTongzhi { hty_id ); - if hty_id.is_some() { + if let Some(hty_id_val) = hty_id.clone() { if keyword.is_some() { //后续如果有新增搜索功能再填充 q = q - .filter(send_to.eq(hty_id.unwrap())); + .filter(send_to.eq(hty_id_val.clone())); } else { q = q - .filter(send_to.eq(hty_id.unwrap())); + .filter(send_to.eq(hty_id_val.clone())); } } else if keyword.is_some() { // todo: 这里有keyword搜索吗? - q = q - .filter(send_to.eq(hty_id.unwrap())); - + if let Some(hty_id_val) = hty_id.clone() { + q = q + .filter(send_to.eq(hty_id_val)); + } } - if the_tongzhi_status.is_some() { - q = q.filter(tongzhi_status.eq(the_tongzhi_status.clone().unwrap())) + if let Some(tongzhi_status_val) = the_tongzhi_status.clone() { + q = q.filter(tongzhi_status.eq(tongzhi_status_val)) } - if the_role_id.is_some() { - q = q.filter(role_id.eq(the_role_id.clone().unwrap())) + if let Some(role_id_val) = the_role_id.clone() { + q = q.filter(role_id.eq(role_id_val)) } q = q.order(created_at.desc()); @@ -3966,7 +3976,10 @@ impl HtyTemplateData .first::>(conn) { Ok(data) => { - let text = data.template_text.unwrap().val.unwrap(); + let text = data.template_text + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; debug!( "find_with_template_id_and_app_id -> template_text: {:?}", text @@ -4028,7 +4041,10 @@ impl HtyTemplateData .first::>(conn) { Ok(data) => { - let text = data.template_text.unwrap().val.unwrap(); + let text = data.template_text + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? + .val + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; debug!( "find_with_template_id_and_app_id_with_string -> template_text: {:?}", text @@ -4203,16 +4219,16 @@ impl HtyUserRels { use crate::schema::hty_user_rels::columns::*; let mut q = hty_user_rels::table.into_boxed(); - if in_rel_type.is_some() { - q = q.filter(rel_type.eq(in_rel_type.clone().unwrap())); + if let Some(rel_type_val) = in_rel_type.clone() { + q = q.filter(rel_type.eq(rel_type_val)); } - if in_from_user_id.is_some() { - q = q.filter(from_user_id.eq(in_from_user_id.clone().unwrap())) + if let Some(from_user_id_val) = in_from_user_id.clone() { + q = q.filter(from_user_id.eq(from_user_id_val)) } - if in_to_user_id.is_some() { - q = q.filter(to_user_id.eq(in_to_user_id.clone().unwrap())) + if let Some(to_user_id_val) = in_to_user_id.clone() { + q = q.filter(to_user_id.eq(to_user_id_val)) } match q.load::(conn) { diff --git a/htyuc_models/src/wx.rs b/htyuc_models/src/wx.rs index be2b404..2380e47 100644 --- a/htyuc_models/src/wx.rs +++ b/htyuc_models/src/wx.rs @@ -63,9 +63,7 @@ pub fn identify2(id: &WxId, app_id: &String, conn: &mut PgConnection) -> anyhow: avatar_url: None, }; - hty_id = HtyUser::create_with_info_with_tx(&new_user, &Some(new_info), conn) - .ok() - .unwrap() + hty_id = HtyUser::create_with_info_with_tx(&new_user, &Some(new_info), conn)? .clone(); Ok(HtyToken { @@ -96,14 +94,16 @@ pub async fn get_or_save_wx_access_token(app: &HtyApp, force_refresh: bool) -> a // force_refresh = true or // token not in cache, refresh the token by accessing WX API. let client = reqwest::Client::new(); - let id_wx = app.wx_id.clone().unwrap(); - let secret = app.wx_secret.clone(); + let id_wx = app.wx_id.clone() + .ok_or_else(|| anyhow::anyhow!("wx_id is required"))?; + let secret = app.wx_secret.clone() + .ok_or_else(|| anyhow::anyhow!("wx_secret is required"))?; let url = "https://api.weixin.qq.com/cgi-bin/token"; - debug!("app -> {:?}, wx_id = {:?}, secret = {:?}", app.app_desc.clone().unwrap(), id_wx.clone(), secret.clone()); + debug!("app -> {:?}, wx_id = {:?}, secret = {:?}", app.app_desc.clone(), id_wx.clone(), secret.clone()); let resp = client .get(url) - .query(&[("grant_type", "client_credential"), ("appid", id_wx.clone().as_str()), ("secret", secret.clone().unwrap().as_str())]) + .query(&[("grant_type", "client_credential"), ("appid", id_wx.clone().as_str()), ("secret", secret.as_str())]) .send().await? .text().await?; @@ -121,15 +121,19 @@ pub async fn get_or_save_wx_access_token(app: &HtyApp, force_refresh: bool) -> a reason: Some(format!("Get Wx access token met error. Error code: {:?}, Error msg: {:?} ", access_token.errcode, access_token.errmsg).to_string()) })); } - let access_token_str = access_token.access_token.unwrap(); - let exp = access_token.expires_in.unwrap() / 2; + let access_token_str = access_token.access_token + .ok_or_else(|| anyhow::anyhow!("access_token is missing in response"))?; + let exp = access_token.expires_in + .ok_or_else(|| anyhow::anyhow!("expires_in is missing in response"))? / 2; save_kv_to_redis_with_exp_secs(&token_id, &access_token_str, exp)?; Ok(access_token_str) } async fn fn_get_jsapi_ticket(app: Option, _: Option>, _: Option, token: String) -> anyhow::Result<(Option, Option, Option)> { + let app_ref = app.as_ref() + .ok_or_else(|| anyhow::anyhow!("app is required"))?; let mut token_id = WX_JSAPI_TICKET_PREFIX.to_string(); - token_id.push_str(app.clone().unwrap().app_id.as_str()); + token_id.push_str(app_ref.app_id.as_str()); let is_ticket_available = is_key_exist_in_redis(&token_id)?; @@ -154,14 +158,18 @@ async fn fn_get_jsapi_ticket(app: Option, _: Option debug!("fn_get_jsapi_ticket -> wx_ticket -> {:?}", jsapi_ticket); - if jsapi_ticket.errcode.clone().unwrap() != 0 { - return Err(anyhow!(HtyErr { - code: HtyErrCode::WebErr, - reason: Some(format!("Get Wx jsapi_ticket met error. Error code: {:?}, Error msg: {:?} ", jsapi_ticket.errcode, jsapi_ticket.errmsg).to_string()) - })); + if let Some(errcode) = jsapi_ticket.errcode.clone() { + if errcode != 0 { + return Err(anyhow!(HtyErr { + code: HtyErrCode::WebErr, + reason: Some(format!("Get Wx jsapi_ticket met error. Error code: {:?}, Error msg: {:?} ", jsapi_ticket.errcode, jsapi_ticket.errmsg).to_string()) + })); + } } - let ticket = jsapi_ticket.ticket.unwrap(); - let exp = jsapi_ticket.expires_in.unwrap(); + let ticket = jsapi_ticket.ticket + .ok_or_else(|| anyhow::anyhow!("ticket is missing in response"))?; + let exp = jsapi_ticket.expires_in + .ok_or_else(|| anyhow::anyhow!("expires_in is missing in response"))?; save_kv_to_redis_with_exp_secs(&token_id, &ticket, exp)?; @@ -169,7 +177,8 @@ async fn fn_get_jsapi_ticket(app: Option, _: Option } pub async fn get_jsapi_ticket(app: &HtyApp) -> anyhow::Result { - Ok(get_access_code_and_call_wx_func(fn_get_jsapi_ticket, Some(app.clone()), None, None).await?.unwrap()) + get_access_code_and_call_wx_func(fn_get_jsapi_ticket, Some(app.clone()), None, None).await? + .ok_or_else(|| anyhow::anyhow!("Failed to get jsapi_ticket")) } pub async fn get_cached_wx_all_follower_openids(app: &HtyApp) -> anyhow::Result> { @@ -180,7 +189,8 @@ pub async fn refresh_cache_and_get_wx_all_follower_openids(app: &HtyApp) -> anyh // let token = get_or_save_wx_access_token(app, false).await?; let none: Option> = None; - Ok(get_access_code_and_call_wx_func(fn_refresh_cache_and_get_wx_all_follower_openids, Some(app.clone()), none, None).await?.unwrap()) + get_access_code_and_call_wx_func(fn_refresh_cache_and_get_wx_all_follower_openids, Some(app.clone()), none, None).await? + .ok_or_else(|| anyhow::anyhow!("Failed to get follower openids")) } pub async fn fn_refresh_cache_and_get_wx_all_follower_openids(app: Option, @@ -201,9 +211,12 @@ pub async fn fn_refresh_cache_and_get_wx_all_follower_openids get resp from weixin {:?}", req_followers); - let openids = req_followers.data.openid.unwrap(); + let openids = req_followers.data.openid + .ok_or_else(|| anyhow::anyhow!("openid is missing in response"))?; let json_openids = serde_json::to_string(&openids)?; - let _ = save_kv_to_redis(&all_openids_prefix(&app.unwrap().app_id), &json_openids)?; + let app_ref = app.as_ref() + .ok_or_else(|| anyhow::anyhow!("app is required"))?; + let _ = save_kv_to_redis(&all_openids_prefix(&app_ref.app_id), &json_openids)?; Ok((Some(openids), req_followers.errcode.clone(), req_followers.errmsg.clone())) } else { let resp_body = resp.text().await?; @@ -230,10 +243,12 @@ pub async fn fn_refresh_and_get_wx_follower_info get follower info {:?}", req_follower_info); - let _ = save_kv_to_redis(&openid_info_prefix(&req_follower_info.clone().openid, &app.clone().unwrap().app_id), + let app_ref = app.as_ref() + .ok_or_else(|| anyhow::anyhow!("app is required"))?; + let _ = save_kv_to_redis(&openid_info_prefix(&req_follower_info.clone().openid, &app_ref.app_id), &json_follower_info.to_string())?; Ok((Some(req_follower_info.clone()), req_follower_info.errcode.clone(), req_follower_info.errmsg.clone())) @@ -261,7 +278,8 @@ pub async fn fn_refresh_and_get_wx_follower_info anyhow::Result { let none: Option> = None; - Ok(get_access_code_and_call_wx_func(fn_refresh_and_get_wx_follower_info, Some(app.clone()), none, Some(openid.clone())).await?.unwrap()) + get_access_code_and_call_wx_func(fn_refresh_and_get_wx_follower_info, Some(app.clone()), none, Some(openid.clone())).await? + .ok_or_else(|| anyhow::anyhow!("Failed to get follower info")) } @@ -320,18 +338,21 @@ pub async fn get_access_code_and_call_wx_func(wx_func: F, let mut retry = 0; let mut some_wx_call_resp = None; + let to_app_ref = to_app.as_ref() + .ok_or_else(|| anyhow::anyhow!("to_app is required"))?; + while retry < 3 && !ok { let wx_token = if retry == 0 { - get_or_save_wx_access_token(&to_app.clone().unwrap(), false).await? + get_or_save_wx_access_token(to_app_ref, false).await? } else { - get_or_save_wx_access_token(&to_app.clone().unwrap(), true).await? + get_or_save_wx_access_token(to_app_ref, true).await? }; let (wx_call_resp, wx_call_err_code, wx_call_err_msg) = wx_func(to_app.clone(), wx_push_message.clone(), openid.clone(), wx_token).await?; debug!("get_access_code_and_call_wx_func -> OK / wx_call_resp: {:?} / wx_call_err_code: {:?} / wx_call_err_msg: {:?}", wx_call_resp, wx_call_err_code, wx_call_err_msg); - if wx_call_err_code.is_none() || (wx_call_err_code.is_some() && wx_call_err_code.unwrap() == 0) { + if wx_call_err_code.is_none() || (wx_call_err_code.is_some() && wx_call_err_code.as_ref().unwrap() == &0) { ok = true; some_wx_call_resp = wx_call_resp; } else { @@ -398,7 +419,9 @@ pub async fn fn_push_wx_message( // todo: check NULL of wx_push_message debug!("fn_push_wx_message -> to_app: {:?} / wx_push_message: {:?} / token: {:?}", _to_app, wx_push_message, token); let wx_url = "https://api.weixin.qq.com/cgi-bin/message/template/send"; - let post_body = serde_json::to_string::>(&wx_push_message.unwrap())?; + let wx_push_message_ref = wx_push_message + .ok_or_else(|| anyhow::anyhow!("wx_push_message is required"))?; + let post_body = serde_json::to_string::>(&wx_push_message_ref)?; debug!("fn_push_wx_message -> post wx body {:?} ", post_body); @@ -423,20 +446,22 @@ pub async fn fn_push_wx_message( pub async fn push_wx_message(to_app: &HtyApp, wx_push_message: &ReqWxPushMessage) -> anyhow::Result<()> { debug!("push_wx_message START -> to_app: {:?} / wx_push_message: {:?}", to_app, wx_push_message); - if skip_wx_push() { + if skip_wx_push().unwrap_or(false) { debug!("push_wx_message() ::BYPASSED::"); Ok(()) } else { - if wx_push_message.touser.is_none() || wx_push_message.touser.clone().unwrap().trim().is_empty() { + if wx_push_message.touser.is_none() || wx_push_message.touser.as_ref().map(|s| s.trim().is_empty()).unwrap_or(true) { debug!("push_wx_message() ::TO_USER_OPENID IS NULL:: 无法推送消息"); Ok(()) } else { let wx_push_resp = get_access_code_and_call_wx_func(fn_push_wx_message, Some(to_app.clone()), Some(wx_push_message.clone()), - None).await?.unwrap(); + None).await? + .ok_or_else(|| anyhow::anyhow!("Failed to push wx message"))?; debug!("push_wx_message -> wx_push_resp -> {:?}", wx_push_resp); - let resp_code = wx_push_resp.errcode.unwrap(); + let resp_code = wx_push_resp.errcode + .ok_or_else(|| anyhow::anyhow!("errcode is missing in response"))?; if resp_code == 0 { Ok(()) } else { @@ -453,7 +478,9 @@ macro_rules! remote_send_tongzhi_and_push_wx_message { // huiwingn内部通知(小程序内部) let r_created_tongzhi_id = create_tongzhi(&$req_hty_tongzhi, &$sudoer_copy).await; // 推送公众号小程序通知. - let _ = ::htyuc_models::wx::push_wx_message2(&$to_app, &$push_message, Some(r_created_tongzhi_id.unwrap())).await; + if let Ok(tongzhi_id) = r_created_tongzhi_id { + let _ = ::htyuc_models::wx::push_wx_message2(&$to_app, &$push_message, Some(tongzhi_id)).await; + } }); } } @@ -485,29 +512,31 @@ pub async fn push_wx_message2(to_app: &HtyA let mut wx_push_message = in_wx_push_message.clone(); - if some_created_hty_tongzhi_id.is_some() && in_wx_push_message.miniprogram.is_some() { - let mut c_miniprogram = in_wx_push_message.miniprogram.clone().unwrap(); - c_miniprogram.pagepath = format!("pages/index/index?hty_tongzhi_id={}", some_created_hty_tongzhi_id.clone().unwrap()); - // c_miniprogram.path = format!("sample?hty_tongzhi_id={}", some_created_hty_tongzhi_id.clone().unwrap()); + if let (Some(tongzhi_id), Some(miniprogram)) = (some_created_hty_tongzhi_id.as_ref(), in_wx_push_message.miniprogram.as_ref()) { + let mut c_miniprogram = miniprogram.clone(); + c_miniprogram.pagepath = format!("pages/index/index?hty_tongzhi_id={}", tongzhi_id); + // c_miniprogram.path = format!("sample?hty_tongzhi_id={}", tongzhi_id); wx_push_message.miniprogram = Some(c_miniprogram); } debug!("push_wx_message2 -> {:?}", wx_push_message); - if skip_wx_push() { + if skip_wx_push().unwrap_or(false) { debug!("push_wx_message2() ::BYPASSED::"); Ok(()) } else { - if wx_push_message.touser.is_none() || wx_push_message.touser.clone().unwrap().trim().is_empty() { + if wx_push_message.touser.is_none() || wx_push_message.touser.as_ref().map(|s| s.trim().is_empty()).unwrap_or(true) { debug!("push_wx_message2() ::TO_USER_OPENID IS NULL:: 无法推送消息"); Ok(()) } else { let wx_push_resp = get_access_code_and_call_wx_func(fn_push_wx_message, Some(to_app.clone()), Some(wx_push_message.clone()), - None).await?.unwrap(); + None).await? + .ok_or_else(|| anyhow::anyhow!("Failed to push wx message"))?; debug!("push_wx_message2 -> wx_push_resp: {:?}", wx_push_resp); - let resp_code = wx_push_resp.errcode.unwrap(); + let resp_code = wx_push_resp.errcode + .ok_or_else(|| anyhow::anyhow!("errcode is missing in response"))?; if resp_code == 0 { Ok(()) } else { @@ -542,7 +571,8 @@ pub async fn get_union_id_by_auth_code(wx_id: String, secret: String, code: Stri })); } - let union_id_str = access_token.unionid.unwrap(); + let union_id_str = access_token.unionid + .ok_or_else(|| anyhow::anyhow!("unionid is missing in response"))?; debug!("get_union_id_by_auth_code -> union_id_str -> {:?}", union_id_str); @@ -559,21 +589,21 @@ pub fn extract_template_data_and_wx_message_data_from_template< req_in_template ); - let in_template_data = req_in_template + let datas = req_in_template .datas .clone() - .unwrap() + .ok_or_else(|| anyhow::anyhow!("datas is required"))?; + let first_data = datas .get(0) // just assume we have only one template data. - .clone() - .unwrap() - .to_db_struct()?; + .ok_or_else(|| anyhow::anyhow!("at least one template data is required"))? + .clone(); + let in_template_data = first_data.to_db_struct()?; let raw_wx_message_text = in_template_data .template_text .clone() - .unwrap() - .clone() + .ok_or_else(|| anyhow::anyhow!("template_text is required"))? .val - .unwrap(); + .ok_or_else(|| anyhow::anyhow!("template_text.val is required"))?; // let wrapped_data = SingleVal { // val: Some(raw_wx_message_data) // }; diff --git a/htyuc_remote/src/remote_calls.rs b/htyuc_remote/src/remote_calls.rs index 167fe8d..b089389 100644 --- a/htyuc_remote/src/remote_calls.rs +++ b/htyuc_remote/src/remote_calls.rs @@ -78,12 +78,16 @@ pub async fn find_app_by_domain( reason: Some("app not found".to_string()), })?; + let app_id = req_app.app_id + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let app_status = req_app.app_status + .ok_or_else(|| anyhow::anyhow!("app_status is required"))?; Ok(HtyApp { - app_id: req_app.app_id.unwrap(), + app_id, wx_secret: req_app.wx_secret, domain: req_app.domain, app_desc: req_app.app_desc, - app_status: req_app.app_status.unwrap(), + app_status, pubkey: req_app.pubkey, privkey: req_app.privkey, wx_id: req_app.wx_id, @@ -108,12 +112,16 @@ pub async fn find_app_by_id(id_app: &String, root: &HtySudoerTokenHeader) -> any reason: Some("to_app not found".to_string()), })?; + let app_id = req_app.app_id + .ok_or_else(|| anyhow::anyhow!("app_id is required"))?; + let app_status = req_app.app_status + .ok_or_else(|| anyhow::anyhow!("app_status is required"))?; Ok(HtyApp { - app_id: req_app.app_id.unwrap(), + app_id, wx_secret: req_app.wx_secret, domain: req_app.domain, app_desc: req_app.app_desc, - app_status: req_app.app_status.unwrap(), + app_status, pubkey: req_app.pubkey, privkey: req_app.privkey, wx_id: req_app.wx_id, @@ -133,17 +141,18 @@ pub async fn find_user_openid_by_hty_id_and_app( hty_user, req_user_infos ); - let user_infos = req_user_infos.unwrap(); + let user_infos = req_user_infos + .ok_or_else(|| anyhow::anyhow!("user_infos is required"))?; let to_user_openid = user_infos .iter() - .find(|user_info| user_info.app_id.as_ref().unwrap() == &to_app.app_id) + .find(|user_info| user_info.app_id.as_ref().map(|id| id == &to_app.app_id).unwrap_or(false)) .ok_or(HtyErr { code: HtyErrCode::NullErr, reason: Some("not found a user_app_info to_app!".into()), })? .openid .as_ref() - .unwrap(); + .ok_or_else(|| anyhow::anyhow!("openid is required"))?; Ok(to_user_openid.to_string()) } diff --git a/upyun_tool/src/upyun.rs b/upyun_tool/src/upyun.rs index da5c346..0c8e816 100644 --- a/upyun_tool/src/upyun.rs +++ b/upyun_tool/src/upyun.rs @@ -294,7 +294,8 @@ pub fn upyun_upt_download(url: &str, config_file: &str) -> Result<(), anyhow::Er if resp.status() == reqwest::StatusCode::OK { let path = Path::new(uri); - let local_file = path.file_name().unwrap(); + let local_file = path.file_name() + .ok_or_else(|| anyhow::anyhow!("Failed to get file name from path"))?; let mut file = std::fs::File::create(local_file)?; let mut content = Cursor::new(resp.bytes()?); std::io::copy(&mut content, &mut file)?;